use*_*633 4 java excel apache-poi
我有一个 3000 行的 excel 文件。我删除了 2000(使用 ms excel 应用程序),但是当我从代码中调用 sheet.getLastRowNum() 时,它给了我 3000(而不是 1000)。如何删除空白行?
我从这里尝试了代码,但它不起作用......
有两种方法:
1.)无代码:复制你的excel的内容并粘贴到一个新的excel中,稍后根据需要重命名。
2.)使用代码(我没有找到它的任何函数,所以我创建了自己的函数):
您需要检查每个单元格是否有任何类型的空白/空字符串/空类型的东西。在处理行之前(我希望你正在处理行,我也在使用org.apache.poi.xssf.usermodel.XSSFRow),放置一个if检查,并在if(condition) 中检查这个方法的返回类型,如果确实,这意味着行(XSSFRow)有一些值,否则将迭代器移动到下一行
public boolean containsValue(XSSFRow row, int fcell, int lcell)
{
boolean flag = false;
for (int i = fcell; i < lcell; i++) {
if (StringUtils.isEmpty(String.valueOf(row.getCell(i))) == true ||
StringUtils.isWhitespace(String.valueOf(row.getCell(i))) == true ||
StringUtils.isBlank(String.valueOf(row.getCell(i))) == true ||
String.valueOf(row.getCell(i)).length() == 0 ||
row.getCell(i) == null) {}
else {
flag = true;
}
}
return flag;
}
Run Code Online (Sandbox Code Playgroud)
所以最后你的处理方法看起来像
.
.
.
int fcell = row.getFirstCellNum();// first cell number of excel
int lcell = row.getLastCellNum(); //last cell number of excel
while (rows.hasNext()) {
row = (XSSFRow) rows.next();//increment the row iterator
if(containsValue(row, fcell, lcell) == true){
.
.
..//processing
.
.
}
}
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助。:)