package com.linghu.listener; import com.alibaba.excel.converters.Converter; 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; /** * 自定义转换器:将BigDecimal转换为带%的字符串(如25.5 → 25.5%) */ public class BigDecimalPercentConverter implements Converter { @Override public Class supportJavaTypeKey() { return BigDecimal.class; // 支持的Java类型 } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; // Excel中显示为字符串类型 } /** * 写入Excel时:将BigDecimal转换为带%的字符串 */ @Override public WriteCellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (value == null) { return new WriteCellData<>(""); // 空值处理 } // 拼接%符号(如需保留固定小数位,可使用setScale处理,如value.setScale(2, BigDecimal.ROUND_HALF_UP)) return new WriteCellData<>(value.toString() + "%"); } /** * 读取Excel时:如果需要从带%的字符串转回BigDecimal,可实现此方法 * (当前场景仅导出,暂时返回null即可) */ @Override public BigDecimal convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return null; } }