簡體   English   中英

Microsoft Open XML SDL 2.0將文檔附加到模板文檔asp.net c#

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

我的asp.net c#web應用程序通過用數據填充現有模板word文檔來創建word文檔。 現在,我需要將下一頁中的其他現有文檔添加到該文檔中。

例如:我的模板有兩頁。 我需要附加的文件有一頁。 結果我想得到一個3頁的單詞文檔。

如何使用Microsoft Open XML SDK 2.0將文檔附加到asp.net/c#中的現有word文檔?

使用此代碼合並兩個文檔

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

這完美無瑕,同樣的代碼也可以在這里找到

還有另一種使用Open XML PowerTools的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM