(1).maven坐标地址
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.1.1</version> </dependency>
(2).配置ReadListener,相当于设置excel读取配置
public class EcommerceMonthTargetExcelListener<E> implements ReadListener<EcommerceMonthTargetExcel> { // 保存全部Excel public List<EcommerceMonthTargetExcel> list = new ArrayList<EcommerceMonthTargetExcel>(); /** * invoke */ @Override public void invoke(EcommerceMonthTargetExcel ecommerceTargetExcel, AnalysisContext analysisContext) { list.add(ecommerceTargetExcel); } /** * doAfterAllAnalysed */ @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { }
invoke在每执行一行则被调用1次,因此我用他来保存全部的数据,用list保存;doAfterAllAnalysed在全部执行完成后执行,EcommerceMonthTargetExcelListener就是我定义的读取下面的excel的监听器,其实只是做了list.add追加数据而已
(3).定义excel数据实体
@Getter @Setter @EqualsAndHashCode public class EcommerceMonthTargetExcel { @ExcelProperty(index = 0) public String name; @ExcelProperty(index = 1) public String channel; @ExcelProperty(index = 2) public String month1; @ExcelProperty(index = 3) public String month2; @ExcelProperty(index = 4) public String month3; @ExcelProperty(index = 5) public String month4; @ExcelProperty(index = 6) public String month5; @ExcelProperty(index = 7) public String month6; }
其中的index就是第几列的意思,映射到某个类属性
(4).读取excel
// 文件位置 String fileName = "D:/excel/电商目标表/21-3 目标更换.xlsx"; String year = "2022"; // 读取Excel文件 EcommerceMonthTargetExcelListener<?> ecommerceMonthTargetExcelListener = new EcommerceMonthTargetExcelListener<>(); try (ExcelReader excelReader = EasyExcel.read(fileName, EcommerceMonthTargetExcel.class, ecommerceMonthTargetExcelListener).build()) { ReadSheet readSheet = EasyExcel.readSheet(0).build(); excelReader.read(readSheet); excelReader.finish(); } // 循环处理数据 for (EcommerceMonthTargetExcel ecommerceMonthTarget : ecommerceMonthTargetExcelListener.list) { // 提取参数(Excel中的数据) String name = ecommerceMonthTarget.name; String channel = ecommerceMonthTarget.channel; String month1 = ecommerceMonthTarget.month1; // 7月 String month2 = ecommerceMonthTarget.month2; // 8月 String month3 = ecommerceMonthTarget.month3; // 9月 String month4 = ecommerceMonthTarget.month4; // 10月 String month5 = ecommerceMonthTarget.month5; // 11月 String month6 = ecommerceMonthTarget.month6; // 12月 }