简体   繁体   中英

Inserting a Template into a Template - C# Open XML SDK 2.0/2.5

I'm working on some code to manipulate bookmarks in a preexisting .DOTX template file. For this issue, some of the bookmarks are intended to point to another .DOTX file and insert it into the current document.

I'm having trouble finding a way to do this without some heavy manipulation and digging through each element in the 2nd template and creating a similar element in the current document.

Anyone have any ideas of a way to do this easily?

Turned out to be easier than I thought.

foreach (BookmarkStart bookmark in mainDoc.RootElement.Descendants<BookmarkStart>().Where(b => String.Equals(b.Name, bookmarkName)))
            {
                var parent = bookmark.Parent;

                using (WordprocessingDocument newTemplate = WordprocessingDocument.Open(template2, false))
                {
                    var newTemplateBody = newTemplate.MainDocumentPart.Document.Body;
                    foreach (var element in newTemplateBody.Elements().Reverse<OpenXmlElement>())
                    {
                        parent.InsertAfterSelf<OpenXmlElement>((OpenXmlElement)element.Clone());
                    }
                }
            }

I apparently was doing everything right, however I was inserting the template in a paragraph. The template is a table, which cannot be nested in a paragraph. This was what was actually breaking my document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM