多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
:-: ![](https://img.kancloud.cn/0d/23/0d2352e68aecd259648945d721aab397_1504x224.jpg) ![](https://img.kancloud.cn/0c/53/0c5301e6b855c25831e335746c92053f_1493x224.jpg) Sheet1、Sheet2 **1. 创建对应的实体类** ```java @Data public class Student { @ExcelProperty("姓名") private String name; @ExcelProperty("年龄") private Integer age; @ExcelProperty("性别") private String gender; @ExcelProperty("身高") private Integer total; } ``` **2. 创建对应的监听器** ```java @Slf4j public class StudentExcelListener implements ReadListener<Student> { /** * 每读取表格中的一行时就会被调用一次 */ @Override public void invoke(Student student, AnalysisContext analysisContext) { log.info("invoke -> {}", student); //invoke -> Student(name=张三, age=25, gender=男, total=175) //invoke -> Student(name=李四, age=28, gender=男, total=179) //invoke -> Student(name=王五, age=35, gender=男, total=180) // //invoke -> Student(total=175, gender=男, age=25, name=zhangsan) //invoke -> Student(total=179, gender=男, age=28, name=lisi) //invoke -> Student(total=180, gender=男, age=35, name=wangwu) } /** * 每当读取完一个sheet就会被调用一次 */ @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { log.info("doAfterAllAnalysed"); } } ``` **3. 调用`EasyExcel.read(...).doReadAll()`方法读取所有的sheet** ```java @Test public void read02() { String path = this.getClass().getResource("/read/001.xlsx").getPath(); EasyExcel.read(path, Student.class, new StudentExcelListener()).doReadAll(); } ``` **4. 调用`EasyExcel.readSheet(index)`方法读取指定的sheet** ```java @Test public void read03() { String path = this.getClass().getResource("/read/001.xlsx").getPath(); //读取第一个sheet, 文件流会自动关闭的 EasyExcel.read(path, Student.class, new StudentExcelListener()).doReadAll(); try (ExcelReader excelReader = EasyExcel.read(path).build()) { ReadSheet readSheet1 = EasyExcel.readSheet(0).head(Student.class).registerReadListener(new StudentExcelListener()).build(); ReadSheet readSheet2 = EasyExcel.readSheet(1).head(Student.class).registerReadListener(new StudentExcelListener()).build(); //注意:一个sheet不能读取多次,比如第0个sheet已经被读取过了,所在不能再调用EasyExcel.readSheet(0) //注意:一定要把sheet1、sheet2 一起传进去,不然有个问题就是03版的excel会读取多次,浪费性能 excelReader.read(readSheet1, readSheet2); } } ```