Gagravarr的回答非常好!
检查Excel单元格是否为空
但是,如果您假设一个单元格包含空字符串(""
)也为空,那么您需要一些额外的代码。这可能会发生,如果一个单元格被编辑然后没有正确清除(有关如何正确清除单元格,请参见下面的进一步操作)。
我写了一个工具来检查一个XSSFCell是否为空(包括空字符串)。
public static boolean isCellEmpty(final XSSFCell cell) {
if (cell == null) {
return true;
}
if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
return true;
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING && cell.getStringCellValue().trim().isEmpty()) {
return true;
}
return false;
}
注意使用更新的POI版本
自版本3.15 Beta 3
起,他们首先将getCellType()
更改为getCellTypeEnum()
,然后在版本4.0
中又改回了getCellType()
。
但最好还是自己仔细检查,因为他们计划在未来版本中再次更改它。
示例
以下JUnit测试显示需要额外检查空值的情况。
场景:单元格的内容在Java程序中更改。稍后,在同一Java程序中,检查该单元格是否为空。如果isCellEmpty(XSSFCell cell)
函数不检查空字符串,则测试将失败。
@Test
public void testIsCellEmpty_CellHasEmptyString_ReturnTrue() {
XSSFCell cell = new XSSFWorkbook().createSheet().createRow(0).createCell(0);
boolean expectedValue = true;
boolean actualValue;
cell.setCellValue("foo");
cell.setCellValue("bar");
cell.setCellValue(" ");
actualValue = isCellEmpty(cell);
Assert.assertEquals(expectedValue, actualValue);
}
另外:正确清除单元格内容
以防有人想知道如何正确清除单元格的内容,有两种方法可以实现(我推荐使用方法1)。
public static void clearCell(final XSSFCell cell) {
cell.setCellType(Cell.CELL_TYPE_BLANK);
}
public static void clearCell(final XSSFCell cell) {
String nullString = null;
cell.setCellValue(nullString);
}
为什么选择第一种方式?显式优于隐式(感谢 Python)
方式 1:将单元格类型明确地设置回空白
。
方式 2:由于在将单元格值设置为null
字符串时产生的副作用,将单元格类型隐式地设置回空白
。
有用的来源
致敬 winklerrr
if(cell.getStringCellValue() != "")
错误,应该改为if(!cell.getStringCellValue().equals(""))
。 - Lion