1. 首先需要引入easyexcel的依赖包,例如:
<!-- easyexcel -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.2.10</version>
</dependency>
  1. 定义实体类,包含表头对应的属性:
public class User {
    private Integer id;
    private String code;
    private String name;
    private Integer age;
    // getter and setter
}
  1. 创建数据列表:
List<User> userList = new ArrayList<>();
userList.add(new User(1, "001", "Tom", 20));
userList.add(new User(2, "002", "Jerry", 22));
  1. 创建表头列表:
List<String> headList = Arrays.asList("序号", "编号", "姓名", "年龄");
  1. 创建写入器并设置相关参数:
// 文件输出路径
String filePath = "D:\\test.xlsx";
// 创建写入器
ExcelWriter excelWriter = EasyExcel.write(filePath, User.class).build();
// 设置表格样式
WriteCellStyle headCellStyle = new WriteCellStyle();
headCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
WriteFont headFont = new WriteFont();
headFont.setBold(true);
headCellStyle.setWriteFont(headFont);
// 设置表头
WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").head(headList).headCellStyle(headCellStyle).build();
// 写入数据
excelWriter.write(userList, writeSheet);
// 关闭写入器
excelWriter.finish();
  1. 运行程序,查看输出文件。

原文地址: https://www.cveoy.top/t/topic/brVK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录