返回十进制而不是字符串(POI jar)

问题描述 投票:1回答:3

我需要阅读xls或xlsx表。我成功地阅读了工作表,但它返回十进制值而不是字符串(例如:for 3 - 它返回3.0)。我需要按原样读取单元格值。所以我需要以字符串形式返回

java apache-poi xls xlsx
3个回答
2
投票

POI为您提供Excel在文件中存储的确切值。通常,如果您在Excel单元格中编写一个数字,Excel会将其存储为带格式的数字。如果你需要,POI支持为你做格式化(大多数人没有 - 他们希望数字作为数字,以便他们可以使用它们)

你要找的班级是DataFormatter。你的代码就像是

 DataFormatter fmt = new DataFormatter();
 for (Row r : sheet) {
    for (Cell c : r) {
       CellReference cr = new CellRefence(c);
       System.out.println("Cell " + cr.formatAsString() + " is " + 
                          fmt.formatCellValue(c) );
    }
 }

0
投票
//use this method for getting values from excel.It might help u.
private String getCellValue(Cell cell) {
    if (cell == null) {
        return null;
    }
    if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
        return cell.getStringCellValue();
    } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        return cell.getNumericCellValue() + "";
    } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
        return cell.getBooleanCellValue() + "";
    }else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
        return cell.getStringCellValue();
    }else if(cell.getCellType() == Cell.CELL_TYPE_ERROR){
        return cell.getErrorCellValue() + "";
    } 
    else {
        return null;
    }
}

0
投票

使用这个代码的开关和案例:

switch (cell.getCellType()) { 
                    case STRING: 
                        String c = cell.getStringCellValue();

                        break; 
                    case NUMERIC: 
                        int n = (int) cell.getNumericCellValue();

                        break; 
                    case BOOLEAN:
                        boolean b = cell.getBooleanCellValue();

                    break; 
                    default : 
                        } 
© www.soinside.com 2019 - 2024. All rights reserved.