EasyExcel导入导出以及读取
时间: 2023-10-13 12:09:40 浏览: 125
EasyExcel 是一个 Java Excel 操作工具,可以方便地进行 Excel 文件的导入、导出和读取。以下是 EasyExcel 的使用方法:
### 导入 Excel
1. 添加 EasyExcel 依赖
```
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.10</version>
</dependency>
```
2. 创建 ExcelListener
```java
public class ExcelListener extends AnalysisEventListener<Data> {
private List<Data> dataList = new ArrayList<>();
@Override
public void invoke(Data data, AnalysisContext analysisContext) {
dataList.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
// 处理数据
}
public List<Data> getDataList() {
return dataList;
}
}
```
3. 导入 Excel 文件
```java
String fileName = "test.xlsx";
File file = new File(fileName);
ExcelReader reader = null;
try {
reader = EasyExcel.read(file, Data.class, new ExcelListener()).build();
reader.readAll();
} finally {
if (reader != null) {
reader.finish();
}
}
```
### 导出 Excel
1. 创建 ExcelWriter
```java
String fileName = "test.xlsx";
ExcelWriter writer = EasyExcel.write(fileName, Data.class).build();
```
2. 写入数据
```java
List<Data> dataList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Data data = new Data();
data.setName("Name" + i);
data.setAge(i);
dataList.add(data);
}
writer.write(dataList, EasyExcel.writerSheet("Sheet1").build());
```
3. 关闭 ExcelWriter
```java
writer.finish();
```
### 读取 Excel
1. 创建 ExcelReader
```java
String fileName = "test.xlsx";
File file = new File(fileName);
ExcelReader reader = null;
try {
reader = EasyExcel.read(file, Data.class, new ExcelListener()).build();
reader.readAll();
} finally {
if (reader != null) {
reader.finish();
}
}
```
2. 处理数据
```java
List<Data> dataList = excelListener.getDataList();
// 处理数据
```
阅读全文