Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete, not clear row in Sheet ? Apache POI

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);
        }
    }
}
like image 441
Andrew Avatar asked Mar 24 '17 12:03

Andrew


People also ask

How do I delete a row in Apache POI?

removeRow( sheet. getRow(rowNum) );

How do I delete a full row?

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.

How do I delete a specific row in Excel using Java?

removeRow(r); int rowIndex = r. getRowNum(); int lastRowNum = sheet. getLastRowNum(); if (rowIndex >= 0 && rowIndex < lastRowNum) { sheet.


1 Answers

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().

like image 62
ManishChristian Avatar answered Sep 22 '22 12:09

ManishChristian