huliguo
16 小时以前 71746341215e75f2d96a329a4c0f44e61c13aa49
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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<BigDecimal> {
 
    @Override
    public Class<BigDecimal> supportJavaTypeKey() {
        return BigDecimal.class; // 支持的Java类型
    }
 
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING; // Excel中显示为字符串类型
    }
 
    /**
     * 写入Excel时:将BigDecimal转换为带%的字符串
     */
    @Override
    public WriteCellData<String> 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;
    }
}