使用 OpenXml 和 C# 复制 Word 文档 [英] Duplicating Word document using OpenXml and C#

查看:38
本文介绍了使用 OpenXml 和 C# 复制 Word 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Word 和 OpenXml 在 C# ASP.NET Web 应用程序中提供邮件合并功能:

I am using Word and OpenXml to provide mail merge functionality in a C# ASP.NET web application:

1) 上传的文档带有多个预定义的字符串以供替换.

1) A document is uploaded with a number of pre-defined strings for substitution.

2) 我使用 OpenXML SDK 2.0 打开 Word 文档,获取 mainDocumentPart 作为字符串并使用 Regex 执行替换.

2) Using the OpenXML SDK 2.0 I open the Word document, get the mainDocumentPart as a string and perform the substitution using Regex.

3) 然后我使用 OpenXML 创建一个新文档,添加一个新的 mainDocumentPart 并将替换产生的字符串插入到这个 mainDocumentPart 中.

3) I then create a new document using OpenXML, add a new mainDocumentPart and insert the string resulting from the substitution into this mainDocumentPart.

但是,新文档中的所有格式/样式等都将丢失.

However, all formatting/styles etc. are lost in the new document.

我猜我可以单独复制和添加样式、定义、注释部分等以模仿原始文档.

I'm guessing I can copy and add the Style, Definitions, Comment parts etc.. individually to mimic the orginal document.

但是,有没有一种使用 Open XML 复制文档的方法,允许我在新副本上执行替换?

However is there a method using Open XML to duplicate a document allowing me to perform the substitutions on the new copy?

谢谢.

推荐答案

这段代码应该将现有文档中的所有部分复制到新文档中.

This piece of code should copy all parts from an existing document to a new one.

using (var mainDoc = WordprocessingDocument.Open(@"c:sourcedoc.docx", false))
using (var resultDoc = WordprocessingDocument.Create(@"c:
ewdoc.docx",
  WordprocessingDocumentType.Document))
{
  // copy parts from source document to new document
  foreach (var part in mainDoc.Parts)
    resultDoc.AddPart(part.OpenXmlPart, part.RelationshipId);
  // perform replacements in resultDoc.MainDocumentPart
  // ...
}

这篇关于使用 OpenXml 和 C# 复制 Word 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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