加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

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

发布时间:2020-12-13 20:25:30 所属栏目:Windows 来源:网络整理
导读:我的asp.net c#web-application通过用数据填充现有模板word文档来创建word文档.现在,我需要将下一页中的其他现有文档添加到该文档中. 例如:我的模板有两页.我需要附加的文件有一页.结果我想得到一个3页的单词文档. 如何使用Microsoft Open XML SDK 2.0将文
我的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:UsersPublicDocumentsDestination.docx";
            string fileName2 = @"c:UsersPublicDocumentsSource.docx";
            string testFile = @"c:UsersPublicDocumentsTest.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的方法

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读