问题
I am using apache-poi(3.16 and 4.0.0) to generate an excel file. I need to delete the specified line (remove row and move to the last row) and append the data after the last line. When I moved the line, I found that it did not work as expected.
These are my codes (rowNum < lastRowNum):
shiftRows1
sheet.shiftRows(rowNum, rowNum, sheet.getLastRowNum() - rowNum, true, false);
shiftRows2
sheet.shiftRows(rowNum + 1, sheet.getLastRowNum(), -1, true, false);
appendRow
setRowValue(sheet.getLastRowNum() + 1, objectArray);
My Question
shiftRows1+appendRow+4.0.0/3.16+XSSF: clear rowNum and delete lastRowNumshiftRows1+appendRow+4.0.0/3.16+HSSF: clear rowNum and clear lastRowNumshiftRows2+appendRow+4.0.0+XSSF: damaged file; after repair, delete lastRowNum and clear rows >= rowNumshiftRows2+appendRow+4.0.0/3.16+HSSF: delete rowNum and can not append row(lastRowNum always equal to the lastRowNum before delete)shiftRows2+appendRow+3.16+XSSF: working
After test, the shiftRows1 cannot be used. Why HSSF not update lastRowNum after appendRow? how can i achive it use shiftRows2 and 3.16?
回答1:
I dealt with this problem in the following way(apache-poi 3.16):
private void removeRow(int rowNum) {
    Row row = sheet.getRow(rowNum);
    if (row == null) return;
    sheet.removeRow(row);
    int lastRowNum = sheet.getLastRowNum();
    if (rowNum < lastRowNum) {
        // bad way: shift the removed row down
        sheet.shiftRows(rowNum + 1, lastRowNum, -1, true, false);
        // remove lastRow: avoid Sheet#getLastRowNum() return same value after Sheet#shiftRows
        if (workbook instanceof HSSFWorkbook) removeRow(lastRowNum);
    }
}
    来源:https://stackoverflow.com/questions/62280390/apache-poi-delete-row-and-append-row