在Excel中的空行

时间:2016-03-23 06:38:22

标签: java apache-poi

我有一张包含5条记录的Excel工作表,我必须将连续的前4个单元格添加到对象列表中,并忽略其余的单元格。如果前4个单元格为空或空白,那么我需要忽略该行并且没有添加到对象中。捕获是有一些记录,其中行前4个单元格是空的但在该单元格之后有一些值。我不想在对象中包含这些行。我试着写一段代码:

public static boolean isRowEmpty(Row row){
         for(int c = row.getFirstCellNum(); c<row.getLastCellNum();c++){
             Cell cell = row.getCell(c);
             if(cell!=null && cell.getCellType()!=Cell.CELL_TYPE_BLANK){
                 return false;
             }
         }
         return true;
    }

if(isRowEmpty(row)==false){
   compList.add(compItem);
}

这段代码仅在row为空且isRowEmpty()方法返回true时才有效。到目前为止很好,它没有增加列表的价值。如果前4个单元格为空并且rest单元格连续有值,则isRowEmpty()返回false,并将null值设置为object对象。有人可以建议我解决它吗?

2 个答案:

答案 0 :(得分:2)

您正在检查行中的所有元素。如果将检查的元素数量限制为行中的前4个,则可以达到预期的结果。

public static boolean isRowEmpty(Row row){
         int firstCol = row.getFirstCellNum();
         for(int cnt = 0; cnt<4 ; cnt++){
             Cell cell = row.getCell(firstCol+cnt);
             if(cell!=null && cell.getCellType()!=Cell.CELL_TYPE_BLANK){
                 return false;
             }
         }
         return true;
    }

if(isRowEmpty(row)==false){
   compList.add(compItem);
}

答案 1 :(得分:1)

我仍然不完全确定问题是什么。我最好的猜测是你要检查每行的前4列。如果4个单元格为空,则忽略该行。

问题是当单元格存在于第四列之后的列中时,它们会被添加到列表中(而不是忽略该行)。

如果是这种情况,那么这应该有所帮助:

public static boolean isRowEmpty(Row row){
         for(int c = row.getFirstCellNum(); c < 4 && c < row.getLastCellNum(); c++){
             Cell cell = row.getCell(c);
             if(cell!=null && cell.getCellType()!=Cell.CELL_TYPE_BLANK){
                 return false;
             }
         }
         return true;
    }

if(isRowEmpty(row)==false){
   compList.add(compItem);
}