POI導入Excel用String讀取數字類型精度丟失問題解決

業務點:

批量導入訂單,訂單中包含價格,爲4.5,6.7這種格式的。

問題:

poi中需要按照字符串形式拿出來數據,映射成具體的實體類。

在cell.setCellType(Cell.CELL_TYPE_STRING) 即設置按照字符串讀取時發生精度異常

例:8.2取出後就是8.19999993,而7.2則正常

 

因爲是接盤的別人的項目,先貼出原代碼:

    private static String getCellStringValue(Cell cell) {
        if (cell == null) {
            return "";
        } else {
            cell.setCellType(1);
            return cell.getStringCellValue().trim();
        }
    }

後封裝方法用於解決此問題,同時解決科學計數法讀取的問題:

    private static String getCellStringValue(Cell cell) {
        if (cell == null) {
            return "";
        } else {
            if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
                return getRealStringValueOfDouble(cell.getNumericCellValue());
            }
            cell.setCellType(1);
            return cell.getStringCellValue().trim();
        }
    }

 
    private static String getRealStringValueOfDouble(Double d) {
        String doubleStr = d.toString();
        boolean b = doubleStr.contains("E");
        int indexOfPoint = doubleStr.indexOf('.');
        if (b) {
            int indexOfE = doubleStr.indexOf('E');
            BigInteger xs = new BigInteger(doubleStr.substring(indexOfPoint
                    + BigInteger.ONE.intValue(), indexOfE));
            int pow = Integer.valueOf(doubleStr.substring(indexOfE
                    + BigInteger.ONE.intValue()));
            int xsLen = xs.toByteArray().length;
            int scale = xsLen - pow > 0 ? xsLen - pow : 0;
            doubleStr = String.format("%." + scale + "f", d);
        } else {
            java.util.regex.Pattern p = Pattern.compile(".0$");
            java.util.regex.Matcher m = p.matcher(doubleStr);
            if (m.find()) {
                doubleStr = doubleStr.replace(".0", "");
            }
        }
        return doubleStr;
    }

希望對有需要的朋友有幫助!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章