[英]Apache POI shift row to last vs shift rows up
I am using Apache POI to process excel files.我正在使用 Apache POI 来处理 excel 文件。 I want to delete the specified line, and then found that the first method not wort, I mean the deleted row should be moved to the end of this sheet, but it still has not moved.我想删除指定的行,然后发现第一个方法没有,我的意思是删除的行应该移动到这张表的末尾,但它仍然没有移动。
Method1:方法1:
sheet.shiftRows(rowNum, rowNum, sheet.getLastRowNum() - rowNum, true, false);
Method2:方法2:
sheet.shiftRows(rowNum + 1, sheet.getLastRowNum(), -1, true, false);
Anyone can help me?任何人都可以帮助我吗?
UPDATE更新
After test, I found other prombel Apache POI delete row and append row经过测试,我发现其他prombel Apache POI删除行和append行
Using what apache poi
version is method 1 even working?使用什么apache poi
版本是方法 1 甚至工作? The logic is not the one for deleting a row.逻辑不是删除行的逻辑。 It only shifts the row rowNum
to the position of the last row.它仅将行rowNum
移动到最后一行的 position。 So last row gets overwritten and row rowNum
gets empty.所以最后一行被覆盖,行rowNum
空。 This is not what I would call deleting a row.这不是我所说的删除一行。 Furthermore this always leads to corrupt Excel
files when XSSF
( *.xlsx
) is used.此外,当使用XSSF
( *.xlsx
) 时,这总是会导致Excel
文件损坏。 So clearly method 2.很明显方法2。
But this one-liner will not always work.但这种单线并不总是有效。 It only works if there are filled rows after the to delete row.它仅在删除行之后有填充行时才有效。 If that is not the case, rowNum + 1
will be greater than sheet.getLastRowNum()
and it fails.如果不是这种情况, rowNum + 1
将大于sheet.getLastRowNum()
并且它会失败。 In that case we should shift the empty rowNum + 1
one up.在这种情况下,我们应该将空的rowNum + 1
上移一个。
void deleteRow(Sheet sheet, int rowNum) {
if (rowNum > sheet.getLastRowNum()) return; // rowNum is outside the filled rows
if (rowNum + 1 < sheet.getLastRowNum()) { // there are filled rows after the to delete row
sheet.shiftRows(rowNum + 1, sheet.getLastRowNum(), -1, true, false);
} else { // there are no filled rows after the to delete row, so shift rowNum + 1 one up
sheet.shiftRows(rowNum + 1, rowNum + 1, -1, true, false);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.