如何使用Apache POI检查excel单元格是否为空?

我正在使用Poi.jar从excel表中获取输入,并想知道如何检查单元格是否为空。

现在我使用下面的代码。

cell = myRow.getCell(3); if (cell != null) { cell.setCellType(Cell.CELL_TYPE_STRING); //System.out.print(cell.getStringCellValue() + "\t\t"); if (cell.getStringCellValue() != "") depend[p] = Integer.parseInt(cell.getStringCellValue()); } } 

怎么样:

  Cell c = row.getCell(3); if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) { // This cell is empty } 

Gagravarr的答案非常好!


检查excel单元格是否为空

但是如果你假设一个单元格也是空的,如果它包含一个空字符串 (“”),你需要一些额外的代码。 如果没有正确清除单元格,可能会发生这种情况(有关如何执行此操作,请参见下文)。

我给自己写了一个帮助来检查XSSFCell是否为空(包括一个空字符串)。

  /** * Checks if the value of a given {@link XSSFCell} is empty. * * @param cell * The {@link XSSFCell}. * @return {@code true} if the {@link XSSFCell} is empty. {@code false} * otherwise. */ public static boolean isCellEmpty(final XSSFCell cell) { if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) { return true; } if (cell.getCellType() == Cell.CELL_TYPE_STRING && cell.getStringCellValue().isEmpty()) { return true; } return false; } 

此JUnit测试显示需要额外空检查的情况。

场景:在Java程序中更改单元格的内容。 稍后,在同一Java程序中,检查单元格是否空白。 如果isCellEmpty(XSSFCell cell)函数未检查空字符串,则测试将失败。

 @Test public void testIsCellEmpty_CellHasEmptyString_ReturnTrue() { // Arrange XSSFCell cell = new XSSFWorkbook().createSheet().createRow(0).createCell(0); boolean expectedValue = true; boolean actualValue; // Act cell.setCellValue("foo"); cell.setCellValue("bar"); cell.setCellValue(""); actualValue = isCellEmpty(cell); // Assert Assert.assertEquals(expectedValue, actualValue); } 

另外:正确清理细胞

以防万一有人想知道,如何正确清除单元格的内容。 存档有两种方法(我建议方法1 )。

 // way 1 public static void emptyCell(final XSSFCell cell) { cell.setCellType(Cell.CELL_TYPE_BLANK); } // way 2 public static void emptyCell(final XSSFCell cell) { String nullString = null; cell.setCellValue(nullString); } 

有用的来源

  • CellTypes
  • XSSFCell.setCellValue(字符串)
  • Cell.setCellType(单元格类型)

问候winklerrr

还有另一种选择。

 row=(Row) sheet.getRow(i); if (row == null || isEmptyRow(row)) { return; } Iterator cells = row.cellIterator(); while (cells.hasNext()) {} 
 .getCellType() != Cell.CELL_TYPE_BLANK 
 Cell cell = row.getCell(x, Row.CREATE_NULL_AS_BLANK); 

这个技巧对我有很大帮助,看看它对你有用

从Apache POI 3.17开始,您必须使用枚举检查单元格是否为空:

 import org.apache.poi.ss.usermodel.CellType; if(cell == null || cell.getCellTypeEnum() == CellType.BLANK) { ... } 

首先要避免NullPointerException,你必须添加这个Row.MissingCellPolicy.CREATE_NULL_AS_BLANK这将创建一个空白单元而不是给你NPE然后你可以检查以确保没有任何问题,就像@Gagravarr所说的那样。

 Cell cell = row.getCell(j, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) // do what you want 

在最新的POI API中不推荐使用Cell.getCellType() 。 如果您使用的是POI API 3.17版,请使用以下代码:

 if (Cell.getCellTypeEnum() == CellType.BLANK) { //do your stuff here }