【问题标题】:returning decimal instead of string (POI jar)返回十进制而不是字符串(POI jar)
【发布时间】:2012-09-21 07:48:11
【问题描述】:

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

【问题讨论】:

    标签: java apache-poi xls xlsx


    【解决方案1】:

    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) );
        }
     }
    

    【讨论】:

    • 谢谢 4 你的回复........这对我很有用.......现在我怀疑 POI jar 中间的单元格是否为空,跳过那个细胞.....但我需要返回为空
    • 这里有很多关于空白单元格和 POI 的问题,您最好阅读那些给出的答案
    【解决方案2】:
    //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;
        }
    }
    

    【讨论】:

    • 感谢 4 您的回复.....如果您尝试使用您的样本,它将返回 3.0 而不是 3,如果您的单元格值为 3。尝试使用 Gagravarr 解决方案,它将按原样返回 3
    【解决方案3】:

    使用 switch 和 case 这样的代码:

    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 : 
                            } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 2013-02-11
      • 2010-11-26
      • 1970-01-01
      • 2016-11-07
      相关资源
      最近更新 更多