POI:如果公式返回空白,则输出空白

我在Excel中有这样一个公式:

=IF(A1="foo";"";"0") 

如果公式返回一个空白值,我想在POI创build的resultiong csv文件中没有值。 如果公式返回0我想在我的CSV文件中为0

这是我的代码的一部分(它总是多less剥离代码的问题):

 Iterator<Row> rowIterator = sheet.rowIterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); boolean isFirst = true; for (int cn = 0; cn < row.getLastCellNum(); cn++) { Cell cell = row.getCell(cn, Row.CREATE_NULL_AS_BLANK); if (!isFirst) { buffer.write(delimiter.getBytes(charset)); } else { isFirst = false; } // Numeric Cell type (0) // String Cell type (1) // Formula Cell type (2) // Blank Cell type (3) // Boolean Cell type (4) // Error Cell type (5) if (cell.getCellType() == 0 || cell.getCellType() == 2) { try { if (DateUtil.isCellDateFormatted(cell)) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); Date value = cell.getDateCellValue(); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); if (cell.getNumericCellValue() < 1) { sdf.applyPattern("HH:mm:ss"); } buffer.write(sdf.format(value).getBytes(charset)); } else { double valueDouble = cell.getNumericCellValue(); if (valueDouble == Math.ceil(valueDouble)) { buffer.write(String.format("%d", (long) valueDouble).getBytes(charset)); } else { valueDouble = round(valueDouble, roundingPlaces); String value = String.valueOf(valueDouble).replace(".", ","); buffer.write(value.getBytes(charset)); } } } catch (Exception e) { // Formula returns a string cell.setCellType(Cell.CELL_TYPE_STRING); String value = cell.getStringCellValue(); buffer.write(value.getBytes(charset)); } } else { cell.setCellType(Cell.CELL_TYPE_STRING); String value = cell.getStringCellValue(); buffer.write(value.getBytes(charset)); } } buffer.write("\r\n".getBytes(charset)); } 

这个代码在每种情况下都会在csv文件中产生一个0 。 它来自线路

 double valueDouble = cell.getNumericCellValue(); 

关于这一点, 文档很清楚:

double getNumericCellValue()

获取单元格的值作为数字。

对于string,我们抛出exception。 对于空白单元格,我们返回一个0.对于公式或错误单元格,我们返回预先计算的值;

如何分析单元格是否包含NULL值?

cell.getCellType() == Cell.CELL_TYPE_BLANK应该为空,否则为false。

编辑:我忘了你有一个公式单元格。 在这种情况下,补充: cell.getCellType() == Cell.CELL_TYPE_FORMULA ? Cell.getCachedFormulaResultType() == Cell.CELL_TYPE_BLANK : cell.getCellType() == Cell.CELL_TYPE_BLANK cell.getCellType() == Cell.CELL_TYPE_FORMULA ? Cell.getCachedFormulaResultType() == Cell.CELL_TYPE_BLANK : cell.getCellType() == Cell.CELL_TYPE_BLANK

另外你也许不应该过滤空白单元格,而是非数字单元格。

我认为你的问题是公式返回一个字符“”或“0”,但你把它当作一个数字。

@llogiq给我带来了正确的轨道!

我在if语句之前添加了下面的代码:

  if (cell.getCellType() == 2 && cell.getCachedFormulaResultType() == 1) { logger.log(Level.DEBUG, "Formula returns a string. (1)"); cell.setCellType(Cell.CELL_TYPE_STRING); String value = cell.getStringCellValue(); buffer.write(value.getBytes(charset)); } else if (cell.getCellType() == 0 || cell.getCellType() == 2) { 

现在公式导致我的CSV文件中的空白字段! 我甚至可以摆脱讨厌的try catch块。 当然,现在我仍然需要对代码进行美化。