【问题标题】:Getting wrong numeric values from Excels first column从 Excel 第一列获取错误的数值
【发布时间】:2014-04-22 14:46:24
【问题描述】:

我使用 Apache-poi 3.8 阅读 Excel 电子表格 (.xlsx)。当我尝试从 0 列索引的单元格中获取数值时,我得到了错误的数值。

例如我的桌子是这样的

+-----------+---------+---------+
| Header1   | Header2 | Header3 |
+-----------+---------+---------+
| 123456789 | AA      | BB      |
|     99999 | CC      | DD      |
+-----------+---------+---------+

我开始阅读行索引 1 和单元格索引 0。它应该返回 123456789,但它返回错误值 13。下一列是正确的,即使它是数值。如果第一个单元格包含字符串,它也会返回正确的值。第 2 行单元格 0 读起来像 14,接下来的列是正确的。

我从第一列得到的数字在某种程度上与工作表中的行数有关,如果我有 6 行,它开始返回 16,17,18,19,20。它不应该与其他框架相关,但我使用 myfaces tomahawk 和 jsf 1.2 上传我的 Excel 文件。

public String getCellStr(final int x, final int y) {
    String cellValue = "";
    try {
        Row row = sheet.getRow(x);
        Cell cell = row.getCell(y);
        if (row == null || (row != null && cell == null)) {
            cellValue = "";
        } else {
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                cellValue = cell.toString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    cellValue = DateUtils.date2String(cell.getDateCellValue());
                } else {
                    Double value = cell.getNumericCellValue();
                    Long longValue = value.longValue();
                    cellValue = longValue.toString();
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                cellValue = new String(new Boolean(
                                  cell.getBooleanCellValue()).toString());
                break;
            case Cell.CELL_TYPE_BLANK:
                cellValue = "";
                break;
            }
        }
    } catch (NullPointerException e) {
        return cellValue;
    }
    return cellValue;
}

【问题讨论】:

  • 不要使用 new String(...),不需要 toString 已经返回一个 String 对象。
  • 另外,我不认为 excel 索引从零开始,而是从一开始。所以尝试获取索引为 1 的列。
  • 您好,先将单元格格式设置为String,再读取后再读取..可以设置为cell.setCellType(Cell.CELL_TYPE_STRING);然后使用您的代码读取 cell.getNumericCellValue();
  • @Lawrence 它从零开始,我试过了。
  • @user1763507 我也试过你的方法,但没有区别。

标签: java excel apache-poi


【解决方案1】:

我终于找到了我的错误。这段代码是造成这种奇怪行为的原因。显然我不能将单元格转换为其他类型并在不破坏值的情况下将其转换回去。

int cellType = cell.getCellType();
cell.setCellType(Cell.CELL_TYPE_STRING);
String val = cell.getStringCellValue();
cell.setCellType(cellType);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 2019-08-14
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多