Java POI讀取excel中數值精度損失
描述:
excel 單元格中,純數字的單元格,讀取后 后面會加上 .0 。
例如: 1 --> 1.0
而使用下面的方法,可能會對小數存在精度損失
cell.setCellType(CellType.STRING); //讀取前將單元格設置為文本類型讀取
例如: 2.2 --> 2.1999999997
目前的解決辦法:
一. 將excel單元格改為文本類型。
注意,直接修改單元格屬性不管用, 使用 分列 的方式,可以實現將數值改為文本類型。
二. java處理
public class CommonUtil {
private static NumberFormat numberFormat = NumberFormat.getNumberInstance();
static {
numberFormat.setGroupingUsed(false);
}
public static String getCellValue(Cell cell) {
if (null == cell) {
return "";
}
Object value;
switch (cell.getCellTypeEnum()) {
// 省略
case NUMERIC:
double d = cell.getNumericCellValue();
value = numberFormat.format(d); // 關鍵在這里!
//省略
}
return value == null ? "" : value.toString();
}
}
上面的方法可以獲取一個正確的數值
