【问题标题】:Merging Documents with OpenXML 2.0使用 OpenXML 2.0 合并文档
【发布时间】:2015-02-27 04:38:16
【问题描述】:

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

【问题讨论】:

  • @TravisJ 我以前从未真正做过这样的事情。所以任何帮助表示赞赏。我不一定要求解决方案。只是方向正确的一点。
  • 如果您有 Visual Studio,请先查看他们的 word 2007 模板项目。 (还有一个word 2003模板项目)。我认为这应该是“正确方向的一点”

标签: c# .net ms-word openxml


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多