当前位置:   article > 正文

EasyExcel的数据写入和导出_easyexcel.write

easyexcel.write

目录

总体效果:

要上传的excel文件

postman请求服务器上传

写入数据库成功!

1.上传excel代码部分

引入easyexcel依赖

实体类

上传代码,此处为核心代码,每五条插入一次数据库:

StudentPutReadMapper部分:

 结果:

1.2.自定义Listener实现拓展业务

结果 

2.下载数据库导出excel

实体类

代码如下,关注核心部分即可

导出效果


总体效果:

要上传的excel文件

postman请求服务器上传

写入数据库成功!

1.上传excel代码部分

引入easyexcel依赖

  1. <!-- easyexcel 依赖 -->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>easyexcel</artifactId>
  5. <version>2.2.7</version>
  6. </dependency>

实体类

上传代码,此处为核心代码,每五条插入一次数据库:

  1. @ApiOperation(value = "上传Excel")
  2. @GetMapping("put")
  3. public ResponseResult putExcel(@RequestParam("file") MultipartFile file) {
  4. List<StudentPutFileRead> studentPutFileReadList = new ArrayList<>();
  5. InputStream inputStream = null;
  6. try {
  7. inputStream = file.getInputStream();
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. EasyExcel.read(inputStream, StudentPutFileRead.class, new AnalysisEventListener<StudentPutFileRead>() {
  12. @Override
  13. public void invoke(StudentPutFileRead studentPutFileRead, AnalysisContext analysisContext) {
  14. studentPutFileReadList.add(studentPutFileRead);
  15. if (studentPutFileReadList.size() == 5){
  16. //批量插入数据库
  17. studentPutReadMapper.batchInsert(studentPutFileReadList);
  18. }
  19. // 清空集合
  20. studentPutFileReadList.clear();
  21. }
  22. @Override
  23. public void doAfterAllAnalysed(AnalysisContext analysisContext) {
  24. }
  25. }).sheet().doRead();
  26. return new ResponseResult(200, "插入数据库成功");
  27. }

StudentPutReadMapper部分:

  1. /**
  2. * @author yt
  3. * @create 2022/5/12 15:07
  4. */
  5. @Mapper
  6. public interface StudentPutReadMapper extends BaseMapper<StudentPutFileRead> {
  7. @Insert({
  8. "<script>",
  9. "insert into student_read(name,salary,birthday) values ",
  10. "<foreach collection='insertList' item='item' separator=','>",
  11. "(#{item.name}, #{item.salary}, #{item.birthday})",
  12. "</foreach>",
  13. "</script>"
  14. })
  15. void batchInsert(@Param("insertList") List<StudentPutFileRead> studentPutFileReadList);
  16. }

 结果:

1.2.自定义Listener实现拓展业务

自定义StudentListener 继承 AnalysisEventListener<StudentRead>

  1. /**
  2. * @author yt
  3. * @create 2022/10/27 16:50
  4. */
  5. public class StudentListener extends AnalysisEventListener<StudentRead> {
  6. private StudentReadMapper studentReadMapper = MyApplicationContext.getBean(StudentReadMapper.class);
  7. //集合数量
  8. private Integer NUM = 5;
  9. //读取第几条
  10. private static int READ_COUNT = 0;
  11. private ArrayList<StudentRead> studentReadList = new ArrayList<>();
  12. @Override
  13. public void invoke(StudentRead studentRead, AnalysisContext analysisContext) {
  14. READ_COUNT++;
  15. System.out.println("读取数据行数 = " + READ_COUNT);
  16. studentReadList.add(studentRead);
  17. if (studentReadList.size() == NUM) {
  18. for (StudentRead read : studentReadList) {
  19. studentReadMapper.insert(read);
  20. }
  21. studentReadList.clear();
  22. }
  23. System.out.println(studentReadList.size());
  24. }
  25. @Override
  26. public void doAfterAllAnalysed(AnalysisContext analysisContext) {
  27. System.out.println("共导入 = " + READ_COUNT + "条数据");
  28. }
  29. }

在自定义的监听器中,无法实现类的注入,需要从ApplicationContext中获取,具体说明在我的另一篇博客中

 在EasyExcel.read中即可使用自定义的监听器

  1. @GetMapping("test3")
  2. public ResponseResult userTest3(@RequestParam("file") MultipartFile file) {
  3. List<StudentRead> list = new ArrayList<>();
  4. InputStream inputStream = null;
  5. try {
  6. inputStream = file.getInputStream();
  7. } catch (IOException e) {
  8. e.printStackTrace();
  9. }
  10. //使用自定义的监听器
  11. EasyExcel.read(inputStream, StudentRead.class, new StudentListener()).sheet().doRead();
  12. return new ResponseResult(200, "上传成功", list);
  13. }

结果 

2.下载数据库导出excel

实体类

  1. @Data
  2. @TableName("student_read")
  3. public class StudentRead implements Serializable {
  4. @ExcelProperty(value = {"学生信息","学生编号"})
  5. private Integer id;
  6. @ExcelProperty(value = {"学生信息","学生姓名"})
  7. private String name;
  8. @ExcelProperty(value = {"学生信息","学生薪水"})
  9. private Double salary;
  10. @ExcelProperty(value = {"学生信息","学生生日"})
  11. private Date birthday;
  12. }

代码如下,关注核心部分即可(此为window指定用户保存路径的写法)

  1. /**
  2. * 下载excel
  3. *
  4. * @param
  5. * @return
  6. */
  7. @ApiOperation(value = "下载Excel")
  8. @GetMapping("down")
  9. public ResponseResult downExcel() {
  10. Random random = new Random(8);
  11. // 下载的地址以及名称
  12. String PATH = "F:\\文件\\excel下载\\学生测试";
  13. // 查询数据库
  14. List<StudentRead> list = studentReadMapper.selectList(null);
  15. // 核心代码
  16. EasyExcel.write(PATH + ".xlsx", StudentRead.class)
  17. .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
  18. .sheet().doWrite(list);
  19. return new ResponseResult(200, "下载成功");
  20. }

 可以用导出流的形式导出excel,代码如下

  1. @GetMapping("down")
  2. public ApiResponse downloadExcel(HttpServletResponse response) throws IOException {
  3. List<OrderDO> orderDOList = orderService.findAll();
  4. String fileName = URLEncoder.encode("名字", "UTF-8");
  5. response.setContentType("application/vnd.ms-excel");
  6. response.setCharacterEncoding("utf-8");
  7. response.setContentType("application/force-download");
  8. response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
  9. response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
  10. response.setHeader("Content-Type","application/octet-stream;charset=utf-8");
  11. /**导入结果流*/
  12. EasyExcel.write(response.getOutputStream(), DownloadExcel.class).sheet("名字").
  13. registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).doWrite(orderDOList);
  14. return ApiResponse.success("下载成功");
  15. }

此方法postman导出会有文件名乱码的问题,如果是浏览器下载的话,文件名是没有问题的。

导出效果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/tf789/article/detail/61106
推荐阅读
相关标签
  

闽ICP备14008679号