java - 处理 apache poi 中的空列

标签 java excel apache-poi

我有一个从 java 程序读取 Excel 工作表的程序。

我正在迭代单元格,如下所示:

Iterator cells = row.cellIterator();
String temp;
StringBuilder sb;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

while (cells.hasNext()) {
Cell cell = (Cell) cells.next();
temp = null;

    switch (cell.getCellType()) {
         case Cell.CELL_TYPE_STRING:
         temp = cell.getRichStringCellValue().getString();
         break;

    case Cell.CELL_TYPE_NUMERIC:

    if (DateUtil.isCellDateFormatted(cell)) {
        temp = sdf.format(cell.getDateCellValue());
       } else {
             temp = df.format(new BigDecimal(cell.getNumericCellValue()));
       }
          break;
          default:
     }
    if (temp == null || temp.equalsIgnoreCase("null")) {
        sb.append("").append(";");
    } else {
        sb.append(temp).append(";");
    }
 }

正如所见,我正在尝试创建一个字符串生成器,其中包含以分号分隔的 excel 行中的值。

问题是,如果列值为空,我希望它在字符串生成器中作为空值并带有两个连续的分号。

但是,调用

Cell cell = (Cell) cells.next();

简单地忽略空单元格并跳转到下一个非空单元格。

所以这条线

if (temp == null || temp.equalsIgnoreCase("null"))

从未遇到过。

如何在迭代器中获取空列值的句柄?

最佳答案

这实际上是this question的重复。 ,等等my answer to that question基本上也完全适合你。

单元迭代器仅迭代文件中定义的单元。如果单元格从未在 Excel 中使用过,它可能不会出现在文件中(Excel 并不总是一致...),因此 POI 不会看到它

如果您想确保命中每个单元格,则应该按索引查找,并检查空单元格(表示该单元格在文件中从未存在过),或者设置 MissingCellPolicy控制如何处理空单元格和空白单元格

因此,如果您确实想要获取每个单元格,请执行以下操作:

Row r = sheet.getRow(myRowNum);
int lastColumn = Math.max(r.getLastCellNum(), MY_MINIMUM_COLUMN_COUNT);

for (int cn=0; cn<lastColumn; cn++) {
   Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
   if (c == null) {
      // The spreadsheet is empty in this cell
   } else {
      // Do something useful with the cell's contents
   }
}

关于java - 处理 apache poi 中的空列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13171870/

相关文章:

java - 跳过了 46 帧!应用程序可能在其主线程上做了太多工作

excel - Powershell等待Excel中执行宏

excel - 将 Range.SpecialCells 与错误处理程序一起使用是个好习惯吗?

java - 如何在Java中将ppt文件转换成pdf文件?

java - 使用多个 Java 工具链运行 Gradle 测试

java - HTTP header 中缺少 Spring WebServiceTemplate SOAPAction

java - 如何在java中调用带有嵌套泛型的构造函数

excel - 使用 "FIND"公式查找与给定字符不同的大小写

java - org.apache.poi.poifs.filesystem.OfficeXmlFileException

java - 兴趣点/Excel : applying formulas in a "relative" way