实体类 属性类型为 BigDecimal
注解 @NumberFormat("#,###.00") 试过了不顶用,原因不太清楚
值为 0.81 这种,导出后变为 .81
所以,换个思路,写个转换器,就是麻烦点
转换器
BigDecimalConvert
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;import java.math.BigDecimal;/*** @Package_Name * @Author Leslie Lee* @TIME* @Version*/
public class BigDecimalConvert implements Converter<BigDecimal> {@Overridepublic Class<?> supportJavaTypeKey() {return Converter.super.supportJavaTypeKey();}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {return Converter.super.supportExcelTypeKey();}@Overridepublic BigDecimal convertToJavaData(ReadConverterContext<?> context) throws Exception {return Converter.super.convertToJavaData(context);}@Overridepublic WriteCellData<?> convertToExcelData(WriteConverterContext<BigDecimal> context) throws Exception {String val = context.getValue().toString();if (!StrUtil.isEmpty(val)) {if (!val.contains(".")) {//没有小数点 加 . 并补零val = val + ".00";} else if (val.indexOf(".") == val.length() - 2) {//一位小数 补零val = val + "0";}int decimalIndex = val.indexOf('.');// 假设val为 19569.12String integerPart = val.substring(0, decimalIndex);// 19569String decimalPart = val.substring(decimalIndex);// .12StringBuilder formattedNum = new StringBuilder();int count = 0;for (int i = integerPart.length() - 1; i >= 0; i--) {// 循环前部分加入千分位formattedNum.insert(0, integerPart.charAt(i));count++;if (count % 3 == 0 && i != 0) {// 三个字符一加formattedNum.insert(0, ",");}}formattedNum.append(decimalPart);return new WriteCellData<>(formattedNum.toString());}return new WriteCellData<>(val);}
}
使用方式
@ExcelProperty(value = "金额",converter = BigDecimalConvert.class)
Leslie Lee 随笔