OpenXML SDK C#:如何将书签内容从 1 个单词文件复制到另一个单词文件

问题描述

我需要在 C# 中使用 OpenXMl SDK 创建 word 文件我有 2-word files 我需要将一些书签内容1st-word file 复制到 2nd-word file 并保存文件

提前致谢。

解决方法

我尝试了不同的方法,下面是我的代码。 我收到错误消息“无法插入 OpenXmlElement“newChild”,因为它是树的一部分。”

public void testingExecute()
    {

        try
        {
            using (WordprocessingDocument wordDoc1 = WordprocessingDocument.Open(fromDocument1,false))
            using (WordprocessingDocument wordDoc2 = WordprocessingDocument.Open(toDocument2,true))
            {

                BookmarkStart bookmarkStart = new BookmarkStart();
               
                var res = from bm in wordDoc1.MainDocumentPart.RootElement.Descendants<BookmarkStart>()
                          where bm.Name == "TestBookmark"
                          select bm;
                
                var bookmarkstart = res.SingleOrDefault();
                var res1 = from bm in wordDoc1.MainDocumentPart.RootElement.Descendants<BookmarkEnd>()
                           where bm.Id == bookmarkstart.Id
                           select bm;
                var bookmarkend = res1.SingleOrDefault();

                body.InsertBeforeSelf<BookmarkStart>(bookmarkstart);
                body.InsertAfterSelf<BookmarkEnd>(bookmarkend);

                
                wordDoc2.MainDocumentPart.Document.Save();

        }
        catch (Exception Ex)
        {

            throw;
        }
    }