如何使用easyexcel导出csv格式数据
时间: 2024-01-03 12:55:16 浏览: 148
basic-excel:基本的Excel导入导出php类,可以导出csv,xls,xlsx
使用 EasyExcel 导出 csv 格式数据的步骤如下:
1. 引入 EasyExcel 依赖:
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.4.3</version>
</dependency>
```
2. 创建 ExcelWriter 对象:
```java
String fileName = "test.csv";
ExcelWriter writer = EasyExcel.write(fileName).build();
```
3. 创建 Sheet 对象:
```java
Sheet sheet = new Sheet(1, 0);
sheet.setSheetName("数据");
```
4. 创建表头信息:
```java
List<List<String>> head = new ArrayList<>();
List<String> headRow1 = new ArrayList<>();
headRow1.add("姓名");
headRow1.add("年龄");
head.add(headRow1);
```
5. 写入数据:
```java
List<List<String>> data = new ArrayList<>();
List<String> dataRow1 = new ArrayList<>();
dataRow1.add("张三");
dataRow1.add("20");
data.add(dataRow1);
List<String> dataRow2 = new ArrayList<>();
dataRow2.add("李四");
dataRow2.add("22");
data.add(dataRow2);
writer.write0(data, sheet, new WriteHandler(head));
```
6. 关闭 ExcelWriter 对象:
```java
writer.finish();
```
完整代码示例:
```java
public void exportCsv() {
String fileName = "test.csv";
ExcelWriter writer = EasyExcel.write(fileName).build();
Sheet sheet = new Sheet(1, 0);
sheet.setSheetName("数据");
List<List<String>> head = new ArrayList<>();
List<String> headRow1 = new ArrayList<>();
headRow1.add("姓名");
headRow1.add("年龄");
head.add(headRow1);
List<List<String>> data = new ArrayList<>();
List<String> dataRow1 = new ArrayList<>();
dataRow1.add("张三");
dataRow1.add("20");
data.add(dataRow1);
List<String> dataRow2 = new ArrayList<>();
dataRow2.add("李四");
dataRow2.add("22");
data.add(dataRow2);
writer.write0(data, sheet, new WriteHandler(head));
writer.finish();
}
```
执行该方法后,会在项目根目录下生成一个名为 `test.csv` 的 csv 文件。
阅读全文