使用OpenXml和C#复制Word文档 [英] Duplicating Word document using OpenXml and C#
问题描述
我正在使用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:\newdoc.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屋!