当前位置:   article > 正文

easyexcel_语雀easyexcel

语雀easyexcel

目录:

1.easyexcel

2.easyexcel的写操作

3.easyexcel写操作--web模式

4.easyexcel完成读操作

5.easyexcel读操作--web模式


1.easyexcel

   EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目。 在尽可能节约内存的情况下支持读写百M的Excel。github地址:https://github.com-alibaba/easyexcel

我们现在用这个网站写excel(文档已经迁移) · 语雀EasyExcel写Excel的示例https://www.yuque.com/easyexcel/doc/write通过java代码完成对Excel的读写操作。 所谓的读写理解为上传和下载

2.easyexcel写操作

所谓的写操作就是把java中的类对象写入到excel表格中
 

 实现步骤:

1.引入相关依赖 2.配置相应的实体类 3.通过excel进行写入操作

1.引入相关依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.3.12.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.hql</groupId>
  12. <artifactId>spring-easyexcel</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>spring-easyexcel</name>
  15. <description>spring-easyexcel</description>
  16. <properties>
  17. <java.version>8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-web</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.projectlombok</groupId>
  26. <artifactId>lombok</artifactId>
  27. <optional>true</optional>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-test</artifactId>
  32. <scope>test</scope>
  33. </dependency>
  34. <dependency>
  35. <groupId>com.alibaba</groupId>
  36. <artifactId>easyexcel</artifactId>
  37. <version>3.1.2</version>
  38. </dependency>
  39. <dependency>
  40. <groupId>com.alibaba</groupId>
  41. <artifactId>fastjson</artifactId>
  42. <version>1.2.62</version>
  43. </dependency>
  44. <dependency>
  45. <groupId>com.baomidou</groupId>
  46. <artifactId>mybatis-plus-boot-starter</artifactId>
  47. <version>3.5.1</version>
  48. </dependency>
  49. <dependency>
  50. <groupId>mysql</groupId>
  51. <artifactId>mysql-connector-java</artifactId>
  52. </dependency>
  53. </dependencies>
  54. <build>
  55. <plugins>
  56. <plugin>
  57. <groupId>org.springframework.boot</groupId>
  58. <artifactId>spring-boot-maven-plugin</artifactId>
  59. <configuration>
  60. <excludes>
  61. <exclude>
  62. <groupId>org.projectlombok</groupId>
  63. <artifactId>lombok</artifactId>
  64. </exclude>
  65. </excludes>
  66. </configuration>
  67. </plugin>
  68. </plugins>
  69. </build>
  70. </project>

2.配置相应的实体类

  1. package com.hql.excel;
  2. import com.alibaba.excel.annotation.ExcelIgnore;
  3. import com.alibaba.excel.annotation.ExcelProperty;
  4. import com.baomidou.mybatisplus.annotation.IdType;
  5. import com.baomidou.mybatisplus.annotation.TableId;
  6. import com.baomidou.mybatisplus.annotation.TableName;
  7. import lombok.AllArgsConstructor;
  8. import lombok.Data;
  9. import lombok.NoArgsConstructor;
  10. /**
  11. * @program: spring-easyexcel
  12. * @description:
  13. * @author:
  14. * @create: 2023-04-28 14:51
  15. **/
  16. @Data
  17. @AllArgsConstructor
  18. @NoArgsConstructor
  19. @TableName
  20. public class ExcelDemo {
  21. @ExcelProperty("ID")//标记excel标题内容
  22. @TableId(type = IdType.AUTO)
  23. private int id;
  24. @ExcelProperty("姓名")
  25. private String ename;
  26. @ExcelProperty("年龄")
  27. private int age;
  28. // @ExcelIgnore 该属性不写入excel表格里
  29. }

3.通过excel进行写入操作

这里的data,以后我们可以通过查询数据库

  1. package com.hql.excel;
  2. import com.alibaba.excel.EasyExcel;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. /**
  6. * @program: spring-easyexcel
  7. * @description:
  8. * @author:
  9. * @create: 2023-04-28 14:54
  10. **/
  11. public class TestWrite {
  12. public static void main(String[] args) {
  13. String fileName = "D:\\maven\\apache-maven-3.8.6\\conf\\spring-easyexcel\\mingren.xls";
  14. // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
  15. // 如果这里想使用03 则 传入excelType参数即可
  16. List<ExcelDemo> data=new ArrayList<>();
  17. data.add(new ExcelDemo(1,"李白",18));
  18. data.add(new ExcelDemo(2,"杜甫",18));
  19. data.add(new ExcelDemo(3,"辛弃疾",18));
  20. data.add(new ExcelDemo(4,"苏轼",18));
  21. EasyExcel.write(fileName, ExcelDemo.class).sheet("ok").doWrite(data);
  22. }
  23. }

