Identify Merge Field Names in Word with C#

We often come across a scenario where we need to merge data to the merge fields which are created by some others, and we are not sure about the merge fields’ names. So in order to accomplish the mail merge purpose, first we need to read the names of all the merge fields.

The MailMerge class in Spire.Doc.Reporting namespace exposes the following methods which return a collection of merge field names or group (region) names in a word document.

  • public string[] GetMergeFieldNames(): return a collection of all the merge field names.
  • public string[] GetMergeFieldNames(string groupName): return a collection of merge field names within a specific group.
  • public string[] GetMergeGroupNames(): return a collection of group names.

For better demonstration, we use the following sample document:

Identify Merge Field Names in Word with C#

The following example elaborates how to read the names of groups and merge fields in above word document.

//Creates Document instance
Document document = new Document();

//Loads the word document
document.LoadFromFile("MergeFields.docx");

//Gets the collection of group names
string[] GroupNames = document.MailMerge.GetMergeGroupNames();

//Gets the collection of merge field names in a specific group
string[] MergeFieldNamesWithinRegion = document.MailMerge.GetMergeFieldNames("Products");

// Gets the collection of all the merge field names
string[] MergeFieldNames = document.MailMerge.GetMergeFieldNames();

Console.WriteLine("----------------Group Names-----------------------------------------");
for (int i = 0; i < GroupNames.Length; i++)
{
Console.WriteLine(GroupNames[i]);
}

Console.WriteLine("----------------Merge field names within a specific group-----------");
for (int j = 0; j < MergeFieldNamesWithinRegion.Length; j++)
{
Console.WriteLine(MergeFieldNamesWithinRegion[j]);
}

Console.WriteLine("----------------All of the merge field names------------------------");
for (int k = 0; k < MergeFieldNames.Length; k++)
{
Console.WriteLine(MergeFieldNames[k]);
}

Screenshot:

Identify Merge Field Names in Word with C#