第一步:创建maven项目导增加如下依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.1.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> <dependency> <groupId>org.apache.xmlbeans</groupId> <artifactId>xmlbeans</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>net.sf.saxon</groupId> <artifactId>saxon-dom</artifactId> <version>8.7</version> </dependency>
第二步创建Java实体类
@Data public class DataDemo { @ExcelProperty("姓名") private String name; @ExcelProperty("生日") private Date birthday; @ExcelProperty("薪资") private Double salary; }
第三步:简单的写入操作demo,代码如下:
/** * 写入xlsx文件测试方法 */ @Test public void simpleWriteXlsx() { String fileName = "d:/excel/simpleWrite.xlsx"; //需要提前新建目录 // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 EasyExcel.write(fileName, DataDemo.class).sheet("模板").doWrite(data()); } /** * 写入xls文件测试方法 */ @Test public void simpleWriteXls() { String fileName = "d:/excel/simpleWrite.xls"; // 如果这里想使用03 则 传入excelType参数即可 EasyExcel.write(fileName, DataDemo.class).excelType(ExcelTypeEnum.XLS).sheet("模板").doWrite(data()); }
data()的返回值是一个list集合,可以参考如下代码:
** * 循环制造list集合数据 * @return */ private List<DataDemo> data(){ List<DataDemo> list = new ArrayList<>(); //算上标题,做多可写65536行 //超出:java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0..65535) for (int i = 0; i < 2; i++) { DataDemo data = new DataDemo(); data.setName("Helen" + i); data.setBirthday(new Date()); data.setSalary(123456.1234); list.add(data); } return list; }
第四步简单的读取操作,代码如下:
1-创建监听重写invoke,doAfterAllAnalysed方法
@Slf4j public class ExcleDemoListener extends AnalysisEventListener<DataDemo> { @Override public void invoke(DataDemo dataDemo, AnalysisContext analysisContext) { log.info("解析到一条数据:{}", dataDemo); } @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { log.info("所有数据解析完成!"); }
2-调用easyExcel读取方法:
/** * 读取xlsx文件最简单的读 */ @Test public void simpleReadXlsx() { String fileName = "d:/excel/simpleWrite.xlsx"; // 这里默认读取第一个sheet EasyExcel.read(fileName, DataDemo.class, new ExcleDemoListener()).sheet().doRead(); } /** * 读取xls文件最简单的读 */ @Test public void simpleReadXls() { String fileName = "d:/excel/simpleWrite.xls"; EasyExcel.read(fileName, DataDemo.class, new ExcleDemoListener()).excelType(ExcelTypeEnum.XLS).sheet().doRead(); }