首页 文章

使用Apache POI从Excel中读取单元格中的问题

提问于
浏览
1

我正在尝试使用Apache POI读取旧的(2007年之前和XLS)Excel文件 . 我的程序到达行的末尾并重复迭代,直到找到不为null或为空的内容 . 然后它重复几次并抓取那些细胞 . 此程序可以很好地读取Office 2010中生成的XLSX和XLS文件 .

我收到以下错误消息:

Exception in thread "main" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    at java.lang.Double.parseDouble(Unknown Source)

在线:

num = Double.parseDouble(str);

从代码:

str = cell.toString();

if (str != "" || str != null) {
    System.out.println("Cell is a string");
    num = Double.parseDouble(str);
} else {
    System.out.println("Cell is numeric.");
    num = cell.getNumericCellValue();
}

cell 是文档中's not empty or null. When I try to print the first cell that'不为空或为空的最后一个单元格,它没有打印任何内容,所以我认为我没有正确访问它 .

3 回答

  • 2

    评估细胞类型然后做你需要的更好 . 我使用此代码来处理单元格数据(检查我是否处理空白单元格):

    switch (cell.getCellType()) {
        case Cell.CELL_TYPE_STRING:
            str = cell.toString().trim();
            break;
        case Cell.CELL_TYPE_NUMERIC:
            if (DateUtil.isCellDateFormatted(cell)) {
                //you should change this to your application date format
                objSimpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
                str = objSimpleDateFormat.format(cell.getDateCellValue());
            } else {
                num = cell.getNumericCellValue();
                str = String.valueOf(cell.getNumericCellValue());
            }
            break;
        case Cell.CELL_TYPE_BLANK:
            str = "";
            break;
        case Cell.CELL_TYPE_ERROR:
            str = "";
            break;
        case Cell.CELL_TYPE_BOOLEAN:
            str = String.valueOf(cell.getBooleanCellValue());
        break;
    }
    
  • 0

    也许您正在读取空白单元格的原因是由于使用了正确的Apache POI子组件来读取Excel文件 . 对于XLS格式使用HSSF(可怕的SpreadSheet格式),对XLSX格式使用XSSF(XML SpreadSheet格式) .


    至于代码本身,您可能希望优化布尔表达式 . 你现在的方式,因为你正在使用或运算符( || ),

    • 如果 str != null ,则执行if语句的第一部分

    • 如果 str == null ,将执行if语句的 else 部分 .

    如果 str 无法解析为数字,那么if语句的第一部分将抛出 NumberFormatException 来调用 Double.parseDouble .

    也许以下代码段可以帮助您:

    if (str == null || str.trim().isEmpty()) {
        // handle null and empty strings
    } else if (cell.getType() == Cell.CELL_TYPE_NUMERIC) {
        System.out.println("Cell is numeric.");
        num = cell.getNumericCellValue();
    } else {
        // If the cell is not numeric, Double.parseDouble(str) 
        // will most likely throw a NumberFormatException
    }
    

    要了解有关 Cell 的更多信息,请阅读Javadoc .

  • 3

    如果我们都知道什么代码行号导致了异常,那将是很好的 .

    我怀疑你的第一行代码是原因 . 对象单元格可以为null,并且无法将空地址转换为String类型 . 您可以按代码查看 .

    注意:代码适用于Office 2010,但我认为这种类型的问题可能发生在任何Excel版本中 .

相关问题