Removing a row from an Excel sheet with Apache POI HSSF
/** * 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) { int lastRowNum=sheet.getLastRowNum(); if(rowIndex>=0&&rowIndex<lastRowNum){ sheet.shiftRows(rowIndex+1,lastRowNum, -1); } if(rowIndex==lastRowNum){ HSSFRow removingRow=sheet.getRow(rowIndex); if(removingRow!=null){ sheet.removeRow(removingRow); } }}
I know, this is a 3 year old question, but I had to solve the same problem recently, and I had to do it in C#. And here is the function I'm using with NPOI, .Net 4.0
public static void DeleteRow(this ISheet sheet, IRow row) { sheet.RemoveRow(row); // this only deletes all the cell values int rowIndex = row.RowNum; int lastRowNum = sheet.LastRowNum; if (rowIndex >= 0 && rowIndex < lastRowNum) { sheet.ShiftRows(rowIndex + 1, lastRowNum, -1); } }
Something along the lines of
int newrownum=0;for (int i=0; i<=sheet.getLastRowNum(); i++) { HSSFRow row=sheet.getRow(i); if (row) row.setRowNum(newrownum++);}
should do the trick.