• java读取Excel文件并各方案对比


    前言

            java程序员经常会做一些报表导入的工作,比如历史数据迁移,批量数据导入等等都会需要。曾经我遇到过一场面试。面试官问我在哪些地方使用过多线程。我顺口提了一句在表格导入的时候也使用过。然后就开始鬼畜了:

            1.你解决了10w数据的导入,那你有试过100w,1000w,一个亿,甚至更大吗?

            2.这么多数据,多线程处理会不会重复操作?

            3.一个亿的数据,网络请求能抗住吗?你的内存能抗住吗?

            。。。。。

    解决不了问题就解决出问题的人,我想打人

            其实这些问题对我而言还算是受益匪浅,很多事情可能看起来是比较简单,但是我们从来没有考虑过如果量变引起质变,我们能不能保证我们程序的健壮性?接下来就是根据自己的经验对如何导入数据做一些简单的记录,也希望能对别人有所帮助或者启发。当然,欢迎有更好的解决方案不断学习,不断超越,数据没有上限,我们的解决方案也永远没有上限!

    本文源码先给出来一下:阿里云盘分享

    POI

            我所了解过的读取表格的方式有jxl,和poi的方式。记得以前开始工作的时候是用的jxl方式,而且当时也有很多错误,比如excel版本需要2003  不支持2007以上(被这个bug支配过)。当然这么多年也没有再玩过了,据说是没更新了,所以就不再说明了,只对poi方式说明一下

            简单说明下原理读取步骤:        

            1.加载文件路径、获取流

            2.创建工作簿

            3.取表

            4.取行

            5.取单元格

    单线程处理

    直接上代码:

    1. /**
    2. * @Author andy
    3. * @Description 文件读取 poi方式,并写入数据库
    4. * @Date 11:37 2022/10/27
    5. * @Param [file]
    6. * @return boolean
    7. **/
    8. @Override
    9. public boolean poiFileRead(MultipartFile file){
    10. // readGoodOutOf(file); //单条新增 本地数据库不存在网络问题,所以与批量操作效率差距不明显
    11. try {
    12. XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());//从文件流中创建工作簿
    13. XSSFSheet sheet = workbook.getSheetAt(0);//获取表格
    14. int lastRowNum = sheet.getLastRowNum();//所有行数
    15. int row = 0;
    16. while (row<=lastRowNum){
    17. //循环读取,每次处理1000条
    18. saveBatch(readGoodWhile(sheet,row,1000,lastRowNum));
    19. row+=1000;
    20. }
    21. }catch (Exception e){
    22. e.printStackTrace();
    23. }
    24. return true;
    25. }
    26. /**
    27. * @Author andy
    28. * @Description //循环读取实体
    29. * @Date 11:41 2022/10/27
    30. * @Param [file]
    31. * @return java.util.List
    32. **/
    33. @Async("myThreadPoolExecutor")
    34. public List readGoodWhile(XSSFSheet sheet,int begin,int lengths,int lastRowNum){
    35. List list = new ArrayList<>();
    36. try {
    37. //分行和列读取
    38. for(int row = begin; row < (begin+lengths) && row<=lastRowNum; row++) {
    39. //节省篇幅,没有写完出来,最后会把源码和测试结果给出来
    40. //读取每行,每个单元格
    41. SupplierGoodCopy area = new SupplierGoodCopy( sheet.getRow(row).getCell(0)==null?"":sheet.getRow(row).getCell(0).getStringCellValue(),
    42. );
    43. list.add(area);
    44. }
    45. } catch (Exception e){
    46. e.printStackTrace();
    47. }
    48. return list;
    49. }

    先简单解释一下,大体步骤是上面的五部,先加载到内存,然后再循环读取,批量新增。这里面有一些弊端,可以思考下

    看下实测的结果:5w多条数据

    1.单条新增的结果

     2.多条新增的结果

     可以看到,单条比多条的新增慢了一些。其实这个速度并不准确。因为我本地测试的,数据库也是本地,以前我试过链接公网数据库,两个的速度差距能达到N多倍,原因是因为网络请求的缘故,如果单条新增,1000条就会有1000次网络io,而批量只需要一次io。这是第一个需要关注的点

    多线程处理

    1. package com.file.config;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.Configuration;
    4. import org.springframework.scheduling.annotation.EnableAsync;
    5. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    6. import java.util.concurrent.Executor;
    7. /**
    8. * 线程池定义
    9. */
    10. @Configuration
    11. @EnableAsync
    12. public class ThreadPoolConfig {
    13. @Bean("myThreadPoolExecutor")
    14. public Executor threadPoolExecutor(){
    15. ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    16. taskExecutor.setCorePoolSize(1);//核心线程数
    17. taskExecutor.setMaxPoolSize(10);//最大线程数
    18. taskExecutor.setQueueCapacity(100);//队列大小
    19. taskExecutor.setKeepAliveSeconds(60);//保持存活时长
    20. taskExecutor.setThreadNamePrefix("threadPoolExecutor-");//名称前缀
    21. //下面两个是线程关闭需要注意的问题
    22. taskExecutor.setWaitForTasksToCompleteOnShutdown(true);//线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean,默认false
    23. taskExecutor.setAwaitTerminationSeconds(60);//设置线程池中 任务的等待时间,如果超过这个时间还没有销毁就 强制销毁,以确保应用最后能够被关闭,而不是阻塞住。
    24. return taskExecutor;
    25. }
    26. }
    1. package com.file.business;
    2. import com.alibaba.excel.util.ListUtils;
    3. import com.file.entity.SupplierGoodCopy;
    4. import com.file.mapper.SupplierGoodCopyMapper;
    5. import com.file.service.SupplierGoodCopyService;
    6. import lombok.Data;
    7. import lombok.extern.slf4j.Slf4j;
    8. import org.apache.poi.xssf.usermodel.XSSFSheet;
    9. import java.math.BigDecimal;
    10. import java.util.ArrayList;
    11. import java.util.Date;
    12. import java.util.List;
    13. /**
    14. * @ClassName BatchInsert
    15. * @Description 批量新增
    16. * @Author andy
    17. * @Date 2022/10/28 9:58
    18. * @Version 1.0
    19. */
    20. @Data
    21. @Slf4j
    22. public class BatchInsert implements Runnable{
    23. private XSSFSheet sheet;
    24. private int begin;
    25. private int lengths;
    26. private int lastRowNum;
    27. private SupplierGoodCopyService service;
    28. public BatchInsert(XSSFSheet sheet, int begin, int lengths, int lastRowNum, SupplierGoodCopyService service) {
    29. this.sheet = sheet;
    30. this.begin = begin;
    31. this.lengths = lengths;
    32. this.lastRowNum = lastRowNum;
    33. this.service = service;
    34. }
    35. @Override
    36. public void run() {
    37. log.info("启动线程处理");
    38. List list = new ArrayList<>();
    39. try {
    40. int i = 0;
    41. //分行和列读取
    42. for(int row = begin; row < (begin+lengths) && row<=lastRowNum; row++) {
    43. SupplierGoodCopy area = new SupplierGoodCopy(
    44. sheet.getRow(row).getCell(0)==null?"":sheet.getRow(row).getCell(0).getStringCellValue()
    45. );
    46. list.add(area);
    47. i++;
    48. if(i>=1000){
    49. service.saveBatch(list);
    50. list = ListUtils.newArrayListWithExpectedSize(i);
    51. i=0;
    52. }
    53. }
    54. } catch (Exception e){
    55. e.printStackTrace();
    56. }
    57. service.saveBatch(list);
    58. }
    59. }

     

    1. @Autowired
    2. Executor myThreadPoolExecutor;
    3. /**
    4. * @Author andy
    5. * @Description 文件读取 poi方式,并写入数据库
    6. * @Date 11:37 2022/10/27
    7. * @Param [file]
    8. * @return boolean
    9. **/
    10. @Override
    11. public boolean poiFileRead(MultipartFile file){
    12. // readGoodOutOf(file); //单条新增 本地数据库不存在网络问题,所以与批量操作效率差距不明显
    13. try {
    14. XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
    15. XSSFSheet sheet = workbook.getSheetAt(0);
    16. int lastRowNum = sheet.getLastRowNum();//所有行数
    17. int row = 0;
    18. // while (row<=lastRowNum){
    19. // //循环读取,每次处理1000条
    20. // saveBatch(readGoodWhile(sheet,row,1000,lastRowNum));
    21. // row+=1000;
    22. // }
    23. //多线程线程池方式操作
    24. while (row<=lastRowNum){
    25. //循环读取,每次处理1000条
    26. myThreadPoolExecutor.execute(new BatchInsert(sheet,row,1000,lastRowNum,this));
    27. row+=1000;
    28. }
    29. }catch (Exception e){
    30. e.printStackTrace();
    31. }
    32. return true;
    33. }

    使用线程池,将读取的文件每1000条为一个任务,交由线程池执行,结果如下:

    是不是突然感觉多线程快好多。。。。。其实不然,注意下面一个启动线程处理,实际上我controller的主线程是已经返回了,给了用户,但是实际我的新增任务,才刚由多线程开始处理,至于实际速度,受限数据库的物理新增速度,并不比单线程的快速。当然有朋友可能会考虑并发安全问题,有没有重复插入之类的,读一下代码的逻辑,自行找下吧,实际是这部分代码,并没有线程安全问题,如果有疑问,可留言沟通。

    总结下poi原始读取的方式

            1.读取每个单元格的的写法,我实体类有多少字段就需要把全部字段都读取出来

            2.读取前是需要把文件加载到内存,如果文件过大,内存不足就会出错

            3.新增速率并不快,多线程只能让接口反馈更迅速

    我测试时用的是5w多条,实测后面最大的文件里面是34w的时候,我电脑内存不足,无法加载到内存,更别说读取了。

    Easy Excel

            那么大的文件无法读取,难道超过了多少数据量我们就没办法用java处理么?肯定不是,不同量级我们肯定要考虑不同的方案,当技术无法满足,也可以使用其他手段。接下来我们就看下阿里根据poi的基础开发出来的上层框架 easy excel

    直接看代码吧:

    导入依赖

    1. <dependency>
    2. <groupId>com.alibabagroupId>
    3. <artifactId>easyexcelartifactId>
    4. <version>3.1.1version>
    5. dependency>

    创建监听

    1. package com.file.business;
    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.file.entity.SupplierGood;
    6. import com.file.service.SupplierGoodService;
    7. import lombok.extern.slf4j.Slf4j;
    8. import java.util.List;
    9. /**
    10. * @ClassName UploadFileListener
    11. * @Description easyexcel读取数据
    12. * @Author andy
    13. * @Date 2022/10/28 11:04
    14. * @Version 1.0
    15. */
    16. @Slf4j
    17. public class UploadFileListener implements ReadListener {
    18. /**
    19. * 500条,然后清理list ,方便内存回收
    20. */
    21. private static final int BATCH_COUNT = 500;
    22. /**
    23. * 缓存的数据
    24. */
    25. private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    26. /**
    27. * 一个service。当然如果不用存储这个对象没用。
    28. */
    29. private SupplierGoodService service;
    30. /**
    31. * 每次创建Listener的时候需要把spring管理的类传进来
    32. *
    33. * @param service
    34. */
    35. public UploadFileListener(SupplierGoodService service) {
    36. this.service = service;
    37. }
    38. /**
    39. * 这个每一条数据解析都会来调用
    40. *
    41. * @param data one row value. Is is same as {@link AnalysisContext#readRowHolder()}
    42. * @param context
    43. */
    44. @Override
    45. public void invoke(SupplierGood data, AnalysisContext context) {
    46. cachedDataList.add(data);
    47. // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
    48. if (cachedDataList.size() >= BATCH_COUNT) {
    49. saveData();
    50. // 存储完成清理 list
    51. cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    52. }
    53. }
    54. /**
    55. * 所有数据解析完成了 都会来调用
    56. *
    57. * @param context
    58. */
    59. @Override
    60. public void doAfterAllAnalysed(AnalysisContext context) {
    61. // 这里也要保存数据,确保最后遗留的数据也存储到数据库
    62. saveData();
    63. log.info("所有数据解析完成!");
    64. }
    65. /**
    66. * 加上存储数据库
    67. */
    68. private void saveData() {
    69. service.saveBatch(cachedDataList);
    70. }
    71. }

    实体类

    1. package com.file.entity;
    2. import com.alibaba.excel.annotation.ExcelProperty;
    3. import com.baomidou.mybatisplus.annotation.IdType;
    4. import com.baomidou.mybatisplus.annotation.TableId;
    5. import com.baomidou.mybatisplus.annotation.TableName;
    6. import java.io.Serializable;
    7. import java.math.BigDecimal;
    8. import java.time.LocalDateTime;
    9. import java.util.Date;
    10. import io.swagger.annotations.ApiModel;
    11. import io.swagger.annotations.ApiModelProperty;
    12. import lombok.Getter;
    13. import lombok.Setter;
    14. import lombok.experimental.Accessors;
    15. /**
    16. *

    17. * 供应商商品管理
    18. *

    19. *
    20. * @author andy
    21. * @since 2022-10-25
    22. */
    23. @Getter
    24. @Setter
    25. //@Accessors(chain = true) easy不能使用该注解
    26. @TableName("supplier_good")
    27. @ApiModel(value = "SupplierGood对象", description = "供应商商品管理")
    28. public class SupplierGood implements Serializable {
    29. private static final long serialVersionUID = 1L;
    30. @ApiModelProperty("id")
    31. @TableId(value = "id", type = IdType.AUTO)
    32. private Long id;
    33. @ApiModelProperty("雪花id")
    34. @ExcelProperty(index = 0)
    35. private String snowId;
    36. @ApiModelProperty("商品编号")
    37. @ExcelProperty(index = 1)
    38. private String goodsNumber;
    39. @ApiModelProperty("商品id")
    40. @ExcelProperty(index = 2)
    41. private Long goodId;
    42. @ApiModelProperty("供应商名称")
    43. @ExcelProperty(index = 3)
    44. private String supplierName;
    45. @ApiModelProperty("商品别名")
    46. @ExcelProperty(index = 4)
    47. private String goodAlias;
    48. @ApiModelProperty("商品一级分类id")
    49. @ExcelProperty(index = 5)
    50. private Integer oneCategoryId;
    51. @ApiModelProperty("商品一级分类名称")
    52. @ExcelProperty(index = 6)
    53. private String oneCategoryClass;
    54. @ApiModelProperty("商品二级分类id")
    55. @ExcelProperty(index = 7)
    56. private Integer twoCategoryId;
    57. @ApiModelProperty("商品二级分类名称")
    58. @ExcelProperty(index = 8)
    59. private String twoCategoryClass;
    60. @ApiModelProperty("二级分类pid")
    61. @ExcelProperty(index = 9)
    62. private Long twoClasspid;
    63. @ApiModelProperty("商品名称")
    64. @ExcelProperty(index = 10)
    65. private String goodName;
    66. @ApiModelProperty("商品品牌")
    67. @ExcelProperty(index = 11)
    68. private String goodBrand;
    69. @ApiModelProperty("商品产地")
    70. @ExcelProperty(index = 12)
    71. private String goodPlace;
    72. @ApiModelProperty("商品溯源信息")
    73. @ExcelProperty(index = 13)
    74. private String goodRoot;
    75. @ApiModelProperty("商品溯源说明")
    76. @ExcelProperty(index = 14)
    77. private String goodRootRemark;
    78. @ApiModelProperty("是否上架 0下架 1上架")
    79. @ExcelProperty(index = 15)
    80. private Integer isNotShelves;
    81. @ApiModelProperty("创建人id")
    82. @ExcelProperty(index = 16)
    83. private String createId;
    84. @ApiModelProperty("供应商id")
    85. @ExcelProperty(index = 17)
    86. private String supplierId;
    87. @ApiModelProperty("创建时间")
    88. @ExcelProperty(index = 18)
    89. private Date createTime;
    90. @ApiModelProperty("修改人id")
    91. @ExcelProperty(index = 19)
    92. private Long updateId;
    93. @ApiModelProperty("修改时间")
    94. @ExcelProperty(index = 20)
    95. private Date updateTime;
    96. @ApiModelProperty("状态")
    97. @ExcelProperty(index = 21)
    98. private Integer status;
    99. @ApiModelProperty("审批状态(0, 未审核 1 审核通过 1 审核驳回)")
    100. @ExcelProperty(index = 22)
    101. private Integer approvalState;
    102. @ApiModelProperty("供应商状态(0 上架 1 下架)")
    103. @ExcelProperty(index = 23)
    104. private Integer supplierState;
    105. @ApiModelProperty("系统端上架状态 (0 上架 1 下架)")
    106. @ExcelProperty(index = 24)
    107. private Integer systemState;
    108. @ApiModelProperty("说明")
    109. @ExcelProperty(index = 25)
    110. private String remark;
    111. @ApiModelProperty("选择好分类和名称,自动显示编码")
    112. @ExcelProperty(index = 26)
    113. private String goodCode;
    114. @ApiModelProperty("单位")
    115. @ExcelProperty(index = 27)
    116. private String unit;
    117. @ApiModelProperty("商品价格")
    118. @ExcelProperty(index = 28)
    119. private BigDecimal goodPrice;
    120. @ApiModelProperty("商品规格描述")
    121. @ExcelProperty(index = 29)
    122. private String specificationsRemark;
    123. @ApiModelProperty("损耗率")
    124. @ExcelProperty(index = 30)
    125. private Integer loss;
    126. @ApiModelProperty("商品标签id")
    127. @ExcelProperty(index = 31)
    128. private Long goodLabelId;
    129. @ApiModelProperty("标签名称")
    130. @ExcelProperty(index = 32)
    131. private String goodLabel;
    132. @ApiModelProperty("税收分类编码")
    133. @ExcelProperty(index = 33)
    134. private String rateCode;
    135. @ApiModelProperty("税率")
    136. @ExcelProperty(index = 34)
    137. private String rate;
    138. @ApiModelProperty("商品主图")
    139. @ExcelProperty(index = 35)
    140. private String goodMainImage;
    141. @ApiModelProperty("0 未删除 1删除")
    142. @ExcelProperty(index = 36)
    143. private Integer deleted;
    144. @ApiModelProperty("创建人")
    145. @ExcelProperty(index = 37)
    146. private String createName;
    147. @ApiModelProperty("商品规格")
    148. @ExcelProperty(index = 38)
    149. private String specifications;
    150. @ApiModelProperty("农民信息图片")
    151. @ExcelProperty(index = 39)
    152. private String farmingImages;
    153. @ApiModelProperty("起订量")
    154. @ExcelProperty(index = 40)
    155. private Integer startNumber;
    156. }

    读取

    1. @Override
    2. public boolean easyFileRead(MultipartFile file) throws IOException {
    3. EasyExcel.read(file.getInputStream(), SupplierGood.class, new UploadFileListener(this)).sheet().doRead();
    4. return true;
    5. }

    搞定了,先看下效果

    这是5w条数据结果

    这是34w条数据结果

     

     来对比下poi和easy excel

    拿到源码的小伙伴可以看到,我在poi原始情况下读取,对实体类写了一个构造,而且在构造中做了很多处理。(本来是偷懒想直接放值,结果各种异常越来越大)而且这个情况是没有做过数据校验的,但是easy excel并没有任何去写行和列的代码

    区别:

    1.代码的简洁度,可读性,维护性easy更高(有很多api可自行官网必读 | Easy Excel

    2.同样的5w条数据,easy的速度更快

    3.34w数据,原始poi电脑配置不够,搞不定,easy轻松处理(easy是分段读取,利用磁盘做缓存)

    各位也可自行测试

    总结

            我暂时没有去研究过其他的读取方式,就先说这两种了。回到最开始的面试问题来说。其实可以看到,当一个技术无法满足我们的业务的时候,我们需要在原有基础上做一次包装升级,比如easy对poi做了升级,如果你觉得easy也慢了点(34w的时候)其实去读下它的源码,在基础上能不能找到更适合自己的优化呢?肯定是可以的,比如给大家个思路,它的读取是按sheet的页,有没有可能我把大量数据分成多个sheet,用多线程来读取呢?我没有试过,但是你试过没?

            当然也不是说你试了就一定会比较快,还要考虑其他的问题,比如数据库新增的速度,网络传输数据的问题,能不能加缓存或者是其他的什么方式来解决。如果所有的技术方案都无法支撑量级的增长呢?技术跟不上业务的增长了呢?这个时候就不能一味的再去用极高的成本来解决极小的优化了,适当调整下业务。比如我们在网络购物的时候付款成功为啥会有个看着没有啥任何作用的倒计时跳转页面呢?这个就是当技术无法满足所有情况,由业务做出的妥协。

            技术学习永无止境,开发思想不要局限。更多思考原因,找问题。我想如果你也遇到和我一样的面试题,应该能在心中有些想法了

  • 相关阅读:
    beforeRouteEnter、created、mounted的思考和总结
    Android Studio 引入Xui框架-简单应用
    在页面上用卡片展示数据
    类和对象(2)
    云服务器安装 redis
    神经网络(neural network)
    【Java成王之路】EE初阶第二十篇: 前端三剑客 JavaScript 基础语法篇
    Qt Creator 创建 Qt 默认窗口程序
    JVM内存模型
    C++ 类和对象 (中)
  • 原文地址:https://blog.csdn.net/qq_20607405/article/details/127635941