无法使用Apache POI删除空行Excel文件

use*_*503 2 java excel row apache-poi

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

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

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

San*_*ngh 6

当任何行为空时,将出现两种情况.

  1. 首先,Row位于其他行之间,但从不进行初始化或创建.在这种情况下,Sheet.getRow(i)将为null.
  2. 第二,Row被创建了,它的单元格可能会被使用,也可能不会被使用,但现在它的所有单元格都是空白的.在这种情况下,Sheet.getRow(i)不会为null.(您可以使用Sheet.getRow(i).getLastCellNum()来检查它,它将始终显示与其他行相同的计数.)

在一般情况下,发生第二种情况.也许在你的情况下,它应该是原因.为此,您需要添加其他条件以检查所有单元格是否为空白.

    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--;
        }
    }
Run Code Online (Sandbox Code Playgroud)