Apache POI 删除行并追加行 [英] Apache POI delete row and append row
问题描述
我正在使用 apache-poi(3.16 and 4.0.0)
生成一个 excel 文件.我需要删除指定的行(删除行并移动到最后一行)并在最后一行之后附加数据.当我移动线路时,我发现它没有按预期工作.
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.
这些是我的代码(rowNum < lastRowNum):
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);
我的问题
shiftRows1
+appendRow
+4.0.0/3.16
+XSSF
: 清除rowNum并删除lastRowNum
shiftRows1
+appendRow
+4.0.0/3.16
+XSSF
: clear rowNum and delete lastRowNum
shiftRows1
+ appendRow
+ 4.0.0/3.16
+ HSSF
: 清除 rowNum 并清除lastRowNum
shiftRows1
+ appendRow
+ 4.0.0/3.16
+ HSSF
: clear rowNum and clear lastRowNum
shiftRows2
+ appendRow
+ 4.0.0
+ XSSF
: 损坏的文件;修复后,删除lastRowNum并清除行>= rowNum
shiftRows2
+ appendRow
+ 4.0.0
+ XSSF
: damaged file; after repair, delete lastRowNum and clear rows >= rowNum
shiftRows2
+ appendRow
+ 4.0.0/3.16
+ HSSF
: 删除rowNum即可不追加行(lastRowNum 总是等于删除前的 lastRowNum)
shiftRows2
+ 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
shiftRows2
+ appendRow
+ 3.16
+ XSSF
: working
经测试,shiftRows1
无法使用.为什么 HSSF
在 appendRow
之后不更新 lastRowNum?我怎样才能使用 shiftRows2
和 3.16
实现它?
After test, the shiftRows1
cannot be used. Why HSSF
not update lastRowNum after appendRow
? how can i achive it use shiftRows2
and 3.16
?
推荐答案
我是这样处理这个问题的(apache-poi 3.16
):
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);
}
}
这篇关于Apache POI 删除行并追加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!