运行后 

 3.easyexcel写操作web模式

  1. package com.ykq.qy163easyexcel.controller;
  2. import com.alibaba.excel.EasyExcel;
  3. import com.alibaba.excel.util.MapUtils;
  4. import com.alibaba.fastjson.JSON;
  5. import com.ykq.qy163easyexcel.dao.UserDao;
  6. import com.ykq.qy163easyexcel.excel.ExcelDemo;
  7. import com.ykq.qy163easyexcel.listener.UserDataListener;
  8. import com.ykq.qy163easyexcel.pojo.User;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.web.bind.annotation.GetMapping;
  12. import org.springframework.web.bind.annotation.PostMapping;
  13. import org.springframework.web.bind.annotation.ResponseBody;
  14. import org.springframework.web.multipart.MultipartFile;
  15. import javax.servlet.http.HttpServletResponse;
  16. import java.io.IOException;
  17. import java.net.URLEncoder;
  18. import java.util.ArrayList;
  19. import java.util.List;
  20. import java.util.Map;
  21. /**
  22. * @program: qy163-easyexcel
  23. * @description:
  24. * @author:
  25. * @create: 2023-04-28 15:06
  26. **/
  27. @Controller
  28. public class UploadController {
  29. @GetMapping("/upload")
  30. public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
  31. // 这里需要设置不关闭流
  32. List<ExcelDemo> data=new ArrayList<>();
  33. data.add(new ExcelDemo(1,"李白",18));
  34. data.add(new ExcelDemo(2,"杜甫",18));
  35. data.add(new ExcelDemo(3,"辛弃疾",18));
  36. data.add(new ExcelDemo(4,"苏轼",18));
  37. upload(response,"今天放假",data);
  38. }
  39. public void upload(HttpServletResponse response,String title,List<?> data) throws IOException{
  40. // 这里注意 使用swagger 会导致各种问题,请直接用浏览器或者用postman
  41. try {
  42. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  43. response.setCharacterEncoding("utf-8");
  44. // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
  45. String fileName = URLEncoder.encode("qy163下载学员信息", "UTF-8").replaceAll("\\+", "%20");
  46. response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
  47. EasyExcel.write(response.getOutputStream(), ExcelDemo.class).autoCloseStream(Boolean.FALSE).sheet("模板")
  48. .doWrite(data);
  49. } catch (Exception e) {
  50. // 重置response
  51. response.reset();
  52. response.setContentType("application/json");
  53. response.setCharacterEncoding("utf-8");
  54. Map<String, String> map = MapUtils.newHashMap();
  55. map.put("status", "failure");
  56. map.put("message", "下载文件失败" + e.getMessage());
  57. response.getWriter().println(JSON.toJSONString(map));
  58. }
  59. }
  60. }

