2014-01-09 49 views
1

我的asp.net c#web應用程序通過用數據填充現有的模板文檔來創建word文檔。現在我需要爲該文檔添加更多現有文檔作爲下一頁。Microsoft Open XML SDL 2.0將文檔附加到模板文檔asp.net c#

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

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

回答

7

使用此代碼合併兩個文件

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

這完美的作品和相同的代碼也可以here

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