EasyExcel使用说明,点击链接https://www.yuque.com/easyexcel/doc/read
转Double也可参考该博客
最近使用easyexcel时碰到一个这样的问题,读取excel时出现了小数点精度问题。例如,0.137这个值,使用easyexcel解析后得到的Double对象就变成了0.13700000000000001,5.1,变成5.0999999999999996。
原excel中一条数据,见下图体积
商品名称 | 长(cm) | 宽(cm) | 高(cm) | 体积(cm³) | 重量(Kg) |
按摩油 | 5.1 | 4.0 | 11.6 | 236.64 | 0.137 |
实体类
**
* 商品主数据
*
* @author yk
* @Date 2020-02-26
*/
@Data
public class GoodsTempImportVo {
@ExcelProperty(value = "商品名称")
private String goodsName;
@ExcelProperty(value = "长(cm)")
private BigDecimal length;
@ExcelProperty(value = "宽(cm)")
private BigDecimal width;
@ExcelProperty(value = "高(cm)")
private BigDecimal height;
@ExcelProperty(value = "体积(cm³)")
private BigDecimal volume;
@ExcelProperty(value = "重量(Kg)")
private BigDecimal weight;
}
通过接口导入,打印出数据格式
解析到一条数据:{"goodsName":"按摩油","height":11.6,"length":5.0999999999999996,"volume":236.64,"weight":0.13700000000000001,"width":4}
我尝试去查看了excel解压后的文件,发现这条数据在xml里存储的值就是0.13700000000000001。
当我在把实体类里把BigDecimal的字段修改成String类型后,读出来的数据就是期望的0.137。
查看easyexcel源码,其实easyexcel解析excel单元格的时候,会根据单元格格式选择不同的converter。在本例中,由于是数字类型单元格解析成BigDecimal类型字段,调用的就是BigDecimalNumberConverter 。这个Converter是这样的:
public class BigDecimalNumberConverter implements Converter<BigDecimal> {
public BigDecimalNumberConverter() {
}
public Class supportJavaTypeKey() {
return BigDecimal.class;
}
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.NUMBER;
}
public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
return cellData.getNumberValue();
}
public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
return new CellData(value);
}
}
supportJavaTypeKey方法指定该Converter转换的目标类型是BigDecimal,而easyexcel在讲excel单元格内容转换为BigDecimal时调用的就是convertToJavaData方法。
可以看到该方法内容很简单,就是取了CellData的NumberValue,这是个BigDecimal的对象,debug时会发现,执行到这里时取出来的就已经是0.13700000000000001这个值了。
这没有问题,因为excel文件里存储的本来就是这个值,但是为什么转换成String类型就是0.137呢?
数字类型单元格转换成String类型调用的是另外一个converter:StringNumberConverter,可以看到这个类的convertToJavaData就更复杂一些:
public class StringNumberConverter implements Converter<String> {
public StringNumberConverter() {
}
public Class supportJavaTypeKey() {
return String.class;
}
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.NUMBER;
}
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) {
return DateUtils.format(DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(), contentProperty.getDateTimeFormatProperty().getUse1904windowing(), (TimeZone)null), contentProperty.getDateTimeFormatProperty().getFormat());
} else if (contentProperty != null && contentProperty.getNumberFormatProperty() != null) {
return NumberUtils.format(cellData.getNumberValue(), contentProperty);
} else if (cellData.getDataFormat() != null) {
return DateUtil.isADateFormat(cellData.getDataFormat(), cellData.getDataFormatString()) ? DateUtils.format(DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(), globalConfiguration.getUse1904windowing(), (TimeZone)null)) : NumberUtils.format(cellData.getNumberValue(), contentProperty);
} else {
return NumberUtils.format(cellData.getNumberValue(), contentProperty);
}
}
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
return new CellData(new BigDecimal(value));
}
}
本例中的单元格格式为常规,所以调用的是NumberUtils的format方法,最后是通过ExcelGeneralNumberFormat类的format方法进行的处理。
在这个方法中,我们发现它将excel里解析出的值限制为10位小数,并且做了四舍五入的处理:
// Non-integers of non-scientific magnitude are formatted as "up to 11
// numeric characters, with the decimal point counting as a numeric
// character". We know there is a decimal point, so limit to 10 digits.
// https://support.microsoft.com/en-us/kb/65903
final double rounded = new BigDecimal(value).round(TO_10_SF).doubleValue();
return decimalFormat.format(rounded, toAppendTo, pos);
于是0.13700000000000001经过处理后就变成了0.137。
现在我们有了一个解决这个问题的办法,就是在easyexcel解析生成对象后,对每个BigDecimal字段做一样的处理:
new BigDecimal(value).round(new MathContext(10, RoundingMode.HALF_UP)).doubleValue();
最终整合出一个小方法,仅供参考:
private void convertBigDecimal(Object object) {
try {
Field[] field = object.getClass().getDeclaredFields();
for (int j = 0; j < field.length; j++) {
String type = field[j].getGenericType().toString();
if (type.equals("class java.math.BigDecimal")) {
try {
String name = field[j].getName();
name = name.substring(0, 1).toUpperCase() + name.substring(1);
Method getM = object.getClass().getMethod("get" + name);
BigDecimal value = (BigDecimal) getM.invoke(object);
if (Objects.nonNull(value) && value.compareTo(BigDecimal.ZERO) > 0) {
double newValue = value.round(new MathContext(10, RoundingMode.HALF_UP)).doubleValue();
Method setM = object.getClass().getMethod("set" + name, BigDecimal.class);
setM.invoke(object, BigDecimal.valueOf(newValue));
}
} catch (NoSuchMethodException e) {
LOGGER.error("转换错误 error ", e);
} catch (IllegalAccessException e) {
LOGGER.error("转换错误 error ", e);
} catch (InvocationTargetException e) {
LOGGER.error("转换错误 error ", e);
}
}
}
} catch (RuntimeException e) {
LOGGER.error("转换错误 error ", e);
}
}
这样我们通过解析得到的数据,基本上就和你在office/wps软件上看到的数值一致了。