In Spire.Doc, we can use mail merge to insert multiple records from data source to a specified region in a Word template document. The region must be marked by two merge fileds with special names like «GroupStart:GroupName» and «GroupEnd:GroupName», where GroupStart and GroupEnd means the start and end point of a group, it's also the start and end point of the region. After performing Mail merge, the region gets repeated for every record from the data source.
For better demonstration, we created a template document with merge fields as follows:
In this template, "Products" is the group name and we should use the same name when executing mail merge using code. The merge fileds “GroupStart:Products” and “GroupEnd:Products” mean the start and end of the group and the region.
Code snippets:
At first, we defined a class named "Product", in which we created a constructor Product (int number, string type, string name, string price, string vendor, string expirydate) and added four properties "Number", "Type", "Name", "Price", "Vendor" and "ExpiryDate".
Step 1: Instantiate two objects of the Product class and add them into a list.
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);
Step 2: Load the template document.
Document document = new Document("ProductsList.docx");
Step 3: Use the list as data source and execute Mail merge for the group "Products".
MailMergeDataTable table = new MailMergeDataTable("Products", list); document.MailMerge.ExecuteGroup(table);
Step 4: Save the document.
document.SaveToFile("Output.docx");
After executing above code, we will get the resultant document as follows:
Full codes:
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; } } }