使用hutools 生成excel
一.引入依赖
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.3</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>
二.代码
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class User {
@ApiModelProperty(value = "用户ID")
private String id;
@ApiModelProperty(value = "用户名称")
private String name;
@ApiModelProperty(value = "用户年龄")
private Integer age;
@ApiModelProperty(value = "用户邮箱")
private String email;
}
private void writeExcel(List<CarVdnEntity> excelList) {
log.info("CarVdnServiceImpl.writeExcel.excelList.size:", excelList.size());
LinkedList<String> headerList = new LinkedList<>();
//生成文件路径 windows 环境可以写成("D://file//")
ExcelWriter writer = ExcelUtil.getWriter("GBOM-" + (LocalDate.now().toString()));
addHeaderAlias(writer, headerList);
writer.writeHeadRow(headerList);
//一次性写出内容,强制输出标题
writer.write(excelList);
//关闭writer,释放内存
writer.close();
}
private static String convertToUnderscore(String camelCase) {
// 使用正则表达式将大写字母前面添加下划线,并转换为小写
String underscore = camelCase.replaceAll("([A-Z])", "_$1").toLowerCase();
// 如果开头有下划线,则去除开头的下划线
if (underscore.startsWith("_")) {
underscore = underscore.substring(1);
}
return underscore;
}
private static void addHeaderAlias(ExcelWriter writer, LinkedList<String> header) {
Class<?> clazz = User.class;
Field[] fields = clazz.getDeclaredFields();
// 遍历字段数组,获取每个字段的名称并添加到列表中
for (Field field : fields) {
String fieldName = field.getName();
header.add(convertToUnderscore(fieldName));
writer.addHeaderAlias(fieldName, convertToUnderscore(fieldName));
}
}
测试类:
LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
// 结果集合
List<User> excelList = new ArrayList<>();
excelList.add(new User("1","张三",20,"zhangsan@163.com"));
//写入excel
writeExcel(excelList);