Springboot3学习——POI实现导入导出(七)
1、POI介绍
Apache POI 是一种流行的 API,允许程序员使用 Java 程序创建、修改和显示 MS Office 文件。 它是由 Apache Software Foundation 开发和分发的开源库,用于使用 Java 程序设计或修改 Microsoft Office 文件。 它包含将用户输入数据或文件解码为 MS Office 文档的类和方法。
几乎所有的项目,都会涉及对office文件的操作,本文我们在springboot项目中,使用POI实现excel的导入导出功能
2、pom.xml添加依赖poi-ooxml
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.3.0</version> </dependency>
3、导入
1、controller层修改
@PostMapping(value="/users", consumes = "multipart/form-data") public String importUsers(@RequestPart MultipartFile file) { try { List<User> userList = userService.importUsers(file.getInputStream()); return "导入成功"; } catch (Exception e) { e.printStackTrace(); return "导入失败"; } }
2、serviceImpl层修改
@Override public List<User> importUsers(InputStream inputStream) throws Exception { List<User> userList = new ArrayList<>(); Workbook workbook = WorkbookFactory.create(inputStream); Sheet sheet = workbook.getSheetAt(0); // 假设用户信息在第一个 Sheet 中 Iterator<Row> rowIterator = sheet.iterator(); Date now=new Date(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); if (row.getRowNum() == 0) { // 跳过表头 continue; } User user = new User(); user.setUserid(new DataFormatter().formatCellValue(row.getCell(0))); user.setUsername(new DataFormatter().formatCellValue(row.getCell(1))); user.setDept(new DataFormatter().formatCellValue(row.getCell(2))); user.setPassword(new DataFormatter().formatCellValue(row.getCell(3))); user.setGender(new DataFormatter().formatCellValue(row.getCell(4))); user.setTransdatetime(now); user.setStatus("1"); user.setCreateuid("sys"); userList.add(user); } workbook.close(); userList.forEach(user -> userMapper.insert(user)); return userList; }
3、测试
运行,访问swagger,调用对应接口,成功,如下图
3、导出
1、controller层修改
@GetMapping("/users") public void exportUsers(HttpServletResponse response) { try { List<User> userList = userService.selectAll(); // 假设获取所有用户信息的方法 userService.exportUsers(userList, response); } catch (Exception e) { e.printStackTrace(); } }
2、serviceImpl层修改
@Override public void exportUsers(List<User> userList, HttpServletResponse response) throws Exception { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("用户信息"); // 创建表头 Row headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("USERID"); headerRow.createCell(1).setCellValue("USERNAME"); headerRow.createCell(2).setCellValue("DEPT"); headerRow.createCell(3).setCellValue("GENDER"); // 添加更多字段... // 写入数据 int rowNum = 1; for (User user : userList) { Row row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(user.getUserid()); row.createCell(1).setCellValue(user.getUsername()); row.createCell(2).setCellValue(user.getDept()); row.createCell(3).setCellValue(user.getGender()); } // 设置响应头 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); //response.setHeader("Content-Disposition","attachment;filename=用户表.xlsx"); response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("用户表.xlsx","UTF-8")); // 输出到响应流 workbook.write(response.getOutputStream()); workbook.close(); }
3、测试
运行,访问swagger,调用对应接口,准备导入excel,如下图
上传文件,导入成功
查看数据库,数据插入成功
标签:userList,createCell,导入,user,POI,new,Springboot3,row From: https://blog.csdn.net/weixin_38696566/article/details/143166287遇到的问题
ps:实际测试过程中,也是出现了一些问题,分享记录下
1、在导出时,因为设置的导出名称为中文,导致报如下错:
The Unicode character [用] at code point [29,992] cannot be encoded as it is outside the permitted range of 0 to 255
解决方法,中文编码为utf-8转码即可
response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("用户表.xlsx","UTF-8"));
2、导入时,报了如下错,
Cannot get a STRING value from a NUMERIC cell
原因是,我导入的模板,密码写的是123,识别为了int类型,做如下修改即可
user.setPassword(new DataFormatter().formatCellValue(row.getCell(3)));user.setPassword(row.getCell(3).getStringCellValue());