Articles in this section
Category / Section

How to replace merge field with table using mail merge in Word document?

7 mins read

Syncfusion DocIO is a .NET Core Word library used to create, read, and edit Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can replace merge field with table using mail merge in Word document using C#.

Steps to replace merge field with table using mail merge in Word document

  1. Create a new C# .NET Core console application project.

    Create console in Visual Studio

  2. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from Nuget.org.

    Install Syncfusion Word Library NuGet packages

Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering a Syncfusion license key in your application to use the components without trail message.

  1. Include the following namespace in the Program.cs file​.
    C#
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
  1. Include the below code snippet to replace merge field with table using mail merge in a Word document.
    C#
//Declare and initialize dictionary for tables
static Dictionary<WParagraph, Dictionary<int, WTable>> paraToInsertTable = new Dictionary<WParagraph, Dictionary<int, WTable>>();
using (FileStream fileStream = new FileStream(Path.GetFullPath(@"../../../Template.docx"), FileMode.Open, FileAccess.ReadWrite))
{
   //Loads an existing Word document into DocIO instance.
   using (WordDocument document = new WordDocument(fileStream, FormatType.Automatic))
   {
       //Enables the flag to start each record in new page.
       document.MailMerge.StartAtNewPage = true;
       //Gets the employee details as “IEnumerable” collection
       List<Employees> employeeList = GetEmployeeData(document);
       //Creates an instance of MailMergeDataTable by specifying MailMerge group name and IEnumerable collection.
       MailMergeDataTable dataTable = new MailMergeDataTable("Employees", employeeList);
       //Uses the mail merge event handler to insert chart during mail merge.
       document.MailMerge.MergeField += new MergeFieldEventHandler(MergeField_Table);
       //Performs Mail merge.
       document.MailMerge.ExecuteGroup(dataTable);
       InsertTable();
       //Unhooks the event after mail merge execution.
       document.MailMerge.MergeField -= new MergeFieldEventHandler(MergeField_Table);
       //Creates file stream.
       using (FileStream outputStream = new FileStream(Path.GetFullPath(@"../../../Result.docx"), FileMode.Create, FileAccess.ReadWrite))
       {
           //Saves the Word document to file stream.
           document.Save(outputStream, FormatType.Docx);
       }
   }
}
  1. Use the following methods to retrieve the list of employees.
    C#
// Gets the employee data to perform mail merge. 
public static List<Employees> GetEmployeeData(WordDocument document)
{
   WTable table = CreateTable(document);
   //Adds all details in employee data collection for all employees.
   List<Employees> employeeData = new List<Employees>();
   employeeData.Add(new Employees("Nancy", "Davolio", "1", "505 - 20th Ave. E. Apt. 2A,", "Seattle", "USA", table));
  
   return employeeData;
}

// Creates the table.
private static WTable CreateTable(WordDocument document)
{
   //Adds a new table into Word document
   WTable table = new WTable(document);
   //Specifies the total number of rows & columns
   table.ResetCells(3, 2);
   //Accesses the instance of the cell (first row, first cell) and adds the content into cell
   IWTextRange textRange = table[0, 0].AddParagraph().AppendText("Item");
   textRange.CharacterFormat.FontName = "Arial";
   textRange.CharacterFormat.FontSize = 12;
   textRange.CharacterFormat.Bold = true;
   //Accesses the instance of the cell (first row, second cell) and adds the content into cell
   textRange = table[0, 1].AddParagraph().AppendText("Number of items sold out");
   textRange.CharacterFormat.FontName = "Arial";
   textRange.CharacterFormat.FontSize = 12;
   textRange.CharacterFormat.Bold = true;
   //Accesses the instance of the cell (second row, first cell) and adds the content into cell
   textRange = table[1, 0].AddParagraph().AppendText("Mountain-350");
   textRange.CharacterFormat.FontName = "Arial";
   textRange.CharacterFormat.FontSize = 10;
   //Accesses the instance of the cell (second row, second cell) and adds the content into cell
   textRange = table[1, 1].AddParagraph().AppendText("50");
   textRange.CharacterFormat.FontName = "Arial";
   textRange.CharacterFormat.FontSize = 10;
   //Accesses the instance of the cell (third row, first cell) and adds the content into cell
   textRange = table[2, 0].AddParagraph().AppendText("Mountain-500");
   textRange.CharacterFormat.FontName = "Arial";
   textRange.CharacterFormat.FontSize = 10;
   //Accesses the instance of the cell (third row, second cell) and adds the content into cell
   textRange = table[2, 1].AddParagraph().AppendText("30");
   textRange.CharacterFormat.FontName = "Arial";
   textRange.CharacterFormat.FontSize = 10;
   return table;
}
  1. Use the following method to handle the mail merge event
    C#
// Represents the method that handles MergeField event.
private static void MergeField_Table(object sender, MergeFieldEventArgs args)
{
   if (args.FieldName == "TableDetails")
   {
       //Gets the current merge field owner paragraph.
       WParagraph paragraph = args.CurrentMergeField.OwnerParagraph;
       WTextBody ownerTextBody = paragraph.OwnerTextBody;
       //Gets the index of the owner paragraph.
       int paraIndex = ownerTextBody.ChildEntities.IndexOf(args.CurrentMergeField.OwnerParagraph);
       //Maintain table in collection.
       Dictionary<int, WTable> fieldValues = new Dictionary<int, WTable>();
       fieldValues.Add(paraIndex, args.FieldValue as WTable);
       //Maintain paragraph in collection.
       paraToInsertTable.Add(paragraph, fieldValues);
       //Set field value as empty.
       args.Text = string.Empty;
   }
}
  1. Use the following method to insert the table.
    C#
// Append Table to Textbody.
private static void InsertTable()
{
   //Iterates through each item in the dictionary.
   foreach (KeyValuePair<WParagraph, Dictionary<int, WTable>> dictionaryItems in paraToInsertTable)
   {
       WParagraph paragraph = dictionaryItems.Key;
       Dictionary<int, WTable> values = dictionaryItems.Value;
       //Iterates through each value in the dictionary.
       foreach (KeyValuePair<int, WTable> valuePair in values)
       {

           int index = valuePair.Key;
           WTable fieldValue = valuePair.Value;
           //Inserts table at the same position of mergefield in Word document.
           paragraph.OwnerTextBody.ChildEntities.Insert(index, fieldValue);
       }
   }
   paraToInsertTable.Clear();
}
  1. Use the following helper class to create employee list
    C#
#region Helper Class
// Represents a class to maintain employee details.
public class Employees
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string EmployeeID { get; set; }
   public string Address { get; set; }
   public string City { get; set; }
   public string Country { get; set; }
   public WTable TableDetails { get; set; }
   public Employees(string firstName, string lastName, string employeeID, string address, string city, string country, WTable tableDetails)
   {
       FirstName = firstName;
       LastName = lastName;
       EmployeeID = employeeID;
       Address = address;
       City = city;
       Country = country;
       TableDetails = tableDetails;
   }
}
#endregion

A complete working sample to replace merge field with table using mail merge in Word document can be downloaded from GitHub.

Take a moment to peruse the [documentation](https where you can find basic Word document processing options along with the features like mail merge, merge, split, and compare documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples.

Conclusion
I hope you enjoyed learning about how to replace merge field with table using mail merge in a Word document using .NET Core Word Library.

You can refer to our ASP.NET Core DocIO feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core DocIO example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied