java生成excel文件到指定目录,使用hutool
时间: 2023-11-27 20:49:23 浏览: 150
使用Hutool生成Excel文件到指定目录的代码如下:
```java
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.cell.CellStyleBuilder;
import cn.hutool.poi.excel.cell.CellUtil;
import cn.hutool.poi.excel.style.Align;
import java.util.List;
public class ExcelUtilDemo {
public static void main(String[] args) {
List<User> userList = getUserList();
// 创建Excel写入器
ExcelWriter writer = ExcelUtil.getWriter("D:\\test.xlsx");
// 自定义标题样式
CellStyleBuilder titleStyleBuilder = writer.getCellStyleBuilder();
titleStyleBuilder.bgColor(Color.LIGHT_GRAY);
titleStyleBuilder.align(Align.CENTER);
titleStyleBuilder.borderBottom(BorderStyle.THIN);
CellStyle titleStyle = titleStyleBuilder.build();
// 写入标题行
writer.merge(3, "用户列表"); // 合并单元格
CellUtil.createCell(writer.getRow(0), 0, "姓名", titleStyle);
CellUtil.createCell(writer.getRow(0), 1, "年龄", titleStyle);
CellUtil.createCell(writer.getRow(0), 2, "性别", titleStyle);
CellUtil.createCell(writer.getRow(0), 3, "地址", titleStyle);
// 写入数据行
for (int i = 0; i < userList.size(); i++) {
User user = userList.get(i);
CellUtil.createCell(writer.getRow(i + 1), 0, user.getName());
CellUtil.createCell(writer.getRow(i + 1), 1, user.getAge());
CellUtil.createCell(writer.getRow(i + 1), 2, user.getGender());
CellUtil.createCell(writer.getRow(i + 1), 3, user.getAddress());
}
// 关闭Excel写入器
writer.close();
}
private static List<User> getUserList() {
// TODO: 返回用户列表
return null;
}
private static class User {
private String name;
private int age;
private String gender;
private String address;
public User(String name, int age, String gender, String address) {
this.name = name;
this.age = age;
this.gender = gender;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
}
```
上面的代码中,我们使用`ExcelWriter`类来创建Excel文件,并将其保存到指定目录。通过`CellStyleBuilder`类可以自定义单元格样式,例如设置背景颜色、对齐方式、边框等。`CellUtil`类可以操作单元格,例如合并单元格、创建单元格等。最后,通过`ExcelWriter`的`close`方法关闭文件流。
阅读全文