How to replace a merge field with a table using mail merge in Word document?
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 a merge field with a table using mail merge in a Word document using C#.
Steps to replace a merge field with a table using mail merge in a Word document
-
Create a new C# .NET Core console application project.
-
Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from NuGet.org.
Starting with v16.2.0.x, if you reference Syncfusion® assemblies from a 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 a trial message.
- Include the following namespace in the Program.cs file:
C#
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
- Include the below code snippet to replace a merge field with a 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 on a new page.
document.MailMerge.StartAtNewPage = true;
// Gets the employee details as an “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 a 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 a file stream.
using (FileStream outputStream = new FileStream(Path.GetFullPath(@"../../../Result.docx"), FileMode.Create, FileAccess.ReadWrite))
{
// Saves the Word document to the file stream.
document.Save(outputStream, FormatType.Docx);
}
}
}
- 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 the 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 the Word document.
WTable table = new WTable(document);
// Specifies the total number of rows and columns.
table.ResetCells(3, 2);
// Accesses the instance of the cell (first row, first cell) and adds the content into the 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 the 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 the 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 the 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 the 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 the cell.
textRange = table[2, 1].AddParagraph().AppendText("30");
textRange.CharacterFormat.FontName = "Arial";
textRange.CharacterFormat.FontSize = 10;
return table;
}
- Use the following method to handle the mail merge event.
C#
// Represents the method that handles the 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 the field value as empty.
args.Text = string.Empty;
}
}
- 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 the table at the same position of the merge field in the Word document.
paragraph.OwnerTextBody.ChildEntities.Insert(index, fieldValue);
}
}
paraToInsertTable.Clear();
}
- Use the following helper class to create the 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 a merge field with a table using mail merge in a Word document can be downloaded from GitHub.
Take a moment to peruse the documentation where you can find basic Word document processing options along with features like mail merge, merge, split, and compare Word documents, find and replace text in the Word document, protect Word documents, and most importantly, the PDF and Image conversions with code examples.
Conclusion
I hope you enjoyed learning about how to replace a merge field with a 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 learn about its other groundbreaking feature representations and documentation, and how to quickly get started with 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!