Working with Mail merge

13 Sep 20249 minutes to read

Mail merge is a process of merging data from data source to a Word template document. The WMergeField class provides support to bind template document and data source. The WMergeField instance is replaced with the actual data retrieved from data source for the given merge field name in a template document.

The following data sources are supported by Essential DocIO for performing Mail merge:

Data Source

Examples

String arrays

Mail merge with string arrays

DataRow

Generate multiple Word documents

DataSet

Product catalog

DataTable

Mail merge using DataTable

DataView

Generate letter for filtered contacts

DbConnection

Mail merge using OleDbConnection

IDataReader

Generate payroll for employees

OleDbDataReader

Generate certificate for employees

Dynamic

Mail merge with dynamic objects

IEnumerable

Create Envelopes for mailing

XML

Generate order details of customer from XML

JSON

Create and send email messages using JSON

MailMergeDataTable

Mail merge using MailMergeDataTable

MailMergeDataSet

Mail merge using MailMergeDataSet

To quickly get started with performing a mail merge in a Word document, please check out this video:

Assemblies and NuGet packages required

Refer to the following links for assemblies and NuGet packages required based on platforms for performing mail merge using the .NET Word Library (DocIO).

Mail merge process

The mail merge process involves three documents:

  1. Template Word document: This document contains the static or templated text and graphics along with the merge fields (that are placeholders) for replacing dynamic data.

  2. Data source: This represents file or database containing data to replace the merge fields in template Word document.

  3. Final merged document: This resultant document is a combination of the template Word document and the data from data source.

TIPS

  1. You can use conditional fields (IF, Formula) combined with merge fields, when you require intelligent decisions in addition to simple mail merge (replace merge fields with result text). To use conditional fields, execute mail merge and then update fields in the Word document using UpdateDocumentFields API.
  2. You can replace the fields (IF, Formula) combined with merge fields, with its most recent result and generates the plain Word document by unlinking the fields. Refer to this link for more information.

Create Word document template

You can create a template document with merge fields by using any Word editor application, like Microsoft Word. By using Word editor application, you can take the advantage of the visual interface to design unique layout, formatting, and more for your Word document template interactively.

The following screenshot shows how to insert a merge field in the Word document by using the Microsoft Word.

Word template document

You need to add a prefix (“Image:”) to the merge field name for merging an image in the place of a merge field.

For example: The merge field name should be like “Image:Photo” («Image:MergeFieldName»)

You can create Word document template programmatically by adding merge fields to the Word document using Essential DocIO.

The following code example shows how to create a merge field in the Word document.

NOTE

Refer to the appropriate tabs in the code snippets section: C# [Cross-platform] for ASP.NET Core, Blazor, Xamarin, UWP, .NET MAUI, and WinUI; C# [Windows-specific] for WinForms and WPF; VB.NET [Windows-specific] for VB.NET applications.

//Creates an instance of a WordDocument 
WordDocument document = new WordDocument();
//Adds a section and a paragraph in the document
document.EnsureMinimal();
//Appends merge field to the last paragraph.
document.LastParagraph.AppendField("FullName", FieldType.FieldMergeField);
//Saves the Word document to MemoryStream
MemoryStream stream = new MemoryStream();
document.Save(stream, FormatType.Docx);
//Closes the Word document
document.Close();
//Creates an instance of a WordDocument 
WordDocument document = new WordDocument();
//Adds a section and a paragraph in the document
document.EnsureMinimal();
//Appends merge field to the last paragraph.
document.LastParagraph.AppendField("FullName", FieldType.FieldMergeField);
//Saves and closes the WordDocument instance.
document.Save("Template.docx");
document.Close();
'Creates an instance of a WordDocument 
Dim document As WordDocument = New WordDocument
'Adds a section and a paragraph in the document
document.EnsureMinimal()
'Appends merge field to the last paragraph.
document.LastParagraph.AppendField("FullName", FieldType.FieldMergeField)
'Saves and closes the WordDocument instance.
document.Save("Template.docx")
document.Close()

You can download a complete working sample from GitHub.

Execute mail merge

The following code example shows how to perform mail merge in above Word document template using string arrays as data source.

//Opens the template document
FileStream fileStreamPath = new FileStream("Template.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx);
string[] fieldNames = new string[] { "FullName" };
string[] fieldValues = new string[] { "Nancy Davolio" };
//Performs the mail merge
document.MailMerge.Execute(fieldNames, fieldValues);
//Saves the Word document to MemoryStream
MemoryStream stream = new MemoryStream();
document.Save(stream, FormatType.Docx);
//Closes the Word document
document.Close();
//Opens the template document
WordDocument document = new WordDocument("Template.docx");
string[] fieldNames = new string[] { "FullName" };
string[] fieldValues = new string[] { "Nancy Davolio" };
//Performs the mail merge
document.MailMerge.Execute(fieldNames, fieldValues);
//Saves and closes the WordDocument instance
document.Save("Sample.docx", FormatType.Docx);
document.Close();
'Opens the template document
Dim document As New WordDocument("Template.docx")
Dim fieldNames As String() = New String() {"FullName"}
Dim fieldValues As String() = New String() {"Nancy Davolio"}
'Performs the mail merge
document.MailMerge.Execute(fieldNames, fieldValues)
'Saves and closes the WordDocument instance
document.Save("Sample.docx", FormatType.Docx)
document.Close()

You can download a complete working sample from GitHub.

By executing the previous code example, it generates the resultant Word document as follows.

Mail merge Word document

Simple Mail merge

The MailMerge class provides various overloads for the Execute method to perform Mail merge from various data sources. For further information, click here.

Performing Mail merge for a group

You can perform Mail merge and append multiple records from data source within a specified region to a template document. For further information, click here.

Performing Nested Mail merge for group

You can perform nested Mail merge with relational or hierarchical data source and independent data tables in a template document. For further information, click here.

Performing Mail merge with dynamic objects

Essential DocIO allows you to perform Mail merge with the dynamic objects. For further information, click here.

Performing Mail merge with business objects

You can perform Mail merge with business objects in a template document. For further information, click here.

Performing Nested Mail merge with relational data objects

Essential DocIO supports performing nested Mail merge with implicit relational data objects without any explicit relational commands by using the ExecuteNestedGroup overload method. For further information, click here.

Event support for mail merge

The MailMerge class provides event support to customize the document contents and merging image data during the Mail merge process. The following events are supported by Essential DocIO in Mail merge process:

MergeField event

You can customize the merging text during Mail merge process by using the MergeField event. For further information, click here.

MergeImageField event

You can customize the merging image during Mail merge process by using the MergeImageField event. For further information, click here.

BeforeClearField event

You can get the unmerged fields during Mail merge process by using the BeforeClearField event. For further information, click here.

BeforeClearGroupField event

You can get the unmerged groups during Mail merge process by using the BeforeClearGroupField event. For further information, click here.

Mail merge options

The MailMerge class allows you to customize the Mail merge process with the following options:

Field mapping

You can automatically map the merge field names with data source column names during Mail merge process. For further information, click here.

Retrieving the merge field names

You can retrieve the merge field names and also merge field group names in the Word document. For further information, click here.

Removing empty paragraphs

You can remove the empty paragraphs when the paragraph has a merge field item without any data during Mail merge process. For further information, click here.

Removing empty merge fields

You can remove or keep the unmerged merge fields in the output document based on the ClearFields property on each mail merge execution. For further information, click here.

Restart numbering in lists

You can restart the list numbering in a Word document during Mail merge. For further information, click here.

Online Demo

  • Explore how to generate a letter using mail merge functionality using the .NET Word Library (DocIO) in a live demo here.

See Also