简体   繁体   English

OpenXML 将两个 Docx 模板中的所有内容复制到一个 Docx 文件 C#

[英]OpenXML Copy Everything from two Docx templates into a single Docx File C#

We have two Docx files, one having the header templates(Letter Head) with Header and Footer parts and the title and the second file have the body.我们有两个 Docx 文件,一个具有带有页眉和页脚部分的标题模板(信头)和标题,第二个文件具有正文。 We need to combine both the Docx files into a single Docx File.我们需要将两个 Docx 文件合并为一个 Docx 文件。 Is it possible to copy all the sections and body parts of docx files into a new document.是否可以将 docx 文件的所有部分和正文部分复制到新文档中。

We have tried the following code but we are getting exception on the second document App Parts Method:我们尝试了以下代码,但在第二个文档 App Parts Method 上出现异常:

Only one instance of the type is allowed for this parent.此父级只允许该类型的一个实例。

using (WordprocessingDocument firstDocument = WordprocessingDocument.Open(fileName, false))
using (WordprocessingDocument document = WordprocessingDocument.Open(source1, false))
using (WordprocessingDocument secondDocument = WordprocessingDocument.Create(destination, WordprocessingDocumentType.Document))
{
    MainDocumentPart mainPart = secondDocument.MainDocumentPart;
    foreach (var part in firstDocument.Parts)
    {
        secondDocument.AddPart(part.OpenXmlPart, part.RelationshipId);
    }
    foreach (var part in document.Parts)
    {
        secondDocument.AddPart(part.OpenXmlPart, part.RelationshipId);
    }
}

Have you tried adding a separate Header parts for the 3rd Main document, try adding AddNew Header part inside the loop like below您是否尝试为第三个主文档添加单独的标题部分,尝试在循环中添加 AddNew 标题部分,如下所示

MainDocumentPart mainDocumentPart1 = secondDocument.MainDocumentPart;
                if (mainDocumentPart1 != null)
                {
                    mainDocumentPart1.DeleteParts(mainDocumentPart1.HeaderParts);
                    HeaderPart headPart1 = mainDocumentPart1.AddNewPart<HeaderPart>();
                    IEnumerable<SectionProperties> sectPrs = mainDocumentPart1.Document.Body.Elements<SectionProperties>();
                    foreach (var sectPr in sectPrs)
                    {
                        sectPr.RemoveAllChildren<HeaderReference>();
                        sectPr.PrependChild<HeaderReference>(new HeaderReference() { Id = rId });
                    }
                }

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

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