Apache POI delete row and append row

核能气质少年 提交于 2020-06-27 04:08:21

问题


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

  1. shiftRows1 + appendRow + 4.0.0/3.16 + XSSF : clear rowNum and delete lastRowNum

  2. shiftRows1 + appendRow + 4.0.0/3.16 + HSSF : clear rowNum and clear lastRowNum

  3. shiftRows2 + appendRow + 4.0.0 + XSSF : damaged file; after repair, delete lastRowNum and clear rows >= rowNum

  4. shiftRows2 + appendRow + 4.0.0/3.16 + HSSF : delete rowNum and can not append row(lastRowNum always equal to the lastRowNum before delete)

  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!