邮件如何使用C#在Word文档中进行邮件合并?Aspose.Words解析攻略


邮件合并是自动生成报告 , 信件 , 信封 , 发票和其他类型的文档的方式 。 MS Word中的邮件合并允许您创建包含合并字段的模板文档 , 然后使用数据源中的记录填充这些字段 。 要了解邮件合并 , 假设您必须向十个不同的人发送一封信 , 并且仅姓名和地址字段将被更新 。 在这种情况下 , 只需创建字母的模板 , 然后通过使用数据源填充名称和地址合并字段来动态生成字母 。
可以从任何数据源(例如XML , JSON或数据库)中获取邮件合并的数据 。 就Aspose.Words for .NET而言 , 可以使用ADO.NET支持的任何数据源 。 可以将数据加载到DataSet , DataTable , DataView或值数组中 。
邮件合并模板是包含合并字段的文档 。 执行“邮件合并”时 , 这些字段然后用数据源中的数据填充 。 模板文档不需要是模板格式 , 可以是DOC / DOCX文档 。 这是您可以为邮件合并准备模板的方法 。

  • 在MS Word中打开您的文档或创建一个新文档 。
  • 将光标放在要添加合并字段的位置 。
  • 从 插入 菜单中选择 字段 选项 。
  • 从 字段名称 列表中 , 选择 MergeField 。
  • 在字段名称中为合并字段输入名称 , 然后按 确定 。
  • 保存文档 。
以下是示例模板文档的屏幕截图 。
邮件如何使用C#在Word文档中进行邮件合并?Aspose.Words解析攻略
本文插图
使用C#在Word文档中执行邮件合并
准备好模板后 , 可以执行邮件合并以生成文档 。 以下是在上述模板上执行邮件合并的步骤 。
  • 使用Document类加载模板文档 。
  • 设置必需的邮件合并选项 , 例如Document.MailMerge.TrimWhitespaces 。
  • 使用Document.MailMerge.Execute()方法执行邮件合并 , 并将数据源作为参数传递 。
  • 使用Document.Save(String)方法保存生成的文档 。
下面的代码示例演示如何使用C#中的值数组执行MS Word邮件合并 。
【邮件如何使用C#在Word文档中进行邮件合并?Aspose.Words解析攻略】// The path to the documents directory.string dataDir = RunExamples.GetDataDir_MailMergeAndReporting() // Open an existing document.Document doc = new Document(dataDir + "MailMerge.ExecuteArray.doc")// Trim trailing and leading whitespaces mail merge valuesdoc.MailMerge.TrimWhitespaces = false// Fill the fields in the document with user data.doc.MailMerge.Execute( new string[] { "FullName", "Company", "Address", "Address2", "City" }, new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" })dataDir = dataDir + "MailMerge.ExecuteArray_out.doc"// Send the document in Word format to the client browser with an option to save to disk or open inside the current browser.doc.Save(dataDir)
邮件合并后的Word文档
邮件如何使用C#在Word文档中进行邮件合并?Aspose.Words解析攻略
本文插图
使用C#中的XML数据源执行邮件合并
XML文件被广泛用于保存以及导入/导出数据 。 Aspose.Words for .NET还支持XML作为邮件合并的数据源 。 只需将XML读入DataSet对象并执行邮件合并 。 以下是我们将要使用的示例XML文件 。
邮件如何使用C#在Word文档中进行邮件合并?Aspose.Words解析攻略
本文插图
下面的代码示例从XML数据源获取数据 , 并使用C#执行邮件合并 。
// The path to the documents directory.string dataDir = RunExamples.GetDataDir_MailMergeAndReporting() // Create the Dataset and read the XML.DataSet customersDs = new DataSet()customersDs.ReadXml(dataDir + "Customers.xml")string fileName = "TestFile XML.doc"// Open a template document.Document doc = new Document(dataDir + fileName)// Execute mail merge to fill the template with data from XML using DataTable.doc.MailMerge.Execute(customersDs.Tables["Customer"])dataDir = dataDir + RunExamples.GetOutputFilePath(fileName)// Save the output document.doc.Save(dataDir)


推荐阅读