Hey everyone i have some questions. I have an algorithm structure like this, how do I prevent my loop data from being duplicated?
im using apache poi 3.8
XWPFTable TableArr1 = document.getTableArray(1);
XWPFTableRow getRow1 = TableArr1.getRow(0);
XWPFTableRow copiedRow = new XWPFTableRow((CTRow) getRow1.getCtRow().copy(), TableArr1);
int indexCounter;
for (AuditEngagementLHA l : ListDivAndDivHead) {
copiedRow.getCell(2).setText(l.getDivisionName().trim());
copiedRow.getCell(3).setText(l.getNameDisplay().trim());
TableArr1.addRow(copiedRow);
}
the result (data row is duplicate)
my expectation:
CodePudding user response:
After XWPFTableRow copiedRow = new XWPFTableRow((CTRow) getRow1.getCtRow().copy(), table);
your copiedRow
will be a new row pointing to a copy of the underlying CTRow
of the getRow1
.
Then with copiedRow.getCell(2).setText
you are changing XML content in that CTRow
. After that, the underlying CTRow
of the copiedRow
is changed. Then using .addRow(copiedRow)
you add that row to the table.
As you are doing this within a loop, you are always changing the former state of the underlying CTRow
of the copiedRow
by adding new content. This CTRow
then has empty content from copied first row when loop gets started, first content after first looping, first content and second content after second looping and so on.
Seems as if the new rows always sall be copies from the empty first row of the table. So do always copying the copiedRow
from the first row as first code line within the loop.
...
for (... : ...) {
XWPFTableRow copiedRow = new XWPFTableRow((CTRow)getRow1.getCtRow().copy(), table);
copiedRow.getCell(2).setText(...);
copiedRow.getCell(3).setText(...);
table.addRow(copiedRow);
}
...