**Controller层** @PostMapping("/excelupload") public JsonResultEntity excelupload(@RequestParam("file") MultipartFile file) { return excelService.analysisExcel(file); }
**Service层** @Override public JsonResultEntity analysisExcel(MultipartFile file) { //获取文件名称 String fileName = file.getOriginalFilename(); if (StringUtils.isEmpty(fileName)){ return new JsonResultEntity("","文件不能为空"); } // 获取文件后缀 String prefix=fileName.substring(fileName.lastIndexOf(".")); if (!prefix.toLowerCase().contains("xls") && !prefix.toLowerCase().contains("xlsx") ) { return new JsonResultEntity("","文件格式异常,请上传Excel文件格式"); } //Excel文件--得到Excel工作簿对象 Map<String,Object> map = new HashMap<>(); try { //兼容2003及2007 boolean isExcel2003 = true; if (fileName.matches("^.+\\.(?i)(xlsx)$")) { isExcel2003 = false; } InputStream is = file.getInputStream(); Workbook wb = null; if (isExcel2003) { wb = new HSSFWorkbook(is); } else { wb = new XSSFWorkbook(is); } Sheet sheet = wb.getSheetAt(0); int coloumNum = sheet.getRow(0).getPhysicalNumberOfCells(); int rowNum = sheet.getLastRowNum(); //XSSFRow row = null; List<String> list = new ArrayList<>(); for (int i = 0; i < coloumNum; i++) { Row row = sheet.getRow(0); String string = row.getCell(i).toString(); list.add(string); } map.put("colNum",rowNum); map.put("list",list); return new JsonResultEntity(map); } catch (IOException e) { e.printStackTrace(); return new JsonResultEntity("","解析失败"); } }