使用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>

二.代码

java 复制代码
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;
}
java 复制代码
 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));
        }
    }

测试类:

java 复制代码
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        // 结果集合
        List<User> excelList = new ArrayList<>();
        excelList.add(new User("1","张三",20,"zhangsan@163.com"));
        //写入excel
        writeExcel(excelList);
相关推荐
米芝鱼20 小时前
Unity读取Excel转换为二进制数据文件与自定义数据读写
游戏·unity·游戏引擎·excel·urp
用户2986985301420 小时前
如何在 C# 中创建、读取和更新 Excel 文档
后端·c#·excel
艾上编程20 小时前
第一章——办公自动化之Excel批量合并工具:Python助力高效办公
开发语言·python·excel
MYX_3091 天前
使用EXCEL进行数据清洗
excel
傻啦嘿哟1 天前
Python高效实现Excel与TXT文本文件数据转换指南
开发语言·python·excel
綝~1 天前
Excel导入MongoDB操作手册
数据库·excel
暗武逢天1 天前
Java导出复杂Excel升级版(解决占位符遗留问题,通用工具类)
java·excel·easyexcel·模板导出·通用工具类
ohoy2 天前
EasyPoi 自定义数据处理
excel
ohoy2 天前
easypoi 自定义样式 学生-分数红绿颜色设置
excel
ranchor6662 天前
excel+pandas使用str.contains() 的典型例子
excel·pandas