繁体   English   中英

使用OpenXML 2.0合并文档

[英]Merging Documents with OpenXML 2.0

我试图将一些信息和一些图片从数据库插入到Word文档中。

我已经创建了一个Word文档作为模板,可以在其中查找并用实际数据和图片替换关键字。

如何打开此模板,替换关键字,然后将其放入新文档中。 然后,我需要重新打开该模板,然后再次进行操作,直到列表中的每个人都在新的Word文档中。

//The template file exists, so open it and use it to set up the main Word document
using (WordprocessingDocument templatePackage = WordprocessingDocument.Open(templateDocPath, false))
{
    //Read the template file
    string docText = null;
    using (StreamReader sr = new StreamReader(templatePackage.MainDocumentPart.GetStream()))
    {
        docText = sr.ReadToEnd();
    }

    string tempString = docText;
    Regex regexText = new Regex("<name>");
    docText = regexText.Replace(docText, tnlCampers[0].FirstName + " " + tnlCampers[0].LastName);

    regexText = new Regex("<address>");
    docText = regexText.Replace(docText, tnlCampers[0].Address1 + " " + tnlCampers[0].Address2 + " " + tnlCampers[0].City + ", " + tnlCampers[0].State + " " + tnlCampers[0].ZipCode);

    regexText = new Regex("<phone>");
    docText = regexText.Replace(docText, tnlCampers[0].CellPhone);

    regexText = new Regex("<email>");
    docText = regexText.Replace(docText, tnlCampers[0].Email);

    //Write to the newly created Word Document
    using (StreamWriter sw = new StreamWriter(package.MainDocumentPart.GetStream(FileMode.Create)))
    {
        sw.Write(docText);
    }
}

但是,当我在tnlCampers列表上执行foreach循环时,会引发错误,因为它试图复制整个文档结构而不是仅复制正文部分。 我能做什么?

您可以尝试使用Word Doc Generator ,它是使用Visual Studio 2010和Open XML 2.0 SDK从模板生成Word文档的实用程序。

您也可以尝试使用我们的GemBox.Document组件。

它具有非常用户友好和高效的邮件合并支持。 请参阅C#Word邮件合并文章和自定义邮件合并示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM