简体   繁体   中英

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. We need to combine both the Docx files into a single Docx File. Is it possible to copy all the sections and body parts of docx files into a new document.

We have tried the following code but we are getting exception on the second document 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

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

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