我的asp.net c#web-application通过用数据填充现有模板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();
}
}
}
}
这完美无瑕,同样的代码也可用here.
还有另一种使用Open XML PowerTools的方法