复制和改变 .docx 中的行 table

Copying and mutating row in a .docx table

我正在使用 Apache POI 处理 .docx 文件。

我有 .docx 1 行 1 列 table.

XWPFTable table = document.getTables().get(0);
XWPFTableRow copiedRow = table.getRow(0);
table.addRow(copiedRow);

以上代码成功复制了该行,因此 table 现在将有 2 行


不过,我也想改变复制的行。

XWPFTable table = document.getTables().get(0);
XWPFTableRow copiedRow = table.getRow(0);
copiedRow.getTableCells().get(0).setText("SOME MODIFICATION HERE"); // <- setting some data
table.addRow(copiedRow);

问题是...修改影响了 行。原来的第一个和刚刚添加的第二个都受影响


我还尝试显式构造新行,如下所示:

copiedRow.getTableCells().get(0).setText("SOME MODIFICATION");
XWPFTableRow newRow = new XWPFTableRow(copiedRow.getCtRow(), table);
table.addRow(newRow); 

...但结果仍然相同:两行都被修改,而不仅仅是第二行。

我已尽量简化示例。感谢您的帮助!

您仍在引用相同的基础数据。

CTRow 确实有一个 copy 方法。所以用它来创建一个新的 XWPFTableRow:

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;

import java.io.*;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws IOException {
        Path documentRoot = Paths.get(System.getProperty("user.home"), "Documents");
        try (InputStream inputStream = Files.newInputStream(documentRoot.resolve("Input.docx"))) {
            XWPFDocument document = new XWPFDocument(inputStream);
            XWPFTable table = document.getTables().get(0);
            XWPFTableRow row = table.getRow(0);
            XWPFTableRow copiedRow = new XWPFTableRow((CTRow) row.getCtRow().copy(), table);
            copiedRow.getTableCells().get(0).setText("SOME MODIFICATION HERE");
            table.addRow(copiedRow);
            try (OutputStream outputStream = Files.newOutputStream(documentRoot.resolve("Output.docx"))) {
                document.write(outputStream);
            }
        }
    }
}