EasyExcel简单使用
Maven依赖
<properties>
<poi.version>3.17</poi.version>
<easy-excel.version>2.1.1</easy-excel.version>
</properties>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easy-excel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<!-- xlsx -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
实体类
@Data //lombok
public class DemoData {
@ExcelProperty(value = "学生编号",index = 0)
private Integer sno;
@ExcelProperty(value = "学生姓名",index = 1)
private String sname;
}
监听器
继承AnalysisEventListener类重写方法
public class ExcelListener extends AnalysisEventListener<DemoData> {
//一行一行读取
@Override
public void invoke(DemoData data, AnalysisContext analysisContext) {
System.out.println("---"+data);
}
//读取表头
@Override
public void invokeHead(Map<Integer, CellData> headMap, AnalysisContext context) {
System.out.println("---"+headMap);
}
//读取完成之后方法
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}
主函数
public class TestEasyExcel {
public static void main(String[] args) {
//设置写入的文件夹的地址和excel文件名
String fileName = "E:\\write.xlsx";
//文件路径名称
EasyExcel.write(fileName,DemoData.class)
.sheet("学生列表")
.doWrite(getData());
EasyExcel.read(fileName,DemoData.class,new ExcelListener()).sheet().doRead();
}
private static List<DemoData> getData()
{
List<DemoData> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
DemoData demoData = new DemoData();
demoData.setSno(i);
demoData.setSname("lucy"+1);
list.add(demoData);
}
return list;
}
}