当前位置:   article > 正文

EasyExcel入门_easyexcel依赖

easyexcel依赖

EasyExcel特点

生成Excel比较有名的框架Apache poi、jxl等,但是他们都存在一个严重的问题就是非常的耗内存,如果系统并发量不大可能还行,但是一旦并发上来后一定会OOM或者JVM频繁的full gc

EasyExcel是阿里巴巴开源的一个excel处理框架,以使用简单、节省内存著称,EasyExcel能大大减少占用内存的主要原因是在解析Excel时没有将文件数据一次性全部加载到内存中,而是从磁盘上一行行读取数据,逐个解析

EasyExcel采用一行一行的解析模式,并将一行的解析结果以观察者的模式通知处理(AnalysisEventListener)

EasyExcel对poi进行封装, 采用SAX方式解析

Dom方式(一次性将Excel中的内容全部放到内存中来,再进行读取),缺点就是数据量大的话会很影响效率

SAX方式(一行一行的解析模式,并将一行的解析结果以观察者的模式通知处理(AnalysisEventListener) ,能够大大提高效率,不会产生什么内存溢出问题)

引入依赖

  1. <dependencies> <!--easyexcel依赖-->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>easyexcel</artifactId>
  5. <version>2.1.1</version>
  6. </dependency>
  7. </dependencies>
  8. <!--同时也需要引入下面这两个依赖,poi 3.17版本和easyexcel 2.1.1版本比较契合-->
  9. <poi.version>3.17</poi.version>
  10. <!--xls-->
  11. <dependency>
  12. <groupId>org.apache.poi</groupId>
  13. <artifactId>poi</artifactId>
  14. </dependency>
  15. <dependency>
  16. <groupId>org.apache.poi</groupId>
  17. <artifactId>poi-ooxml</artifactId>
  18. </dependency>

EasyExcel进行写操作

创建一个实体

  1. @Data
  2. //@Accessors(chain = true)
  3. //要去掉这个连缀书写的注解,因为Accessors和EasyExcel冲突,一行一行读取的时候会返回null
  4. public class DemoData {
  5. //设置excel表头名称
  6. @ExcelProperty("学生编号")
  7. private Integer sno;
  8. @ExcelProperty("学生姓名")
  9. private String sname;
  10. }

实现写操作方法

  1. public class TestEasyExcel {
  2. public static void main(String[] args) {
  3. //实现Excel写的操作
  4. String filename = "D:\\write.xlsx";
  5. //调用EasyExcel里面的方法实现写操作
  6. //write两个参数,第一个参数文件路径名称,第二个参数实体类, .sheet给sheet页设置名称 .doWrite传需要写入的List
  7. EasyExcel.write(filename,DemoData.class).sheet("学生列表").doWrite(getDate());
  8. //第二种写法
  9. // ExcelWriter excelWriter = EasyExcel.write(filename, DemoData.class).build();
  10. // WriteSheet writeSheet = EasyExcel.writerSheet("方法二").build();
  11. // excelWriter.write(getDate(), writeSheet);
  12. // //需要手动关闭,第一种不需要
  13. // excelWriter.finish();
  14. }
  15. //创建方法返回List集合
  16. private static List<DemoData> getDate(){
  17. List<DemoData> list = new ArrayList<>();
  18. for (int i = 0; i < 10;i++){
  19. DemoData demoData = new DemoData();
  20. demoData.setSno(i);
  21. demoData.setSname("lucy" + i);
  22. list.add(demoData);
  23. }
  24. return list;
  25. }
  26. }

前端页面导出Excel

  1. import com.alibaba.excel.EasyExcel;
  2. import com.alibaba.excel.ExcelWriter;
  3. import com.alibaba.excel.write.metadata.WriteSheet;
  4. import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import javax.servlet.http.HttpServletResponse;
  9. import java.io.IOException;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. @RestController
  13. @RequestMapping("/excel")
  14. public class ExcelController {
  15. @GetMapping("/exportExcel")
  16. public void exportExcel(HttpServletResponse response) throws IOException {
  17. response.setContentType("application/octet-stream");
  18. // servletResponse.setContentType("application/vnd.ms-excel");
  19. response.setHeader("Content-Disposition", "attachment;fileName=" +
  20. new String("模板名称.xlsx".getBytes("gbk"), "iso8859-1"));
  21. //第一种导出方式
  22. // EasyExcel.write(response.getOutputStream(), DemoData.class)
  23. // //设置自适应列宽
  24. // .head(DemoData.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
  25. // .sheet(0, "学生列表1").doWrite(getData());
  26. //第二种导出方式
  27. //导出多个sheet页
  28. ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), DemoData.class)
  29. //设置自适应列宽
  30. .head(DemoData.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
  31. .build();
  32. WriteSheet writeSheet = EasyExcel.writerSheet(0, "学生列表1").build();
  33. excelWriter.write(getData(), writeSheet);
  34. WriteSheet writeSheet2 = EasyExcel.writerSheet(1, "学生列表2")
  35. .head(DemoData.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
  36. .build();
  37. excelWriter.write(getData(), writeSheet2);
  38. excelWriter.finish();
  39. }
  40. public List<DemoData> getData() {
  41. List<DemoData> list = new ArrayList<>();
  42. for (int i = 0; i < 10; i++) {
  43. DemoData demoData = new DemoData();
  44. demoData.setSno(i);
  45. demoData.setSname("name" + i);
  46. list.add(demoData);
  47. }
  48. return list;
  49. }
  50. }

