在 Spire.Doc 中,我们可以使用邮件合并将数据源中的多条记录插入到 Word 模板文档中的指定区域。该区域必须由两个具有特殊名称的合并文件标记,如roupStart:GroupNameroupEnd:GroupName其中GroupStart和GroupEnd表示一个组的起点和终点,它也是该区域的起点和终点。执行邮件合并后,该区域会针对数据源中的每条记录重复。
为了更好地演示,我们创建了一个包含合并字段的模板文档,如下所示:

在这个模板中,“产品”是组名,我们在使用代码执行邮件合并时应该使用相同的名称。合并文件“GroupStart:Products”和“GroupEnd:Products”表示组和区域的开始和结束。
代码片段:
一开始,我们定义了一个名为“Product”的类,在其中我们创建了一个构造函数Product(int number,string type,string name,string price,string vendor,string expirydate)并添加了四个属性“ Number ”,“ Type ”, “名称”、“价格”、“供应商”和“到期日期”。
第 1 步:实例化 Product 类的两个对象并将它们添加到列表中。
Product p1 = new Product(1, "Software", "Spire.Doc", "$799", "E-iceblue", "April 28th,2018");Product p2 = new Product(2, "Software", "Spire.PDF", "$599", "E-iceblue", "September 15th,2017");List<Product> list = new List<Product>();list.Add(p1);list.Add(p2);
第 2 步:加载模板文档。
Document document = new Document("ProductsList.docx");
第 3 步:使用列表作为数据源并为“产品”组执行邮件合并。
MailMergeDataTable table = new MailMergeDataTable("Products", list);document.MailMerge.ExecuteGroup(table);
第 4 步:保存文档。
document.SaveToFile("Output.docx");
执行上述代码后,我们会得到如下结果文件:

完整代码:
using Spire.Doc;using Spire.Doc.Reporting;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MailMerge{class Program{static void Main(string[] args){Product p1 = new Product(1, "Software", "Spire.Doc", "$799", "E-iceblue", "April 28th,2018");Product p2 = new Product(2, "Software", "Spire.PDF", "$599", "E-iceblue", "September 15th,2017");List list = new List();list.Add(p1);list.Add(p2);Document document = new Document("ProductsList.docx");MailMergeDataTable table = new MailMergeDataTable("Products", list);document.MailMerge.ExecuteGroup(table);document.SaveToFile("Output.docx");}}public class Product{public Product(int number, string type, string name, string price, string vendor, string expirydate){this.Number = number;this.Type = type;this.Name = name;this.Price = price;this.Vendor = vendor;this.ExpiryDate = expirydate;}public int Number { get; set; }public string Type { get; set; }public string Name { get; set; }public string Price { get; set; }public string Vendor { get; set; }public string ExpiryDate { get; set; }}}
欢迎下载|体验更多E-iceblue产品
如需获取更多产品相关信息请咨询在线客服
标签:
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!