讀取excel中的值 (處理公式取值及讀取的數字精度問題)

/**
 * 讀具體數值
 *
 * @param cell
 * @return
 */

//處理公式中讀取出來的數字精度問題
private static NumberFormat numberFormat = NumberFormat.getInstance();

static {
    numberFormat.setGroupingUsed(false);
}

public static String getCellValue(Cell cell) {
    String value = null;
    if (cell != null) {
        // 把數字當成String來讀,避免出現1讀成1.0的情況
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_FORMULA:
                // cell.getCellFormula();
                try {
                    //處理公式中讀取出來的數字精度問題
                    value = numberFormat.format(cell.getNumericCellValue());
                    //  value = String.valueOf(cell.getNumericCellValue());
                } catch (IllegalStateException e) {
                    value = String.valueOf(cell.getRichStringCellValue());
                }
                break;
            case Cell.CELL_TYPE_NUMERIC:
                value = String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING:
                value = String.valueOf(cell.getRichStringCellValue());
                break;
        }
    }
    return value;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章