在 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
),则正常显示。