EasyExcel
在做excel导入导出的时候,发现项目中封装的工具类及其难用,于是去gitHub上找了一些相关的框架,最终选定了EasyExcel。之前早有听闻该框架,但是一直没有去了解,这次借此学习一波,提高以后的工作效率。实际使用中,发现是真的很easy,大部分api通过名称就能知道大致意思,这点做的很nice。参考文档,大部分场景的需求基本都能够满足。
GitHub上的官方说明
image
快速开始
maven仓库地址
com.alibaba
easyexcel
2.1.2
导入
如下图excel表格:
image
建立导入对应实体类
@Data
public class ReqCustomerDailyImport {
/**
* 客户名称
*/
@ExcelProperty(index = 0)
private String customerName;
/**
* MIS编码
*/
@ExcelProperty(index = 1)
private String misCode;
/**
* 月度滚动额
*/
@ExcelProperty(index = 3)
private BigDecimal monthlyQuota;
/**
* 最新应收账款余额
*/
@ExcelProperty(index = 4)
private BigDecimal accountReceivableQuota;
/**
* 本月利率(年化)
*/
@ExcelProperty(index = 5)
private BigDecimal dailyInterestRate;
}
Controller代码
@PostMapping("/import")
public void importCustomerDaily(@RequestParam MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
List reqCustomerDailyImports = EasyExcel.read(inputStream)
.head(ReqCustomerDailyImport.class)
// 设置sheet,默认读取第一个
.sheet()
// 设置标题所在行数
.headRowNumber(2)
.doReadSync();
}
运行结果
image
可以看出只需要在实体对象使用@ExcelProperty注解,读取时指定该class,即可读取,并且自动过滤了空行,对于excel的读取及其简单。不过此时发现一个问题,这样我如果要校验字段该怎么办?要将字段类型转换成另外一个类型呢?
不必担心,我们可以想到的问题,作者肯定也考虑到了,下面来一个Demo
代码如下
List reqC