- I found that there was an existing bug with shiftRows function which caused excel to break. https://bz.apache.org/bugzilla/show_bug.cgi?id=57423 I am not exactly sure if this was fixed. I have added a comment on bugzilla to know further on this.
I am trying to delete rows (not removing content of) from an excel file if a particular cell value condition is met.
I achieved this successfully, but the problem is that it breaks my excel and when i reopen the file (manually), excel shows me an error that it broke and when i open the repaired value, the file has lost all its formatting. Below is the code that i have used. I think the culprit here is shiftRows. This is because if i use other option of hiding the cells, the excel does not break and it also works fine. But the thing is I want to delete the rows and not hide it.
My first question is: What could be my options here to change the way excel is behaving here? Second question is , I want to understand the functioning of shiftRows method. The syntax for it is
void shiftRows(int startRow, int endRow, int n);
POI documentation says,
Shifts rows between startRow and endRow n number of rows. * If you use a negative number, it will shift rows up. * Code ensures that rows don't wrap around.
So, lets say i am at Row1 and will remove its contents, then what parameters should I pass to shift whole of the sheet below the Row1, 1 row above. I tried with below and it failed in the sense that t=it gave me null pointer exception on the second for loop iteration.
shiftRows(Row1+1, last row number value, difference between the last row and current row);
Code for filtering and shifting rows:
for(int r=sh.getFirstRowNum(); r<=sh.getLastRowNum(); r++){ //iterating through all the rows of excel
Row currentRow = sh.getRow(r); //get r'th row
if(currentRow.getCell(1).getStringCellValue().equalsIgnoreCase("Assigned to Duration")){
int tempRowNum = (currentRow.getRowNum()+1);
System.out.println("Working on Row: " + (currentRow.getRowNum()+1) + " value " + currentRow.getCell(0).getStringCellValue());
int tempValue = sh.getLastRowNum() - currentRow.getRowNum();
System.out.println("Difference: " +tempValue);
sh.removeRow(currentRow);
// currentRow.setZeroHeight(true);
sh.shiftRows(tempRowNum, sh.getLastRowNum(), tempValue);
r--;
// System.out.print(" row number below the current row is " + (tempRowNum+1) + " and value is " + sh.getRow(tempRowNum).getCell(0).getStringCellValue());
}
countfilter++;
}
System.out.println("Total Rows after removing: " + sh.getLastRowNum());
System.out.println("Loop iterated for " + countfilter + " times.");
fos = new FileOutputStream(file);
wb.write(fos);
wb.close();
fis.close();
System.out.println("Row filtering completed");
Excel opening error encountered after running the above code: