以下代码获取文档中第一个表中第二行的确切副本。然后它更改此行中单元格的文本内容。然后在此表的第2行和第3行之间插入此复制的行。
的改变必须table.addRow之前完成,因为该行必须在List tableRows插入它并将它添加到CTTbl ctTbl的TrArray之前完成的内容。后来的更改不会写入XML。我没有真正明白为什么会出现这种情况。
然后代码获取最后一行的副本,并将该副本添加到表的末尾。这里也要更改内容,必须在table.addRow之前完成。
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;
public class WordInsertTableRow {
public static void main(String[] args) throws Exception {
XWPFDocument doc = new XWPFDocument(new FileInputStream("source.docx"));
XWPFTable table = doc.getTableArray(0);
//insert new row, which is a copy of row 2, as new row 3:
XWPFTableRow oldRow = table.getRow(1);
CTRow ctrow = CTRow.Factory.parse(oldRow.getCtRow().newInputStream());
XWPFTableRow newRow = new XWPFTableRow(ctrow, table);
int i = 1;
for (XWPFTableCell cell : newRow.getTableCells()) {
for (XWPFParagraph paragraph : cell.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
run.setText("New row 3 cell " + i++, 0);
}
}
}
table.addRow(newRow, 2);
//insert new last row, which is a copy previous last row:
XWPFTableRow lastRow = table.getRows().get(table.getNumberOfRows() - 1);
ctrow = CTRow.Factory.parse(lastRow.getCtRow().newInputStream());
newRow = new XWPFTableRow(ctrow, table);
i = 1;
for (XWPFTableCell cell : newRow.getTableCells()) {
for (XWPFParagraph paragraph : cell.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
run.setText("New last row cell " + i++, 0);
}
}
}
table.addRow(newRow);
doc.write(new FileOutputStream("result.docx"));
doc.close();
}
}