当前位置: 首页 > news >正文

easyExcel2.2.10中为0数据显示为空

在 EasyExcel 2.2.10 中,如果希望将数值为 0 的数据在 Excel 中显示为空(即不显示 0),可以通过以下方法实现:

1. 使用 @ExcelProperty 的 format 参数

通过设置单元格格式为 ## 会忽略 0),将 0 显示为空:

@ExcelProperty(value = "数量", format = "#")
private Integer quantity;

此时,若字段值为 0,Excel 单元格会显示为空。


2. 自定义 Converter 过滤零值

通过自定义 Converter 将 0 转换为空字符串:

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ZeroToEmptyConverter implements Converter<Integer> {

    @Override
    public Class supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }

    @Override
    public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return 0;
    }

    @Override
    public CellData convertToExcelData(Integer value, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (value == null || value == 0) {
            return new CellData<>(""); // 如果值为 0 或 null,则返回空字符串
        }
        return new CellData<>(value.toString()); // 否则正常写入
    }
}

3. 检查数据源

确保字段的值为 0(而非 null 或其他值):

// 示例数据对象
YourDataClass data = new YourDataClass();
data.setQuantity(0); // 明确设置为 0

4. 使用 @ExcelIgnore 注解(可选)

如果需要在特定条件下忽略 0 的写入,可以结合业务逻辑动态处理:

public class YourDataClass {
    private Integer quantity;

    @ExcelIgnore
    public boolean isQuantityZero() {
        return quantity != null && quantity == 0;
    }

    @ExcelProperty("数量")
    public String getQuantityForExcel() {
        return (quantity == null || quantity == 0) ? "" : quantity.toString();
    }
}

效果验证

  • 导出 Excel 后,数值为 0 的单元格会显示为空。

  • 如果数值为非零(如 1-5),则正常显示。

相关文章:

  • 基于深度学习的行人人脸识别系统的设计与实现
  • 【 <二> 丹方改良:Spring 时代的 JavaWeb】之 Spring Boot 中的日志管理:Logback 的集成
  • LeetCode-215. 数组中的第K个最大元素
  • 解决MediaMetadataRetriever.finalize()超时问题
  • CUDA与GPU架构:解锁并行计算的终极奥义
  • 2025中国AI Agent 行业研究报告|附文件下载
  • 《TCP/IP网络编程》学习笔记 | Chapter 21:异步通知 I/O 模型
  • Charles抓HTTPS包
  • 调用百度api实现语音识别(python)
  • CLion Debug查看指针数组元素
  • Kubernetes(k8s)-Pod亲和性(Affinity)和反亲和性(Anti-affinity)
  • PAQ压缩算法
  • 自动驾驶系统的车辆动力学建模:自行车模型与汽车模型的混合策略及自动驾驶分层控制架构
  • 3.24-3 接口测试断言
  • 面试中如何回答性能优化的问题
  • C语言 【实现电脑关机小游戏】非常好玩
  • java实现coze平台鉴权+工作流调用(踩坑记录)
  • 大数据(2)Hadoop架构深度拆解:HDFS与MapReduce企业级实战与高阶调优
  • 在 Kubernetes 中部署 Trivy 漏洞扫描服务
  • 力扣DAY24 | 热100 | 回文链表
  • 上海营商环境的“分寸”感:底线之上不断拓宽自由,底线之下雷霆制止
  • 重温经典|中国首部剪纸动画片《猪八戒吃瓜》创作始末
  • 甘肃省政府原党组成员、副省长杨子兴被提起公诉
  • 48岁黄世芳履新中国驻毛里求斯大使,曾在广西工作多年
  • 南京明孝陵石兽遭涂鸦“到此一游”,景区:已恢复原貌,警方在排查
  • 伊朗港口爆炸最新事故调查报告公布,2名管理人员被捕