邮件如何使用C#在Word文档中进行邮件合并?Aspose.Words解析攻略
邮件合并是自动生成报告 , 信件 , 信封 , 发票和其他类型的文档的方式 。 MS Word中的邮件合并允许您创建包含合并字段的模板文档 , 然后使用数据源中的记录填充这些字段 。 要了解邮件合并 , 假设您必须向十个不同的人发送一封信 , 并且仅姓名和地址字段将被更新 。 在这种情况下 , 只需创建字母的模板 , 然后通过使用数据源填充名称和地址合并字段来动态生成字母 。
可以从任何数据源(例如XML , JSON或数据库)中获取邮件合并的数据 。 就Aspose.Words for .NET而言 , 可以使用ADO.NET支持的任何数据源 。 可以将数据加载到DataSet , DataTable , DataView或值数组中 。
邮件合并模板是包含合并字段的文档 。 执行“邮件合并”时 , 这些字段然后用数据源中的数据填充 。 模板文档不需要是模板格式 , 可以是DOC / DOCX文档 。 这是您可以为邮件合并准备模板的方法 。
- 在MS Word中打开您的文档或创建一个新文档 。
- 将光标放在要添加合并字段的位置 。
- 从 插入 菜单中选择 字段 选项 。
- 从 字段名称 列表中 , 选择 MergeField 。
- 在字段名称中为合并字段输入名称 , 然后按 确定 。
- 保存文档 。
本文插图
使用C#在Word文档中执行邮件合并
准备好模板后 , 可以执行邮件合并以生成文档 。 以下是在上述模板上执行邮件合并的步骤 。
- 使用Document类加载模板文档 。
- 设置必需的邮件合并选项 , 例如Document.MailMerge.TrimWhitespaces 。
- 使用Document.MailMerge.Execute()方法执行邮件合并 , 并将数据源作为参数传递 。
- 使用Document.Save(String)方法保存生成的文档 。
【邮件如何使用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#中的XML数据源执行邮件合并
XML文件被广泛用于保存以及导入/导出数据 。 Aspose.Words for .NET还支持XML作为邮件合并的数据源 。 只需将XML读入DataSet对象并执行邮件合并 。 以下是我们将要使用的示例XML文件 。
本文插图
下面的代码示例从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)
推荐阅读
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 机智萌妹|A72拍照实力如何?,OPPO千元5G新机开售,这款OPPO
- 寒武纪科学馆|太空飞船如何安全返回地球?经历哪几个阶段?了解一下
- 数码达人分享|X1蓝牙耳机不易脱落,运动蓝牙耳机如何选择,HIK
- 中国青年网|如何入环火轨道,揭秘“天问一号”如何在太空保持轨道
- 作文|如何正确看待,张子枫的高考事件?很多人都是断章取义吗?
- 狗哥说游戏|一代人的热血游戏《传奇》IP是如何营销的?,娱美德
- 陈薇院士回应疫苗发热率高|陈薇院士回应疫苗发热率高 如何回应?有啥影响?
- 北斗|北斗卫星高密度发射 产品质量如何保证?专家回应
- 家装百科|如何用银色配饰搭出清凉感?3套40岁左右时尚达人的夏日穿搭示范
- 大众途锐|Model 3售价确认!国产版价格控制在20万内,本土品牌如何生存?
