简体   繁体   English

将模板插入模板-C#Open XML SDK 2.0 / 2.5

[英]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. 我正在处理一些代码来操作预先存在的.DOTX模板文件中的书签。 For this issue, some of the bookmarks are intended to point to another .DOTX file and insert it into the current document. 对于此问题,某些书签旨在指向另一个.DOTX文件,并将其插入当前文档中。

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. 这实际上是在破坏我的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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