使用Apache POI复制Word文档内容到指定书签位置

本篇文章将介绍如何使用Apache POI库将一个Word文档(.docx)的全部内容复制到另一个Word文档中指定的书签位置。

代码示例

以下代码使用Apache POI 5.2.2版本,将'input01.docx'文件的内容复制到'input03.docx'文件的'应变计'书签位置:javaimport java.io.FileInputStream;import java.io.FileOutputStream;import org.apache.poi.openxml4j.opc.OPCPackage;import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.apache.poi.xwpf.usermodel.XWPFParagraph;import org.apache.poi.xwpf.usermodel.XWPFRun;

public class CopyContentToBookmark { public static void main(String[] args) { try { // 打开input01.docx文件 FileInputStream fis = new FileInputStream('input01.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());                    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();        }    }}

注意:

  • 此代码假设'input01.docx'和'input03.docx'文件位于当前工作目录中。您需要根据实际情况修改文件路径。* 确保已将Apache POI库添加到您的项目中。

希望这篇文章对您有所帮助!


原文地址: https://www.cveoy.top/t/topic/fNCl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录