2014-09-25 49 views
0

我正在使用Apache POI读取Java中特定的Excel模板。底部有一些不需要的字段(如小指南),我需要跳过。所以我想在POI发现一行完全空白时停止迭代,因此底部的字段将被自动跳过。如何在Java中使用Apache POI停止迭代

我发现了很多方法来处理一个空白的细胞,但我的要求是一个完整的行。

+0

Apache的POI支持[通过行和细胞迭代的两种不同的方式(http://poi.apache.org/spreadsheet/quick-guide.html#Iterator),其中之一是您使用? – Gagravarr 2014-09-25 14:56:29

+0

我在使用Renju在他的回答中显示的相同方法。虽然我没有想到挽救伯爵。他的代码工作。不管怎么说,还是要谢谢你。 – thedonsmind 2014-09-26 05:55:19

回答

0

以下代码将遍历一行的单元格。它会为每个遇到的单元格保留一个计数(cellCount)。另一个couont(nullCount),仅在单元格为空时递增。如果这两个计数相等,则行是空的。

boolean isEmptyRow = false; 
      int cellCount = 0; 
      int nullCount = 0; 

       Iterator<Cell> cellIterator = row.iterator(); 
       while (cellIterator.hasNext()) { 
        cellCount++; 
        Cell cell = (Cell) cellIterator.next(); 
        if ((cell == null) 
          || ((cell != null) && (cell.getCellType() == Cell.CELL_TYPE_BLANK))) { 
         nullCount++; 
        } 
       } 

      if ((cellCount != 0) && (nullCount != 0) 
        && (cellCount == nullCount)) {  //If nullCount & cellCouont are same, Row is empty 
       isEmptyRow = true; 
      } 
+0

工作出色。好想法。非常感谢。 – thedonsmind 2014-09-26 05:53:54

+0

欢迎您:) – Renjith 2014-09-26 06:26:10

+0

虽然我只是有一个疑问。虽然这对我很有用,但现在它也在第一行空白。意味着它在遇到空白行后停止。在此之前可以阻止它吗? – thedonsmind 2014-09-26 10:13:04