引入依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.6</version> </dependency>
当依赖中存在poi时会出现依赖冲突
修改依赖为
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.6</version> <exclusions> <exclusion> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> </exclusion> <exclusion> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> </exclusion> <exclusion> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> </exclusion> <exclusion> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> </exclusion> </exclusions> </dependency>
即可解决依赖冲突
创建实体类
public class ImportExcel { @ExcelProperty(index = 0) private String fpdm; @ExcelProperty(index = 1) private String fphm; @ExcelProperty(index = 2) private String kprq; @ExcelProperty(index = 3) private String jym; }
index为字段在excel中位置 尽量不要使用名称和index共同作为定位
创建监听器easyexcel有多种监听器 这次使用AnalysisEventListener
public class ReadExcelUtil extends AnalysisEventListener<ImportExcel> { public List<ImportExcel> list=new ArrayList<>(); @Override public void invoke(ImportExcel importExcel, AnalysisContext analysisContext) { list.add(importExcel); } @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { } }
服务中开始读取数据
public void readExcel(MultipartFile file){
EasyExcel.read(file.getInputStream(),ImportExcel.class,readExcelUtil).sheet().headRowNumber(2).doRead();
}
headRowNumber()可以指定从第几行开始读