简体   繁体   中英

Removing several blank lines in XLS using Apache POI HSSF with an incrementing loop

I need to remove several lines of an excel xls sheet. These lines always contain the same first cell thats why i check the first cell of all rows to find these rows

SSFCell myCell = myRow.getCell(0);
            myCell.setCellType(Cell.CELL_TYPE_STRING);
            String foundString = myCell.getStringCellValue();
            if(foundString.equals(searchString)){
                foundRows.add(rowCount);
            }
            rowCount++;

I then go on and "remove" those rows using removeRow which nulls all values

public static void removeRows() {

    List<Integer> foundRowsToDelete = new ArrayList<Integer>();
    //Copy values to another list
    for(int i=0; i<foundRows.size(); i++){
        foundRowsToDelete.add(foundRows.get(i));
    }
    //Delete values from rows, leaving empty rows
    while(foundRowsToDelete.size()!=0){
        int rowIndex = foundRowsToDelete.get(0);
        Row removingRow = mySheet.getRow(rowIndex);
        if (removingRow != null) {
            mySheet.removeRow(removingRow);
            foundRowsToDelete.remove(0);
    }
}
    //Move empty rows to bottom of the sheet
    for(int i = 0; i < mySheet.getLastRowNum(); i++){
        if(isRowEmpty(i)){
            mySheet.shiftRows(i+1, mySheet.getLastRowNum(), -1);
            i--;
        }
    }
}

I check if they are empty through using the duplicated rowcounter

//Comparision of previously detected empty rows and given row count
public static boolean isRowEmpty(int suspectedRowNumber) {
    for(int i=0;i<foundRows.size();i++){
        if (suspectedRowNumber == foundRows.get(i)){
            foundRows.remove(i);
            return true;
        }
    }
    return false;
}

However only the first of these rows gets deleted. The rest will stay empty. I therefore assume that there is something wrong with some incrementing done by me, but i just can't figure out exactly why.

Thanks for your help in advance.

It's not immediately clear why your code isn't working, but I look at a couple things to debug

  1. Your foundRowsToDelete ArrayList is being populated with values contained in the foundRows Array. Are you sure what you expect to find in foundRows is actually there.

  2. Is there a reason you don't remove the row when initally iterating through the rows in your sheet? Maybe something like this:

 Sheet sheet = workbook.getSheetAt(0); For (Row row : sheet) { SSFCell myCell = row.getCell(0); if(myCell.getCellType() == Cell.CELL_TYPE_STRING){ String foundString = myCell.getStringCellValue(); if(foundString.equalsIgnoreCase(searchString){ // why not just remove here? sheet.removeRow(row); } } } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM