實體類 屬性類型為?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 隨筆