读取excel中的值 (处理公式取值及读取的数字精度问题)

/**
 * 读具体数值
 *
 * @param cell
 * @return
 */

//处理公式中读取出来的数字精度问题
private static NumberFormat numberFormat = NumberFormat.getInstance();ide

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;
}
相关文章
相关标签/搜索