Thursday, 23 April 2015

Merge multiple word documents into one Open Xml

Using openXML SDK only, you can use AltChunk element to merge the multiple document into one.

using (WordprocessingDocument document = WordprocessingDocument.Open(@"C:\Temp\c.docx", true))
            {
                string altChunkId = "AltChunkID" + DateTime.Now.Ticks.ToString().Substring(0, 2);
                var mainPart = document.MainDocumentPart;
                var chunk = mainPart.AddAlternativeFormatImportPart(DocumentFormat.OpenXml.Packaging.AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                using (FileStream fileStream = File.Open(@"C:\Temp\c1.docx", FileMode.Open))
                {
                    chunk.FeedData(fileStream);
                }
                var altChunk = new DocumentFormat.OpenXml.Wordprocessing.AltChunk();
                altChunk.Id = altChunkId;
                mainPart.Document.Body.InsertAfter(altChunk,mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last());
                mainPart.Document.Save();

            }

No comments:

Post a Comment