将多个 Word 文档合并为一个 Open Xml

2024-04-21

我有大约 10 个 word 文档,它们是使用 open xml 和其他东西生成的。 现在我想创建另一个word文档,我想将它们逐一加入到这个新创建的文档中。 我希望使用 open xml,任何提示都会很有意义。 下面是我的代码:

 private void CreateSampleWordDocument()
    {
        //string sourceFile = Path.Combine("D:\\GeneralLetter.dot");
        //string destinationFile = Path.Combine("D:\\New.doc");
        string sourceFile = Path.Combine("D:\\GeneralWelcomeLetter.docx");
        string destinationFile = Path.Combine("D:\\New.docx");
        try
        {
            // Create a copy of the template file and open the copy
            //File.Copy(sourceFile, destinationFile, true);
            using (WordprocessingDocument document = WordprocessingDocument.Open(destinationFile, true))
            {
                // Change the document type to Document
                document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
                //Get the Main Part of the document
                MainDocumentPart mainPart = document.MainDocumentPart;
                mainPart.Document.Save();
            }
        }
        catch
        {
        }
    }

更新(使用 AltChunks):

using (WordprocessingDocument myDoc = WordprocessingDocument.Open("D:\\Test.docx", true))
        {
            string altChunkId = "AltChunkId" + DateTime.Now.Ticks.ToString().Substring(0, 2) ;
            MainDocumentPart mainPart = myDoc.MainDocumentPart;
            AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
                AlternativeFormatImportPartType.WordprocessingML, altChunkId);
            using (FileStream fileStream = File.Open("D:\\Test1.docx", 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();
        } 

当我使用多个文件时,为什么此代码会覆盖最后一个文件的内容?更新2:

 using (WordprocessingDocument myDoc = WordprocessingDocument.Open("D:\\Test.docx", true))
        {

            MainDocumentPart mainPart = myDoc.MainDocumentPart;
            string altChunkId = "AltChunkId" + DateTime.Now.Ticks.ToString().Substring(0, 3);
            AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
            using (FileStream fileStream = File.Open("d:\\Test1.docx", 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();
            }
            using (FileStream fileStream = File.Open("d:\\Test2.docx", FileMode.Open))
            {
                chunk.FeedData(fileStream);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;
                mainPart.Document
                    .Body
                    .InsertAfter(altChunk, mainPart.Document.Body
                    .Elements<Paragraph>().Last());
            }
            using (FileStream fileStream = File.Open("d:\\Test3.docx", FileMode.Open))
            {
                chunk.FeedData(fileStream);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;
                mainPart.Document
                    .Body
                    .InsertAfter(altChunk, mainPart.Document.Body
                    .Elements<Paragraph>().Last());
            } 
        }

此代码将 Test2 数据附加两次,以代替 Test1 数据。 意味着我得到:

Test
Test2
Test2

代替 :

Test
Test1
Test2

仅使用 openXML SDK,您可以使用AltChunk http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.altchunk.aspx元素将多个文档合并为一个。

这个链接组装多个单词文档的简单方法 http://blogs.msdn.com/b/brian_jones/archive/2008/12/08/the-easy-way-to-assemble-multiple-word-documents.aspx和这个如何使用 altChunk 进行文档组装 http://blogs.msdn.com/b/ericwhite/archive/2008/10/27/how-to-use-altchunk-for-document-assembly.aspx提供一些样品。

EDIT 1

根据您使用的代码altchunk在更新的问题中(更新#1),这是我测试过的 VB.Net 代码,它对我来说就像一个魅力:

Using myDoc = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open("D:\\Test.docx", True)
        Dim altChunkId = "AltChunkId" + DateTime.Now.Ticks.ToString().Substring(0, 2)
        Dim mainPart = myDoc.MainDocumentPart
        Dim chunk = mainPart.AddAlternativeFormatImportPart(
            DocumentFormat.OpenXml.Packaging.AlternativeFormatImportPartType.WordprocessingML, altChunkId)
        Using fileStream As IO.FileStream = IO.File.Open("D:\\Test1.docx", IO.FileMode.Open)
            chunk.FeedData(fileStream)
        End Using
        Dim altChunk = New DocumentFormat.OpenXml.Wordprocessing.AltChunk()
        altChunk.Id = altChunkId
        mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Paragraph).Last())
        mainPart.Document.Save()
End Using

EDIT 2

第二期(更新#2)

此代码将 Test2 数据附加两次,代替 Test1 数据,如下所示 出色地。

altchunkid.

对于要合并到主文档中的每个文档,您需要:

  1. add an AlternativeFormatImportPart in the mainDocumentPartId 这必须是唯一的。该元素包含插入的数据
  2. 在正文中添加Altchunk您在其中设置的元素id来参考之前的AlternativeFormatImportPart.

在您的代码中,您对所有AltChunks。这就是为什么您会多次看到相同的文本。

我不确定 altchunkid 对于您的代码是否是唯一的:string altChunkId = "AltChunkId" + DateTime.Now.Ticks.ToString().Substring(0, 2);

如果您不需要设置特定值,我建议您不要显式设置AltChunkId当你添加AlternativeFormatImportPart。相反,您会得到由 SDK 生成的一个,如下所示:

VB.Net

Dim chunk As AlternativeFormatImportPart = mainPart.AddAlternativeFormatImportPart(DocumentFormat.OpenXml.Packaging.AlternativeFormatImportPartType.WordprocessingML)
Dim altchunkid As String = mainPart.GetIdOfPart(chunk)

C#

AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(DocumentFormat.OpenXml.Packaging.AlternativeFormatImportPartType.WordprocessingML);
string altchunkid = mainPart.GetIdOfPart(chunk);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将多个 Word 文档合并为一个 Open Xml 的相关文章

随机推荐

  • 如何制作这个构造函数的深层复制?

    我制作了这个构造函数 我需要对其进行深层复制 我不太明白深拷贝的含义 我知道它会创建一个拥有自己的动态内存的对象的独立副本 但我不明白这样做的需要是什么 我也不确定如何实际实现深层复制 有什么建议么 这是我需要进行深层复制的构造函数 任何人
  • 配置 Mule JPA 模块以使用 Eclipse Link 和 MySQL

    我正在尝试编写一个 Mule ESB 应用程序 它将 XML 文件读入域对象 然后使用 JPA 将该对象写入 MySQL 数据库 我已经弄清楚了大部分所需的配置 但我遇到了一个问题 其中 Mule JPA 模块 https github c
  • 如何在任何情况下保持文本垂直对齐?

    例如 在下图中 我希望在所有条件下保持文本始终垂直对齐 即使文本是一行 两行或三行 意味着文本应始终垂直居中 我不想添加额外的span div img src Hello Stackoverflow Thank you for help m
  • Google Sheets:使用另一个单元格的内容更改单元格的背景颜色

    我有一个如上所述的谷歌表 我在其中以十六进制格式输入颜色代码 然后命名它们 我想使用代码列中的十六进制代码自动更新颜色块列的背景颜色 我尝试过脚本 但 setBackground 函数不起作用 function myFunction var
  • Chrome 扩展程序编程脚本注入错误

    跟进一个上一篇文章 https stackoverflow com questions 58951909 programmatic method to let the user modify the manifest json conten
  • 如何选择不是第一个 tr 也不是最后一个 td

    MyTable tr tr hover background dfdfdf table tr td A td td B td td C td tr tr td 1 td td 2 td td X td tr tr td 3 td td 4
  • 重塑图像数组时感到困惑

    目前我正在尝试运行 ConvNet 随后将输入神经网络的每张图像都存储为列表 但目前该列表是使用三个 for 循环创建的 看一看 im Image open os path join p input directory item pix i
  • mingw32-make 尝试创建子文件夹 .lib 为非法名称

    我正在尝试编译一个需要 freetype 库的项目 所以我正在弄清楚如何将 freetype 安装到 mingw32 更安全的方法是编译它 无论如何 问题是编译 freetype 2 4 11 我进入了msys中提供的bash 我做到了 c
  • 我们如何在基于Dot Net的Azure移动服务中加载相关对象(预加载)?

    如果我有以下模型结构 public class QuestionItem EntityData public string Content get set public bool IsAnswered get set public int
  • 你能有一个指向工会成员的“成员指针”吗?

    我能找到的所有描述都讨论了类上下文中的 指向成员的指针 工会与结构非常相似 特别是也有成员 您也能指点一下这些成员吗 E g union x int a float b int x p x a 我不是在谈论指向整个联合体的指针 作为联合体成
  • 通过 WebSocket 发送 ArrayBuffer 的子段而不进行复制

    我正在填充一个ArrayBuffer与要通过发送的数据WebSocket 数据具有可变大小 因此在序列化时我动态扩展ArrayBuffer如所须 然而 当序列化过程完成时 我经常在缓冲区末尾有未使用的空间 我不想发送这些空间 可以将所需部分
  • 为什么要费心设置命令对象参数的大小参数?

    我们的数据访问层使用命令对象与sql server 进行通信 在大多数情况下 我已将字段大小 与 sql server 中的列大小匹配 硬编码到命令参数生成器中 Such as SqlParameter param new SqlParam
  • 扩展 Symfony2 控制器解析器

    我目前正在创建一个包 如果请求是 Ajax 请求 它可以将 fooAction 重命名为 fooAjaxAction 作为答案那个问题 https stackoverflow com questions 24672349 edit symf
  • 如何删除 Next.js 中 id="__next" 的 div

    我正在使用 Next js 制作一个网站 我想要一个标题position sticky 行为 然而 Next js 自动生成一个带有属性的 divid next 未经我的许可在我的网站的根目录中 我需要删除该 div 以便position
  • 如何让 Celery 工作人员返回任务结果

    我有一个调用任务的烧瓶应用程序 该任务从数据库中提取数据 绘制折线图并返回在 html 页面上呈现的 html 内容 如果没有 Celery Flask 应用程序可以正常工作并在客户端呈现折线图 但现在我想委托 celery 通过以下方式运
  • CDN 不工作时如何加载本地文件

    我正在使用一些 CDN js 和 css 文件 我在Google上搜索了如果CDN不工作如何加载本地数据 我发现一个很好的链接是这样写的
  • 仅加载 html5 视频/音频的元数据

    首先 我想问这个问题 如果没有任何其他视频内容 我无法加载元数据 preload metadata 不管用 我在 Win Chrome 上测试 不知道它在 Safari FF IE Opera 上如何工作 因此我无法快速加载六个或更多视频剪
  • 事件处理程序返回未定义?

    假设我将 jQuery 单击事件的事件处理程序附加到我的对象的函数之一 但为什么它在我的属性上返回未定义 var buttonView label underscore onClick function alert clicked this
  • 将 SharePoint 用户写入 SharePoint 列表中的用户字段的正确方法

    我正在将用户写入 SharePoint 列表 我读到 SharePoint 用户字段内部有一个类似这样的字符串 userId userLoginName 在写入用户字段时 我尝试以相同的方式进行格式化 例如 当我写入此字符串时 它会起作用
  • 将多个 Word 文档合并为一个 Open Xml

    我有大约 10 个 word 文档 它们是使用 open xml 和其他东西生成的 现在我想创建另一个word文档 我想将它们逐一加入到这个新创建的文档中 我希望使用 open xml 任何提示都会很有意义 下面是我的代码 private