5

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. 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!

user2496503
  • 907
  • 5
  • 13
  • 21
  • Please check [How to delete blank rows in between the sheet using poi?][1] Perhaps this will be helpful. [1]: http://stackoverflow.com/a/16562982/624003 – Sankumarsingh Jun 22 '13 at 03:53

2 Answers2

11

If memory recalls shiftRows(int startRow, int endRow, int n) is what you need. 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. 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). 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. If n is positive the rows shift down. So I'm not quite sure if you meant to shift that chunk of rows down by 500 or not in your provided code. I hope this helps.

Erik Nguyen
  • 839
  • 1
  • 6
  • 21
  • 1
    No problem. Have fun coding! :D – Erik Nguyen Jun 22 '13 at 17:31
  • Note that if you have a stealth entry a long way down in your spreadsheet, after a large gap in the rows, then this approach can be really slow, as it iterates through hundreds of thousands of blank rows, repeatedly shifting the remaining rows one place. – lukens Aug 22 '17 at 16:33
3

Instead of shiftRows method. Try the removeRow method.

For more information have a look here.

JHS
  • 7,761
  • 2
  • 29
  • 53