将文档与 OpenXML 2.0 合并

本文关键字:合并 OpenXML 文档 | 更新日期: 2023-09-27 18:31:45

我正在尝试将数据库中的一些信息和一些图片插入到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 循环时,它会抛出错误,因为它试图复制完整的文档结构而不仅仅是正文部分。我能做什么?

将文档与 OpenXML 2.0 合并

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

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

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