EasyExcel进行读操作

实体

  1. @Data
  2. //@Accessors(chain = true)
  3. //要去掉这个连缀书写的注解,因为Accessors和EasyExcel冲突,一行一行读取的时候会返回null
  4. public class DemoData {
  5. //value对应excel表头名称,index对应表中的列,0代表第一列
  6. @ExcelProperty(value = "学生编号",index = 0)
  7. private Integer sno;
  8. @ExcelProperty(value = "学生姓名",index = 1)
  9. private String sname;
  10. }

创建读取操作的监听器

  1. public class ExcelListener extends AnalysisEventListener<DemoData> { //放入接收excel的实体
  2. //一行一行读取excel内容
  3. @Override
  4. public void invoke(DemoData data, AnalysisContext analysisContext) {
  5. System.out.println("***" + data);
  6. }
  7. //读取excel表头内容
  8. @Override
  9. public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
  10. System.out.println("表头:" + headMap);
  11. }
  12. //读取完成之后
  13. @Override
  14. public void doAfterAllAnalysed(AnalysisContext analysisContext) {
  15. }
  16. }

实现excel读操作

  1. public class TestEasyExcel {
  2. public static void main(String[] args) {
  3. //实现Excel读操作
  4. String filename = "D:\\write.xlsx";
  5. //文件路径,实体,监听器
  6. EasyExcel.read(filename,DemoData.class,new ExcelListener()).sheet().doRead();
  7. }
  8. }

示例:

  1. @Override
  2. public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {
  3. try {
  4. InputStream inputStream = file.getInputStream();
  5. EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(eduSubjectService))
  6. .sheet().doRead();
  7. }catch (Exception e){
  8. e.printStackTrace();
  9. }
  10. }
  1. public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
  2. public EduSubjectService eduSubjectService;
  3. public SubjectExcelListener() {}
  4. public SubjectExcelListener(EduSubjectService eduSubjectService){
  5. this.eduSubjectService = eduSubjectService;
  6. }
  7. @Override
  8. public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
  9. if (subjectData ==null)
  10. throw new GuliException(20001,"读取文件为空");
  11. EduSubject oneEduSubject = getOneEduSubject(eduSubjectService, subjectData.getOneSubjectName());
  12. if (oneEduSubject == null){
  13. oneEduSubject = new EduSubject();
  14. oneEduSubject.setTitle(subjectData.getOneSubjectName());
  15. oneEduSubject.setParentId("0");
  16. eduSubjectService.save(oneEduSubject);
  17. }
  18. String pid = oneEduSubject.getId();
  19. EduSubject twoEduSubject = getTwoEduSubject(eduSubjectService, subjectData.getTwoSubjectName(), pid);
  20. if (twoEduSubject == null){
  21. twoEduSubject = new EduSubject();
  22. twoEduSubject.setTitle(subjectData.getTwoSubjectName());
  23. twoEduSubject.setParentId(pid);
  24. eduSubjectService.save(twoEduSubject);
  25. }
  26. }
  27. private EduSubject getOneEduSubject(EduSubjectService eduSubjectService,String name){
  28. QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
  29. queryWrapper.eq("parent_id","0");
  30. queryWrapper.eq("title",name);
  31. EduSubject one = eduSubjectService.getOne(queryWrapper);
  32. return one;
  33. }
  34. private EduSubject getTwoEduSubject(EduSubjectService eduSubjectService,String name,String pid){
  35. QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
  36. queryWrapper.eq("parent_id",pid);
  37. queryWrapper.eq("title",name);
  38. EduSubject one = eduSubjectService.getOne(queryWrapper);
  39. return one;
  40. }
  41. @Override
  42. public void doAfterAllAnalysed(AnalysisContext analysisContext) {
  43. }
  44. }

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

闽ICP备14008679号