最近接盘一个别人项目,客户反映数据有问题,抓掉N多头发,最后发现是解析Excel读取单元格时,数字类型数据丢失精度,案例如下:
Excel里面数据
导入后数据
可以看出第二行单价数据已经损失精度,废话不多说,下面贴出解决方案:
public class ExcelUtil {
/**
* 将数据转换为String类型
*
* @param row 单元格
* @param i 第i个
* @return
*/
public static String cellGetString(Row row,int i) {
String cellValue = "";
Cell cell = row.getCell(i);
if (cell == null) {
return cellValue;
}
int cellType = cell.getCellType( );
switch (cellType) {
case Cell.CELL_TYPE_NUMERIC: //数字
double numericCellValue = cell.getNumericCellValue();
cellValue = Double.toString(numericCellValue);
break;
case Cell.CELL_TYPE_STRING: //字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //公式
try {
double numericCellValue1 = cell.getNumericCellValue();
cellValue = Double.toString(numericCellValue1);
} catch (IllegalStateException e) {
cellValue = String.valueOf(cell.getRichStringCellValue());
}
break;
case Cell.CELL_TYPE_BLANK: //空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
//这是原来读取数据的方式
//虽然将所有数据设置成字符串读取很方便
//但读取某些特定数据将会导致数据失真
/*cell.setCellType(Cell.CELL_TYPE_STRING);
try {
cellValue = cell.getStringCellValue( );
} catch (Exception e) {
throw new BizException("数据格式有误");
}
return cellValue;*/
}
}
至于为什么会损失精度,我也没找到,知道的大佬欢迎留言解答!