Search code examples
javaapacheexcelapache-poipoi-hssf

HSSFSheet remove all empty rows


I have an excel sheet with, for exemple 3,4 adn 6th line that are empty (previously I called sheet.removeRow() for those rows). In total i have 7 lines

Now, having indexes of those empty rows, i want to remove them (shift them).

When I call the function shiftRows(rowIndex+1, lastRowNum, -1) im getting

 java.lang.IllegalArgumentException: Minumum row number is 0

this is my implementation

 List<Integer> rowsToRemove = [2,3,5];
 for (Integer rowIndex : rowsToRemove) {
     removeRow(sheet, rowIndex);
 }
 int lastRowNum = sheet.getLastRowNum();
 for (Integer rowIndex : rowsToRemove) {
     shiftRow(sheet, rowIndex, lastRowNum);
 }


/**
* Remove a row by its index
* @param sheet a Excel sheet
* @param rowIndex a 0 based index of removing row
*/
public static void removeRow(HSSFSheet sheet, int rowIndex) {

   HSSFRow removingRow = sheet.getRow(rowIndex);
   if(removingRow!=null) {
       sheet.removeRow(removingRow);
   }
}

public static void shiftRow(HSSFSheet sheet, int rowIndex, int lastRowNum) {
   if (rowIndex >= 0 && rowIndex < lastRowNum) {
       sheet.shiftRows(rowIndex+1, lastRowNum, -1);
   }
}

Can u please help me remove those empty rows?? I need a solution that will remove al empty lines from a excel file.

Thanks


Solution

  • This scenario will work only if cells in the columns are not merged. If they are merged, the exception in the poi will occur.