java使用hutools导出excel
时间: 2023-07-20 15:11:09 浏览: 95
java导出excel模板demo
使用Hutools导出Excel需要先添加Hutools依赖,可以在Maven中添加以下依赖:
```xml
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.5</version>
</dependency>
```
接下来,按照以下步骤使用Hutools导出Excel:
1. 创建ExcelWriter对象:
```java
ExcelWriter writer = ExcelUtil.getWriter("d:/test.xlsx");
```
2. 写入表头:
```java
// 写入表头
writer.addHeaderAlias("name", "姓名");
writer.addHeaderAlias("age", "年龄");
writer.addHeaderAlias("gender", "性别");
```
3. 写入数据:
```java
// 写入数据
List<Map<String, Object>> rows = new ArrayList<>();
Map<String, Object> row1 = new LinkedHashMap<>();
row1.put("name", "张三");
row1.put("age", 20);
row1.put("gender", "男");
rows.add(row1);
Map<String, Object> row2 = new LinkedHashMap<>();
row2.put("name", "李四");
row2.put("age", 25);
row2.put("gender", "女");
rows.add(row2);
writer.write(rows);
```
4. 关闭ExcelWriter:
```java
writer.close();
```
完整代码示例:
```java
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class ExportExcelDemo {
public static void main(String[] args) {
// 创建ExcelWriter对象
ExcelWriter writer = ExcelUtil.getWriter("d:/test.xlsx");
// 写入表头
writer.addHeaderAlias("name", "姓名");
writer.addHeaderAlias("age", "年龄");
writer.addHeaderAlias("gender", "性别");
// 写入数据
List<Map<String, Object>> rows = new ArrayList<>();
Map<String, Object> row1 = new LinkedHashMap<>();
row1.put("name", "张三");
row1.put("age", 20);
row1.put("gender", "男");
rows.add(row1);
Map<String, Object> row2 = new LinkedHashMap<>();
row2.put("name", "李四");
row2.put("age", 25);
row2.put("gender", "女");
rows.add(row2);
writer.write(rows);
// 关闭ExcelWriter
writer.close();
}
}
```
阅读全文