使用Apache POI从Excel中读取单元格中的内容

我正在尝试使用Apache POI来读取旧的(2007之前和XLS)Excel文件。 我的程序进入行的末尾并迭代,直到find不为空或空的东西。 然后迭代几次,抓住这些单元。 此程序在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是文档中不是空的或空的最后一个单元格。 当我尝试打印不是空的第一个单元格时,它不打印任何内容,所以我认为我没有正确访问它。

最好是评估细胞types,然后做你所需要的。 我使用这个代码来处理单元格数据(检查我甚至处理空白单元格):

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

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


至于代码本身,你可能想要改进你的布尔expression式。 你现在的方式,因为你正在使用or运算符( || ),

  • if语句的第一部分将在str != null
  • if语句的else部分将在str == null执行。

if语句的第一部分将在调用Double.parseDouble时抛出NumberFormatException ,如果str不能被parsing为数字。

也许下面的代码片段将帮助你:

 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 。

如果我们都知道哪些代码行号导致exception,那将会很好。

我怀疑你的第一行代码是原因。 对象单元格可能为空,并且空地址不能转换为stringtypes。 您可以通过代码检查。

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