Microsoft Open XML SDL 2.0 append document to template document asp.net c#

北战南征 提交于 2019-12-18 07:05:34

问题


My asp.net c# web-application is creating word documents by filling an existing template word document with data. Now I need to add a further existing documents to that document as next page.

For example: My template has two pages. The document I need to append has one page. As result I want to get one word document with 3 pages.

How do I append documents to an existing word document in asp.net/c# with the Microsoft Open XML SDK 2.0?


回答1:


Use this code to merge two documents

using System.Linq;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace altChunk
{
    class Program
    {
        static void Main(string[] args)
        {          
            string fileName1 = @"c:\Users\Public\Documents\Destination.docx";
            string fileName2 = @"c:\Users\Public\Documents\Source.docx";
            string testFile = @"c:\Users\Public\Documents\Test.docx";
            File.Delete(fileName1);
            File.Copy(testFile, fileName1);
            using (WordprocessingDocument myDoc =
                WordprocessingDocument.Open(fileName1, true))
            {
                string altChunkId = "AltChunkId1";
                MainDocumentPart mainPart = myDoc.MainDocumentPart;
                AlternativeFormatImportPart chunk = 
                    mainPart.AddAlternativeFormatImportPart(
                    AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                using (FileStream fileStream = File.Open(fileName2, FileMode.Open))
                    chunk.FeedData(fileStream);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;
                mainPart.Document
                    .Body
                    .InsertAfter(altChunk, mainPart.Document.Body
                    .Elements<Paragraph>().Last());
                mainPart.Document.Save();
            }           
        }
    }
}

This works flawlessly and the same code is also available here.

There is another approach that uses Open XML PowerTools



来源:https://stackoverflow.com/questions/21017317/microsoft-open-xml-sdl-2-0-append-document-to-template-document-asp-net-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!