Merge multiple word documents into one Open Xml

前端 未结 4 903
余生分开走
余生分开走 2020-11-30 01:57

I have around 10 word documents which I generate using open xml and other stuff. Now I would like to create another word document and one by one I would like to join them in

4条回答
  •  星月不相逢
    2020-11-30 02:34

    The only thing missing in these answers is the for loop.

    For those who just want to copy / paste it:

    void MergeInNewFile(string resultFile, IList filenames)
    {
        using (WordprocessingDocument document = WordprocessingDocument.Create(resultFile, WordprocessingDocumentType.Document))
        {
            MainDocumentPart mainPart = document.AddMainDocumentPart();
            mainPart.Document = new Document(new Body());
    
            foreach (string filename in filenames)
            {
                AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML);
                string altChunkId = mainPart.GetIdOfPart(chunk);
    
                using (FileStream fileStream = File.Open(filename, FileMode.Open))
                {
                    chunk.FeedData(fileStream);
                }
    
                AltChunk altChunk = new AltChunk { Id = altChunkId };
                mainPart.Document.Body.AppendChild(altChunk);
            }
    
            mainPart.Document.Save();
        }
    }
    

    All credits go to Chris and yonexbat

提交回复
热议问题