借鉴网址:写Excel | Easy Excel
1.引入依赖
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.写个实体类
下标默认0开始
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@EqualsAndHashCode
public class ExcelBean {
@ExcelProperty(index = 0)
private Integer id;
@ExcelProperty(index = 1)
private String type;
@ExcelProperty(index = 2)
private Integer age;
3.测试类
3.1读:
/**
* 读
*/
@Test
public void test01(){
// 写法1:JDK8+ ,不用额外写一个DemoDataListener
// since: 3.0.0-beta1
String path="E:\\ima\\test.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
// 这里每次会读取100条数据 然后返回过来 直接调用使用数据就行
EasyExcel.read(path, ExcelBean.class, new PageReadListener<ExcelBean>(dataList -> {
for (ExcelBean demoData : dataList) {
System.err.println(demoData);
}
})).sheet().doRead();
}
写:
/**
* 写
*/
@Test
public void test02(){
// 注意 simpleWrite在数据量不大的情况下可以使用(5000以内,具体也要看实际情况),数据量大参照 重复多次写入
// 写法1 JDK8+
// since: 3.0.0-beta1
String path="E:\\ima\\test.xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
// 如果这里想使用03 则 传入excelType参数即可
EasyExcel.write(path, ExcelBean.class)
.sheet("模板")
.doWrite(() -> {
// 分页查询数据
ArrayList<ExcelBean> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
ExcelBean wpp = new ExcelBean(i, "wpp"+i, 20+i);
list.add(wpp);
}
return list;
});
}
注:如果读写是同一个文件,写之前把打开的文件关掉