2

我一直在尝试我的代码来删除我的 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);
    }

}

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

4

2 回答 2

6

There will be two cases when any row is blank.

  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--;
        }
    }
于 2013-06-22T19:44:37.237 回答
0

好的,我不确定您遇到问题的确切原因,但我认为这是由于您访问工作簿的方式。假设您发送的文件file是您要使用的 XLS 工作簿的位置。您需要检查的第一件事是该工作簿是否存在,因为 POI 对现有 v 不存在的工作簿的处理不同。这是这样完成的:

HSSFWorkbook wb;
HSSFSheet sheet;
if(file.exists()) {//The workbook has been created already
    wb = (HSSFWorkbook) WorkbookFactory.create(new FileInputStream(file));//Line 1
    sheet = wb.getSheetAt(0);
} else {//No workbook exists at the location the "file" specifies
    wb = new HSSFWorkbook();
    sheet = wb.createSheet();
}

一些注意事项:从和从Line 1抛出 2 个异常。所以要么抛出异常,要么根据你的喜好用 try-catch 包围。IOExceptionjava.io.IOExceptionInvalidFormatExceptionorg.apache.poi.openxml4j.exceptions.InvalidFormatException

现在如果文件总是存在,那么 if-else 语句并不是真正需要的。但是,要正确打开所需的工作簿,我会使用WorkbookFactory.

最后,您可以通过简单地输入以下内容来简化文件保存:

wb.write(new FileOutputStream("C:/juni1.xls");

请注意,您还将保存的文件写入不同的位置。因此,您的原始工作簿未受影响,而更正的工作簿位于不同的位置。

于 2013-06-22T17:59:06.600 回答