Creating Mail Merge for a group in C#

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:

Creating Mail Merge for a group in C#

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:

Creating Mail Merge for a group in C#

Full codes:

using System.Collections.Generic;
using Spire.Doc;
using Spire.Doc.Reporting;

namespace Mail_Merge_for_Group
{
    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<Product> list = new List<Product>();
            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");
        }
    }
}