wen*_*eno 2 java docx apache-poi xwpf
我正在使用 Apache POI 处理 .docx 文件。
我有 .docx ,其中有1 行、1 列表。
XWPFTable table = document.getTables().get(0);
XWPFTableRow copiedRow = table.getRow(0);
table.addRow(copiedRow);
Run Code Online (Sandbox Code Playgroud)
上面的代码成功复制了行,因此表现在有2 rows。
但是,我也想改变复制的行。
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);
Run Code Online (Sandbox Code Playgroud)
问题是......修改影响了两行。原来的第一个和刚刚添加的第二个都会受到影响。
我还尝试显式构造新行,如下所示:
copiedRow.getTableCells().get(0).setText("SOME MODIFICATION");
XWPFTableRow newRow = new XWPFTableRow(copiedRow.getCtRow(), table);
table.addRow(newRow);
Run Code Online (Sandbox Code Playgroud)
...但结果仍然相同:两行都被修改,而不仅仅是第二行。
我试图使示例尽可能简单。谢谢你的帮助!
您仍然引用相同的基础数据。
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1441 次 |
| 最近记录: |