简体   繁体   English

在Excel工作表中使用JAVA永久删除空行Apache POI

[英]Permanently Delete Empty Rows Apache POI using JAVA in Excel Sheet

I'd like to permanently delete those rows that are empty have no data of any type! 我想永久删除那些没有任何类型数据的空行! I am doing this like: 我这样做:

 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);
    int rowIndex = 0;
    int lastRowNum = sheet.getLastRowNum();

   if (rowIndex >= 0 && rowIndex < lastRowNum) {
   sheet.shiftRows(rowIndex, lastRowNum, 500);
   }

        FileOutputStream fileOut = new FileOutputStream("C:/juni.xls");
         wb.write(fileOut);
         fileOut.close();
    }
    catch(Exception e){
        System.out.print("SERRO "+e);
    }

}

after shiftRows() i write my new file. 在shiftRows()之后我写了我的新文件。 But my code has now effect. 但我的代码现在已经生效了。 I just need to remove/delete the empty rows that come inside my data (any ever). 我只需要删除/删除我的数据中的空行(任何一个)。 so is it possible doing so? 这样做有可能吗? if yes, am i doing right? 如果是的话,我做得对吗? if no can anybody please help me doing so? 如果没有人可以帮助我这样做吗? Thanks in advance! 提前致谢!

If memory recalls shiftRows(int startRow, int endRow, int n) is what you need. 如果内存调用shiftRows(int startRow, int endRow, int n)就是你需要的。 I don't quite remember how to check if a row is empty but if you DO know that a row is empty (normally through use of removeRow(Row row) ) and you know the rowIndex, then it isn't so bad. 我不太记得如何检查一行是否为空但如果你知道一行是空的(通常是通过使用removeRow(Row row) )并且你知道rowIndex,那么它就不那么糟了。 By calling: 致电:

int rowIndex; //Assume already known and this is the row you want to get rid of
int lastIndex = sheet.getLastRowNum();
sheet.shiftRows(rowIndex + 1, lastIndex, -1);

you shift every row in [rowIndex + 1, lastIndex] inclusive up by 1 (which should delete an empty row effectively). 你将[rowIndex + 1,lastIndex]中的每一行向上移动1(这应该有效地删除一个空行)。 If you have multiple rows and had a way to determine if the row was empty then I suggest something like: 如果你有多行并且有办法确定行是否为空,那么我建议如下:

for(int i = 0; i < sheet.getLastRowNum(); i++){
    if(isEmpty(sheet.getRow(i)){
        sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
        i--;//Adjusts the sweep in accordance to a row removal
    }
}

boolean isEmpty(Row row){

//Code to determine if a row is empty

}

As a small note if n is negative, the rows shift up. 作为一个小注释,如果n为负数,则行向上移动。 If n is positive the rows shift down. 如果n为正,则行向下移动。 So I'm not quite sure if you meant to shift that chunk of rows down by 500 or not in your provided code. 所以我不太确定你是否打算在你提供的代码中将那一行的行减少500或者不是。 I hope this helps. 我希望这有帮助。

Instead of shiftRows method. 而不是shiftRows方法。 Try the removeRow method. 尝试removeRow方法。

For more information have a look here . 有关更多信息,请查看此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM