欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > easyExcel2.2.10中为0数据显示为空

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

2025/4/5 9:22:39 来源:https://blog.csdn.net/qq_36608622/article/details/146474970  浏览:    关键词: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> {@Overridepublic Class supportJavaTypeKey() {return Integer.class;}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {return null;}@Overridepublic Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {return 0;}@Overridepublic 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;@ExcelIgnorepublic boolean isQuantityZero() {return quantity != null && quantity == 0;}@ExcelProperty("数量")public String getQuantityForExcel() {return (quantity == null || quantity == 0) ? "" : quantity.toString();}
}

效果验证

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

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词