使用EasyExcel读和写excel文件
一、EasyExcel
官网地址:https://easyexcel.opensource.alibaba.com/
EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目。在尽可能节约内存的情况下支持读写百M的Excel。 github地址:https://github.com/alibaba/easyexcel。
二、依赖引入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> <scope>compile</scope> </dependency> </dependencies>
|
三、创建一个监听类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class ExcelListener<T> extends AnalysisEventListener<T> {
public List<T> list = new ArrayList<>(); @Override public void invoke(T T, AnalysisContext analysisContext) {
} @Override public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) { }
@Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { save(list); } public void save(List<T> list){
} }
|
四、与excel相对应的DTO
1 2 3 4 5 6 7 8
| @Data public class DemoDate { @ExcelProperty("学生编号") private Integer sno; @ExcelProperty("学生姓名") private String sname; }
|
五、测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| public class TestEasyExcel {
public static void main(String[] args) {
String filename = "F:\\write.xlsx"; List<DemoDate> list = new ArrayList<>(); list = EasyExcel.read(filename,DemoDate.class,new ExcelListener<DemoDate>()).sheet().headRowNumber(1).doReadSync(); System.out.println(list.toString());
File file = new File(filename); list = EasyExcel.read(file).head(DemoDate.class).sheet().headRowNumber(1).doReadSync(); System.out.println(list.get(0)); }
private static List<DemoDate> getDate(){ List<DemoDate> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { DemoDate data = new DemoDate(); data.setSno(i); data.setSname("conrad"+i); list.add(data); } return list; } }
|
表write.xlsx
学生编号 |
学生姓名 |
|
0 |
conrad0 |
|
1 |
conrad1 |
|
2 |
conrad2 |
|
3 |
conrad3 |
|
4 |
conrad4 |
|
5 |
conrad5 |
|
6 |
conrad6 |
|
7 |
conrad7 |
|
8 |
conrad8 |
|
9 |
conrad9 |
|