用spring实现excel的导入

mac2024-05-08  35

用spring实现excel的导入

插入UML图

代码:

/** * 导入 * @param file * @param request * @throws IOException//抛出io异常 */ //前端调用的接口importExcel @RequestMapping(“importExcel”) @ResponseBody public Map<String,Object> importUsers(@RequestParam MultipartFile file,HttpServletRequest request) throws IOException { //保存到本地服务器,REIMBURSMENT_UPLOAD_PATH为自己设置的本地地址,可以在application-dev.yml中设置,如上图所示 List<Map<String,Object>> tempList = FileUtil.fileUpload(REIMBURSMENT_UPLOAD_PATH,".xls",request);

// 获取文件名 Map<String, Object> resultMap = Maps.newHashMap(); String fileName = file.getOriginalFilename(); if (StringUtils.isEmpty(fileName)) { resultMap.put("code", 1001); resultMap.put("message", "文件不能为空"); return resultMap; } // 获取文件后缀 String prefix = fileName.substring(fileName.lastIndexOf(".")); if (!prefix.toLowerCase().contains("xls") && !prefix.toLowerCase().contains("xlsx")) { resultMap.put("code", 1001); resultMap.put("message", "文件格式异常,请上传Excel文件格式"); return resultMap; } final File excelFile = File.createTempFile(System.currentTimeMillis() + "", prefix); file.transferTo(excelFile); //由于2003和2007的版本所使用的接口不一样,所以这里统一用Workbook做兼容 boolean isExcel2003 = prefix.toLowerCase().endsWith("xls") ? true : false; Workbook workbook = null; if (isExcel2003) { workbook = new HSSFWorkbook(new FileInputStream(excelFile)); } else { workbook = new XSSFWorkbook(new FileInputStream(excelFile)); } //Excel表中的内容 List<Map<String, Object>> list = new ArrayList<>(); Sheet sheet = workbook.getSheetAt(0); //这里从1开始,跳过了标题,直接从第二行开始解析 for (int i = 1; i < sheet.getLastRowNum() + 1; i++) { Row row = sheet.getRow(i); //设置行格式和验证start 这里最好做成一个方法,免得代码多处复制 if (row.getCell(0) != null) { row.getCell(0).setCellType(Cell.CELL_TYPE_STRING); } if (row.getCell(1) != null) { row.getCell(1).setCellType(Cell.CELL_TYPE_STRING); } if (row.getCell(2) != null) { row.getCell(2).setCellType(Cell.CELL_TYPE_STRING); } if (row.getCell(3) != null) { row.getCell(3).setCellType(Cell.CELL_TYPE_STRING); } String carnumber = row.getCell(0).getStringCellValue(); //汽车编号 String weight = row.getCell(1).getStringCellValue();//重量 String length = row.getCell(2).getStringCellValue();//长度 String seatnumber = row.getCell(3).getStringCellValue();//座位数量 //组装列表 Map<String, Object> map = new HashMap<>(); map.put("carnumber", carnumber); map.put("weight", weight); map.put("length", length); map.put("seatnumber", seatnumber); //放入list结合中 list.add(map); //调用一下save方法保存到数据库 tSchoolbusService.saveAll(list); } //删除临时转换的文件 if (excelFile.exists()) { excelFile.delete(); } //list就是具体内容,剩下的就是自己处理具体业务了 System.out.println("上传的内容就是这个了:" + list); return resultMap; }
最新回复(0)