如何在读取excel文件时识别单元格为空白或空或空

我读了一个excel文件来传递一些数据字段的input。 但是当我运行程序时,一些单元格值返回为空,有些是空白的。实际上,当我打开Excel文件时,单元格中没有可用的值。

我怎样才能手动确定一个Excel单元格为空或空白。

对于一些场景,我需要将空白值传递给字段。 如果单元格为空,则无法将值传递给字段。

引导我伸出手。

码:

public static void readAllData() throws IOException{ Object result = null; String sheetName = "Testsheet"; String filePathxlsx = "C:/Users/MSTEMP/Documents/Files/Testxssf.xlsx"; try { FileInputStream in = new FileInputStream(filePathxlsx); File file = new File(filePathxlsx); if(file.isFile() && file.exists()){ XSSFWorkbook xworkbook = new XSSFWorkbook(in); XSSFSheet xsheet=xworkbook.getSheet(sheetName); int totalRows = xsheet.getLastRowNum(); for(int row =1; row<totalRows;row++){ xrow=xsheet.getRow(row); int totalCells=xrow.getLastCellNum(); for(int cell =0; cell<totalCells;cell++){ if(xrow != null) { xcell= xrow.getCell(cell); if(xcell!=null) { switch (xcell.getCellType()) { case Cell.CELL_TYPE_NUMERIC:// numeric value in excel if(DateUtil.isCellDateFormatted(xcell)){ Date myDate = xcell.getDateCellValue(); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy", Locale.US); result = formatter.format(myDate); //System.out.println("Today : " + result); } else{ result = new BigDecimal(xcell.getNumericCellValue()).toPlainString(); } break; case Cell.CELL_TYPE_STRING: // string value in excel result = xcell.getStringCellValue(); break; case Cell.CELL_TYPE_BOOLEAN: // boolean value in excel result = xcell.getBooleanCellValue(); break; case Cell.CELL_TYPE_BLANK: // blank value in excel result = xcell.getStringCellValue(); break; case Cell.CELL_TYPE_ERROR: // Error value in excel result = xcell.getErrorCellValue()+""; break; } } else { System.out.println("Cell is empty"); } System.out.println("Value "+result); } else { System.out.println("Row is empty"); } } } } inputStream.close(); } catch (Exception ex){ ex.printStackTrace(); } 

}

不知道为什么你要手动识别单元格types,但是如果你想把case“null”或“blank”作为一个case来处理,你可以使用另一个版本的Row.getCell,它接受第二个参数来指定丢失的单元格政策 。

所以:

  xcell= xrow.getCell(cell); 

会变成 :

  xcell = xrow.getCell(cell, Row.RETURN_NULL_AS_BLANK); 

所以在任何情况下,单元格有一个值或是空白的,但从不为空。