无法使用 Apache POI 删除空行 Excel 文件 [英] Unable to delete the Empty Rows Excel File using Apache POI

查看:40
本文介绍了无法使用 Apache POI 删除空行 Excel 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试我的代码来删除我的 excel 文件中的空行!我的代码是:

I have been trying my code to delete the empty rows inside my excel file! my code is:

private void shift(File f){
    File F=f;
    HSSFWorkbook wb = null;
    HSSFSheet sheet=null;
    try{
        FileInputStream is=new FileInputStream(F);

         wb= new HSSFWorkbook(is);
         sheet = wb.getSheetAt(0);
         for(int i = 0; i < sheet.getLastRowNum(); i++){
if(sheet.getRow(i)==null){
    sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
    i--;
}
}

FileOutputStream fileOut = new FileOutputStream("C:/juni1.xls");
wb.write(fileOut);
fileOut.close();
        //Here I want to write the new update file without empty rows! 
    }
    catch(Exception e){
        System.out.print("SERRO "+e);
    }

}

代码根本没有效果.任何人都可以告诉我有什么问题请帮助我自过去 10 个小时以来我一直在尝试做这件事.提前致谢!

The code has no effect at all. Can any body tell me what is the problem please help me i have been trying to do the thing since last 10 hours. thanks in advance!

推荐答案

任意一行为空会有两种情况.

There will be two cases when any row is blank.

  1. 首先,Row 位于其他行之间,但永远不会被初始化或创建.在这种情况下,Sheet.getRow(i) 将为 null.
  2. 其次,Row 已创建,它的单元格可能会或可能不会被使用,但现在它的所有单元格都是空白的.在这种情况下Sheet.getRow(i) 不会为空.(您可以使用 Sheet.getRow(i).getLastCellNum() 来检查它,它会始终显示与其他行相同的计数.)
  1. First, the Row is in between the other rows, but never be initialized or created. In this case Sheet.getRow(i) will be null.
  2. And Second, the Row was created, its cell may or may not get used but now all of its cells are blank. In this case Sheet.getRow(i) will not be null. (you can check it by using Sheet.getRow(i).getLastCellNum() it will always show you the count same as other rows.)

一般情况下会出现第二种情况.也许在你的情况下,这应该是原因.为此,您需要添加额外的条件来检查所有单元格是否为空.

In general case the second condition occurs. Perhaps in your case, it should be the reason. For this you need to add additional condition to check whether all the cells are blank or not.

    for(int i = 0; i < sheet.getLastRowNum(); i++){
        if(sheet.getRow(i)==null){
            sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
            i--;
        continue;
        }
        for(int j =0; j<sheet.getRow(i).getLastCellNum();j++){
            if(sheet.getRow(i).getCell(j).toString().trim().equals("")){
                isRowEmpty=true;
            }else {
                isRowEmpty=false;
                break;
            }
        }
        if(isRowEmpty==true){
            sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
            i--;
        }
    }

这篇关于无法使用 Apache POI 删除空行 Excel 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