依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
<!--xls-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!--xlsx-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
</dependencies>
一、对Excel写操作
1.创建实体类
@Data
public class DemoData {
//设置Excel表头名称
@ExcelProperty("学生编号")
private Integer sno;
@ExcelProperty("学生姓名")
private String sname;
}
写入测试
public class TestEasyExcel {
public static void main(String[] args) {
//实现Excel写操作
//设置写入文件夹地址和Excel名称
String filename="E:\\test/write.xlsx";
//调用easyexcel里的方法实现写操作
EasyExcel.write(filename,DemoData.class).sheet("学生列表").doWrite(getData());
}
//创建方法返回list集合
private static List<DemoData> getData(){
List<DemoData> dataList=new ArrayList<>();
for (int i = 0; i < 10; i++) {
DemoData demoData=new DemoData();
demoData.setSname("Tom"+i);
demoData.setSno(i);
dataList.add(demoData);
}
return dataList;
}
}
二、对Excel读操作
实体类
@Data
public class DemoData {
//设置Excel表头名称
@ExcelProperty(value = "学生编号",index = 0)
private Integer sno;
@ExcelProperty(value = "学生姓名",index = 1)
private String sname;
}
读操作
public class TestRead {
public static void main(String[] args) {
//实现读操作
String filename="E:\\test/write.xlsx";
EasyExcel.read(filename,DemoData.class,new ExcelListener()).sheet().doRead();
}
}