easyexcel读写
时间: 2023-11-10 21:03:44 浏览: 113
好的,了解您的要求。关于easyexcel读写,可以参考以下步骤:
1. 引入依赖
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.10</version>
</dependency>
```
2. 写入Excel文件
```java
// 创建Excel对应的实体对象
public class DemoData {
@ExcelProperty("姓名")
private String name;
@ExcelProperty("年龄")
private Integer age;
}
// 写入Excel
public void writeExcel() {
// 文件输出位置
String fileName = "demo.xlsx";
// 写法1
EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(dataList);
// 写法2
ExcelWriter excelWriter = null;
try {
excelWriter = EasyExcel.write(fileName, DemoData.class).build();
WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
excelWriter.write(dataList, writeSheet);
} finally {
if (excelWriter != null) {
excelWriter.finish();
}
}
}
```
3. 读取Excel文件
```java
// 读取Excel
public void readExcel() {
// 文件路径
String fileName = "demo.xlsx";
// 读取sheet1内容
EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).sheet().doRead();
// 读取所有sheet内容
EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).doReadAll();
}
// 读取监听器
public class DemoDataListener extends AnalysisEventListener<DemoData> {
private List<DemoData> dataList = new ArrayList<>();
@Override
public void invoke(DemoData data, AnalysisContext context) {
// 读取到一条数据时执行
dataList.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 读取完成后执行
// 可以将dataList进行保存操作
}
}
```
阅读全文