4.easyexcel完成读操作

 1.监听器

  1. package com.hql.listener;
  2. import com.alibaba.excel.context.AnalysisContext;
  3. import com.alibaba.excel.read.listener.ReadListener;
  4. import com.alibaba.excel.util.ListUtils;
  5. import com.alibaba.fastjson.JSON;
  6. import com.hql.dao.ExcelDao;
  7. import com.hql.excel.ExcelDemo;
  8. import lombok.extern.slf4j.Slf4j;
  9. import java.util.List;
  10. /**
  11. * @program: spring-easyexcel
  12. * @description:
  13. * @author:
  14. * @create: 2023-04-28 16:30
  15. **/
  16. @Slf4j
  17. public class ExcelListener implements ReadListener<ExcelDemo> {
  18. /**
  19. * 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
  20. */
  21. private static final int BATCH_COUNT = 100;
  22. /**
  23. * 缓存的数据
  24. */
  25. private List<ExcelDemo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
  26. /**
  27. * 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
  28. */
  29. private ExcelDao excelDao;
  30. public ExcelListener() {
  31. // 这里是demo,所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数
  32. // excelDao = new ExcelDao();
  33. }
  34. /**
  35. * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
  36. *
  37. * @param excelDao
  38. */
  39. public ExcelListener(ExcelDao excelDao) {
  40. this.excelDao = excelDao;
  41. }
  42. /**
  43. * 这个每一条数据解析都会来调用
  44. *
  45. * @param data one row value. Is is same as {@link AnalysisContext#readRowHolder()}
  46. * @param context
  47. */
  48. @Override
  49. public void invoke(ExcelDemo data, AnalysisContext context) {
  50. log.info("解析到一条数据:{}", JSON.toJSONString(data));
  51. cachedDataList.add(data);
  52. // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
  53. if (cachedDataList.size() >= BATCH_COUNT) {
  54. saveData();
  55. // 存储完成清理 list
  56. cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
  57. }
  58. }
  59. /**
  60. * 所有数据解析完成了 都会来调用
  61. *
  62. * @param context
  63. */
  64. @Override
  65. public void doAfterAllAnalysed(AnalysisContext context) {
  66. // 这里也要保存数据,确保最后遗留的数据也存储到数据库
  67. saveData();
  68. log.info("所有数据解析完成!");
  69. }
  70. /**
  71. * 加上存储数据库
  72. */
  73. private void saveData() {
  74. log.info("{}条数据,开始存储数据库!", cachedDataList.size());
  75. excelDao.batchSave(cachedDataList);
  76. log.info("存储数据库成功!");
  77. }
  78. }

2.dao层

  1. package com.hql.dao;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.hql.excel.ExcelDemo;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import java.util.List;
  6. /**
  7. * @program: spring-easyexcel
  8. * @description:
  9. * @author:
  10. * @create: 2023-04-28 16:36
  11. **/
  12. @Mapper
  13. public interface ExcelDao extends BaseMapper<ExcelDemo>{
  14. void batchSave(List<ExcelDemo> cachedDataList);
  15. }

3.测试层

  1. package com.hql.excel;
  2. import com.alibaba.excel.EasyExcel;
  3. import com.hql.dao.ExcelDao;
  4. import com.hql.listener.ExcelListener;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import java.io.File;
  7. /**
  8. * @program: spring-easyexcel
  9. * @description:
  10. * @author:
  11. * @create: 2023-04-28 16:18
  12. **/
  13. public class TestRead {
  14. // @Autowired
  15. // private ExcelDao excelDao;
  16. public static void main(String[] args) {
  17. String fileName = "D:\\maven\\apache-maven-3.8.6\\conf\\spring-easyexcel\\mingre.xls";
  18. // 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
  19. EasyExcel.read(fileName, ExcelDemo.class, new ExcelListener()).sheet().doRead();
  20. }
  21. }

 easyexce读操作web模式

  1. package com.hql.controller;
  2. import com.alibaba.excel.EasyExcel;
  3. import com.alibaba.excel.util.MapUtils;
  4. import com.alibaba.fastjson.JSON;
  5. import com.hql.dao.ExcelDao;
  6. import com.hql.excel.ExcelDemo;
  7. import com.hql.listener.ExcelListener;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.web.bind.annotation.GetMapping;
  10. import org.springframework.web.bind.annotation.PostMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12. import org.springframework.web.multipart.MultipartFile;
  13. import javax.servlet.http.HttpServletResponse;
  14. import java.io.IOException;
  15. import java.net.URLEncoder;
  16. import java.util.ArrayList;
  17. import java.util.List;
  18. import java.util.Map;
  19. /**
  20. * @program: spring-easyexcel
  21. * @description:
  22. * @author:
  23. * @create: 2023-04-28 15:15
  24. **/
  25. @RestController
  26. public class ExcelController {
  27. /**
  28. * 文件上传
  29. */
  30. @Autowired
  31. private ExcelDao excelDao;
  32. @PostMapping("upload2")
  33. public String upload2(MultipartFile file) throws IOException {
  34. EasyExcel.read(file.getInputStream(), ExcelDemo.class, new ExcelListener(excelDao)).sheet().doRead();
  35. return "success";
  36. }
  37. }

通过postman进行测试

 查看数据库

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号