0

can someone tell me how to iterate and delete all the empty rows in excel file using apache poi? I am calling those 2 functions with row indexes that i wish to delete, but the second one (shift) is always giving me Minumum row index is 0 exceltion.

 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 = sheet.getLastRowNum();
   if (rowIndex >= 0 && rowIndex < lastRowNum) {
       sheet.shiftRows(rowIndex+1, rowIndex+1, -1);
   }
 }

Thanks

gospodin
  • 1,133
  • 4
  • 22
  • 42

2 Answers2

0

The problem was in columns that were merged in the excel file.

gospodin
  • 1,133
  • 4
  • 22
  • 42
0
sheet.removeRow(row)

will delete the row, but it will create a white space(hole), or an empty row in your data, hence will make it inconsistent. What you can do is after deleting you can shift your rows, which means moving all the remaining rows one step up using this:

int rowToDeleteIndex = // The row number you want to delete
int lastRowIndex = worksheet.getLastRowNum();
worksheet.shiftRows(rowToDeleteIndex + 1, lastIndex, -1);
Muhammad Ahsan
  • 249
  • 4
  • 13