利用EasyExcel 将List数据转Excel文件

该文章介绍了一种在Java中将List数据转化为Excel文件的方法,利用EasyExcel库。实体类A包含了需要转换的字段,但不支持List或Map类型。转换方法通过排除不需要的字段,创建ExcelWriter并写入数据到指定文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

List数据转Excel文件

相关代码如下:
需要注意,转换只支持基本数据类型,不支持List,Map类似的数据结构

实体类

@Data
@TableName("test")
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "A", description = "A")
public class A implements Serializable {
	private static final long serialVersionUID = 1L;

        @TableId(type= IdType.AUTO)
        @ExcelProperty(value = "序号主键")
        private Integer id;

        @ExcelProperty(value = "A")
        private String a;

        @ColumnWidth(value = 20)
        @ExcelProperty(value = "B")
        private String b;

        @TableField(exist = false)
        @ExcelIgnore
        private List<UploadVo> c;

        @ApiModelProperty(value = "d")
        @ExcelProperty(value = "D")
        private String d;

        @ApiModelProperty(value = "F")
        @ExcelProperty(value = "F")
        private String f;
}

转换方法

    /**
     * list数据转excel文件
     *
     * @param dataList 数据
     * @return 文件
     */
    public File execFile(List<A> dataList, String fileName, String sheetName) {
        String tmpFilePath = "D:\\file\\";
        // 如果文件夹不存在则会创建
        File f = new File(tmpFilePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        File file = new File(tmpFilePath + fileName + System.currentTimeMillis() + ".xlsx");
        if (!dataList.isEmpty()) {
            //新建ExcelWriter
            ExcelWriter excelWriter = EasyExcel.write(file.getAbsoluteFile(), MaterialApplyDetail.class).build();
            try {
                //获取sheet0对象
                // 排除字段 可使用此方式或注解ExcelIgnore
                HashSet<String> set0 = new HashSet<>();
                //该名称为实体类属性
                set0.add("id");
                set0.add("a");
                set0.add("b");
                WriteSheet mainSheet = EasyExcel.writerSheet(0, sheetName).head(MaterialApplyDetail.class).excludeColumnFiledNames(set0).build();
                excelWriter.write(dataList, mainSheet);
            } catch (Exception e) {
                log.error("数据生成excel文件失败,{}", e.getMessage());
            } finally {
                //关闭流
                excelWriter.finish();
            }
        }
        return file;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值