easyexcel空值null值转换

这篇博客介绍了如何在EasyExcel 3.0.5版本中处理空值null字段,避免在导出Excel时出现错误。通过实现IntegerNullableConverter转换器并使用注解进行绑定,成功实现了对null字段的拦截处理,简化了依赖包的引入。

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

在上一篇导出篇我们使用版本2.2.10导出excel,但无法处理null字段拦截。
https://blog.csdn.net/cxj443914930/article/details/123538144

下面我们实现对null字段的拦截处理
升级EasyExcel版本, 3.0.5可以不用导入poi-ooxml、和poi两个包

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.0.5</version>
</dependency>

转换器IntegerNullableConverter.java

package com.learning.easyexcel.converter;

import com.alibaba.excel.converters.NullableObjectConverter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * null转换
 */
public class IntegerNullableConverter implements NullableObjectConverter<Integer> {
    @Override
    public Class<Integer> supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.NUMBER;
    }

    @Override
    public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return cellData.getNumberValue().intValue();
    }

    @Override
    public WriteCellData<?> convertToExcelData(Integer integer, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (Objects.isNull(integer)) {
            return new WriteCellData<>("-");
        } else {
            return new WriteCellData<>(BigDecimal.valueOf(integer));
        }
    }
}

使用注解绑定转换器

@ExcelProperty(value = "测试null值转换", converter = IntegerNullableConverter.class)
// 单元格右对齐(默认int类型右对齐,字符串左对齐)
@ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.RIGHT)
private Integer testNull;

生成表格

/**
     * 测试null值转换
     */
@Test
public void exportNullColumn() {
    Consumer<ExcelWriter> consumer = writer -> {
        List<Student> students = generateStudent(2);
        students.get(0).setTestNull(100);
        writer.write(students, EasyExcel.writerSheet("学生信息")
                     .registerWriteHandler(new FreezeNameHandler()) // 冻结姓名列
                     .head(Student.class)
                     .build());
    };
    export("D:/报表.xlsx", consumer);
}

效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值