Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。
easyexcel重写了poi对07版Excel的解析,能够原本一个3M的excel用POI sax依然需要100M左右内存降低到KB级别,并且再大的excel不会出现内存溢出,03版依赖POI的sax模式。在上层做了模型转换的封装,让使用者更加简单方便。
easyExcel 是阿里巴巴开源的解析 Excel 的工具,easyExcel github 地址:https://github.com/alibaba/easyexcel
1. 准备 pom
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easyexcel.version}</version>
</dependency>
注意: 该版本下使用的POI版本为3.17,所以当项目中的POI版本不为3.17时(有可能项目之前已经引入POI,easyexcel默认自带版本为3.17),可以考虑升级。
2. 创建实体
@Data
public class AwardExcelResponse extends BaseRowModel implements Serializable {
private Long id;
@ExcelProperty(value = "活动编号", index = 0)
private Long activityId;
@ExcelProperty(value = "奖品编号", index = 1)
private Long awardId;
@ExcelProperty(value = "奖品名称", index = 2)
private String awardName;
private Integer awardType;
@ExcelProperty(value = "精品类型", index = 3)
private String awardTypeDesc;
@ExcelProperty(value = "奖品数量", index = 4)
private Integer awardQuantity;
@ExcelProperty(value = "奖品状态", index = 5)
private Integer awardStatus;
@ExcelProperty(value = "奖品导入", index = 6)
private Integer outAwardImport;
@ExcelProperty(value = "是否需要手机号", index = 7)
private Integer needMobile;
@ExcelProperty(value = "是否需要地址", index = 8)
private Integer needAddress;
@ExcelProperty(value = "是否发送短信", index = 9)
private Integer sendMsg;
@ExcelProperty(value = "奖品导入状态", index = 10)
private Integer outImportStatus;
@ExcelProperty(value = "实际奖品ID", index = 11)
private String relatedPrizeId;
@ExcelProperty(value = "实际奖品金额", index = 12)
private Integer relatedPrizeAmount;
@ExcelProperty(value = "备注", index = 13)
private String remark;
注意:需要进行转义的字段可以在 get() 方法中进行转义。
3. 编写监听器,该类用于返回读取到的对象
@Slf4j
&#