I don't know how to delete row without leaving an empty row.
I am using Apache POI 3.9 and I am getting an error using the following code:
public List<MeterInfo> addToList(String patternt) throws ParseException, IOException {
List<Object> data = new ArrayList<Object>();
int lastRowNum = sheet.getLastRowNum();
Row row;
for(int i = 0; i < lastRowNum; i++){
row = sheet.getRow(i);
if(patternt.equals(getCurrentString(row))){
data.add(getDataFromRow(row));
sheet.removeRow(row);
sheet.shiftRows(row.getRowNum() + 1, row.getRowNum() + 1, -1);
}
}
saveWorkbook(new File("blabla.xlsx"));
return data;
}
I've found a solution in https://stackoverflow.com/a/3554129/6812826, but I am getting a NullPointerException because I am decreasing lastRowNum by each deleted row.
Here is the new version:
public List<Object> addToList(String pattern) throws ParseException, IOException {
List<Object> data= new ArrayList<Object>();
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (pattern.equals(getCurrentString(row))) {
data.add(getMeterInfo(row));
deleteRow(row);
}
}
saveWorkbook(new File("blabla.xlsx"));
return data;
}
private void deleteRow(Row row) {
int lastRowNum = sheet.getLastRowNum();
int rowIndex = row.getRowNum();
if(rowIndex >= 0 && rowIndex < lastRowNum){
sheet.shiftRows(rowIndex + 1, lastRowNum, -1);
}
if(rowIndex == lastRowNum){
Row removingRow = sheet.getRow(rowIndex);
if(removingRow != null){
sheet.removeRow(removingRow);
}
}
}
removeRow( sheet. getRow(rowNum) );
Right-click in a table cell, row, or column you want to delete. On the menu, click Delete Cells. To delete one cell, choose Shift cells left or Shift cells up. To delete the row, click Delete entire row.
removeRow(r); int rowIndex = r. getRowNum(); int lastRowNum = sheet. getLastRowNum(); if (rowIndex >= 0 && rowIndex < lastRowNum) { sheet.
Try this code, it should work:
for(int i = 0; i < sheet.getLastRowNum(); i++)
{
row = sheet.getRow(i);
if(patternt.equals(getCurrentString(row)))
{
data.add(getDataFromRow(row));
// sheet.removeRow(row); NO NEED FOR THIS LINE
sheet.shiftRows(row.getRowNum() + 1, sheet.getLastRowNum() + 1, -1);
i--;
}
}
You need to decrease i
by one every time you delete one row. And get the last row number again by using getLastRowNum()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With