错误:如何读取Excel中的空单元格

我试图从使用POI的Excel中读取数据。 我怎样才能检查这是一个空的单元格?

我不知道什么是缺less我认为这应该是工作:

java.util.Iterator<Row> rows = worksheet.rowIterator(); HSSFRow row = (HSSFRow) rows.next(); HSSFCell cellF1 = (HSSFCell) row.getCell(5); if(cellF1.getCellType() == HSSFCell.CELL_TYPE_BLANK) { String val = ""; } 

我得到了错误,如果语句(空指针),但只有当我使用这个我可以检查:

  while (rows.hasNext()) { HSSFRow row = (HSSFRow) rows.next(); java.util.Iterator<Cell> cells = row.cellIterator(); while (cells.hasNext()) { HSSFCell cell = (HSSFCell) cells.next(); if(cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) { String emptytype = ""; System.out.println("empty"); } } } 

这是Row.getCell单参数版本的正常行为。 如果您查看API文档,则明确指出如果未定义单元格,则getCell将返回null。 许多Java函数都performance出这种行为,所以考虑到这一点,编码没有任何问题。 所以,你的代码的一个版本可能是这样的:

 boolean hasDataFlag = true; HSSFRow row = sheet.getRow(rowNumber); hasDataFlag = (row != null); HSSFCell cell = null; if (hasDataFlag) cell = row.getCell(cellNumber); hasDataFlag = (cell != null); if (hasDataFlag) hasDataFlag = (cell.getCellType() != Cell.CELL_TYPE_BLANK); if (hasDataFlag) { // process the cell here } 

或者,您可以使用Row.getCell的另一个版本,该版本的第二个参数指定缺less的单元策略。 该版本将允许您指定getCell为空单元格返回空单元格。 所以,这是一些替代的代码:

 HSSFRow row = sheet.getRow(rowNumber); if (row != null) { HSSFCell cell = row.getCell(cellNumber, Row.RETURN_BLANK_AS_NULL); if (cell != null) { // process cell here } } 

或者,如果您愿意,可以将该策略指定为Row.CREATE_NULL_AS_BLANK 。 在这种情况下,用if (cell.getCellType() != Cell.CELL_TYPE_BLANK)replaceif (cell != null) if (cell.getCellType() != Cell.CELL_TYPE_BLANK)

如果使用CellIterator ,则只会获得已经在某个点定义的单元格(没有null单元格,但会得到blank单元格)。 如果你想获得所有单元格,请通过索引获取它们

按索引,你可以做一些事情:

  Sheet sheet = workbook.getSheetAt(0); for (int rowNumber = sheet.getFirstRowNum(); rowNumber <= sheet.getLastRowNum(); rowNumber++) { Row row = sheet.getRow(rowNumber); if (row == null) { // This row is completely empty } else { // The row has data for (int cellNumber = row.getFirstCellNum(); cellNumber <= row.getLastCellNum(); cellNumber++) { Cell cell = row.getCell(cellNumber); if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) { // This cell is empty } else { // This cell has data in it } } } } 
 int column, rownumber = 0; // just for showing the example code Row row = sheet1.getRow(rownumber); // just for showing the example code if (row!= null) mycell = row.getCell(0); if (mycell != null && mycell.getCellType() != Cell.CELL_TYPE_BLANK) { System.out.println(mycell.getStringCellValue()); } else{ System.out.println("whatever"); } 

public String getCellData(String File_Name,int Sheet_Num,int Row_Num,int Col_Num)throws IOException {

  FileInputStream fileIn = new FileInputStream(System.getProperty("user.dir")+"\\"+File_Name+".xlsx"); XSSFWorkbook workbook = new XSSFWorkbook(fileIn); XSSFSheet sheet=workbook.getSheetAt(Sheet_Num-1); XSSFRow row = sheet.getRow(Row_Num-1); XSSFCell cell= row.getCell(Col_Num-1); String celldata; if(cell!=null){ celldata= cell.getStringCellValue(); } else celldata =""; fileIn.close(); return celldata; }