Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

OpenXML SDK C#: How to Copy Bookmark content from 1 word file to another word file

I need to create the word file using OpenXMl SDK in C#, I have 2-word files I need to copy a few bookmarks contents from the 1st-word file to the 2nd-word file and save the file.

Thanks in advance.

question from:https://stackoverflow.com/questions/65651201/openxml-sdk-c-how-to-copy-bookmark-content-from-1-word-file-to-another-word-fi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I tried in different ways, Below is my code. i am getting error as "Cannot insert the OpenXmlElement "newChild" because it is part of a tree."

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;
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...