Microsoft Open XML SDL 2.0 将文档附加到模板文档 asp.net c# [英] Microsoft Open XML SDL 2.0 append document to template document asp.net c#

查看:26
本文介绍了Microsoft Open XML SDL 2.0 将文档附加到模板文档 asp.net c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 asp.net c# web 应用程序通过用数据填充现有模板 Word 文档来创建 Word 文档.现在我需要向该文档添加更多现有文档作为下一页.

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.

例如:我的模板有两页.我需要附加的文档只有一页.结果我想得到一个 3 页的 word 文档.

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.

如何使用 Microsoft Open XML SDK 2.0 将文档附加到 asp.net/c# 中的现有 Word 文档?

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

推荐答案

使用此代码合并两个文档

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

这完美无缺,同样的代码也可以在这里.

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

还有另一种方法使用 打开XML PowerTools

这篇关于Microsoft Open XML SDL 2.0 将文档附加到模板文档 asp.net c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