package word;import orgapachepoiopenxml4jopcOPCPackage;import orgapachepoixwpfusermodel;import javaioFileInputStream;import javaioFileOutputStream;public class Word public static void mainString a
package word;
import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream; import java.io.FileOutputStream;
public class Word { public static void main(String[] args) { try { // 打开input01.docx文件 FileInputStream fis = new FileInputStream("08-00计算公式(第1版).docx"); XWPFDocument doc1 = new XWPFDocument(OPCPackage.open(fis));
// 打开input03.docx文件
FileInputStream fis2 = new FileInputStream("input03.docx");
XWPFDocument doc2 = new XWPFDocument(OPCPackage.open(fis2));
// 获取“应变计”书签位置的段落
XWPFParagraph bookmarkParagraph = doc2.getParagraphs().stream()
.filter(p -> p.getCTP().getBookmarkStartList().stream()
.anyMatch(b -> b.getName().equals("应变计")))
.findFirst().orElse(null);
if (bookmarkParagraph != null) {
// 清空“应变计”书签位置的段落内容
for (int i = bookmarkParagraph.getRuns().size() - 1; i >= 0; i--) {
bookmarkParagraph.removeRun(i);
}
// 复制input01.docx文件的内容到“应变计”书签位置的段落
for (XWPFParagraph paragraph : doc1.getParagraphs()) {
XWPFParagraph newParagraph = doc2.createParagraph();
newParagraph.getCTP().setPPr(paragraph.getCTP().getPPr());
newParagraph.getCTP().setRsidR(paragraph.getCTP().getRsidR());
newParagraph.getCTP().setRsidRDefault(paragraph.getCTP().getRsidRDefault());
for (XWPFRun run : paragraph.getRuns()) {
XWPFRun newRun = newParagraph.createRun();
newRun.getCTR().setRPr(run.getCTR().getRPr());
newRun.setText(run.getText(0));
}
}
// 复制input01.docx文件的表格到“应变计”书签位置的段落
for (XWPFTable table : doc1.getTables()) {
XWPFTable newTable = doc2.createTable();
newTable.getCTTbl().setTblPr(table.getCTTbl().getTblPr());
newTable.getCTTbl().setTblGrid(table.getCTTbl().getTblGrid());
for (XWPFTableRow row : table.getRows()) {
XWPFTableRow newRow = newTable.createRow();
newRow.getCtRow().setTrPr(row.getCtRow().getTrPr());
newRow.getCtRow().setRsid(row.getCtRow().getRsid());
for (XWPFTableCell cell : row.getTableCells()) {
XWPFTableCell newCell = newRow.createCell();
newCell.getCTTc().setTcPr(cell.getCTTc().getTcPr());
for (XWPFParagraph paragraph : cell.getParagraphs()) {
XWPFParagraph newParagraph = newCell.addParagraph();
newParagraph.getCTP().setPPr(paragraph.getCTP().getPPr());
newParagraph.getCTP().setRsidR(paragraph.getCTP().getRsidR());
newParagraph.getCTP().setRsidRDefault(paragraph.getCTP().getRsidRDefault());
for (XWPFRun run : paragraph.getRuns()) {
XWPFRun newRun = newParagraph.createRun();
newRun.getCTR().setRPr(run.getCTR().getRPr());
newRun.setText(run.getText(0));
}
}
}
}
}
}
// 保存修改后的input03.docx文件
FileOutputStream fos = new FileOutputStream("input03.docx");
doc2.write(fos);
// 关闭所有打开的文件流
fis.close();
fis2.close();
fos.close();
System.out.println("内容复制完成!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
原文地址: https://www.cveoy.top/t/topic/h7za 著作权归作者所有。请勿转载和采集!