Products Technologies Demo Docs Blog Support Company

Mail Merge MS Word Office Open XML (DOCX) Templates in C#

TX Text Control's MailMerge engine allows you to perform MS Word compatible mail merge processes in .NET based applications. This article gives an overview of the basic functionality and shows how to merge JSON data into templates.

Mail Merge MS Word Office Open XML (DOCX) Templates in C#

Using TX Text Control, merging data into MS Word compatible templates can be effortlessly done in 3 simple steps.

  • Loading a template
  • Merging with data
  • Exporting the document

Loading a Template

The MailMerge class merges the data from various data sources into documents. It can be connected to any Text Control (TXTextControl.ServerTextControl, TXTextControl.TextControl and TXTextControl.WPF.TextControl. The document that is loaded into the connected Text Control is automatically used as the mail merge template.

The following code shows how to create a Mailmerge instance and how to connect it to a ServerTextControl:

using (MailMerge mailMerge = new MailMerge()) {
  mailMerge.TextComponent = textControl1;
}

In the next code snippet an Office Open XML (DOCX) template is loaded into a new ServerTextControl instance that is then connected to MailMerge:

TXTextControl.LoadSettings ls = new TXTextControl.LoadSettings() {
  ApplicationFieldFormat = TXTextControl.ApplicationFieldFormat.MSWord };

using (TXTextControl.ServerTextControl serverTextControl =
       new TXTextControl.ServerTextControl()) {
  serverTextControl.Create();
  serverTextControl.Load("template.docx", TXTextControl.StreamType.WordprocessingML, ls);

  using (MailMerge mailMerge = new MailMerge()) {
    mailMerge.TextComponent = serverTextControl;
  }
}

The template can be any MS Word document with merge fields that can be added using the pre-designed Reporting ribbon tab of the TX Text Control visual editor or using MS Word. The sample template is shown in the next screenshot:

Creating documents with TX Text Control

Merging with Data

MailMerge provides support for the following data sources:

  • DataTable
  • DataSet
  • IEnumerable objects
  • JSON
  • XML

For all of these data source, different Merge methods and implementations are available. For simplicity, the following JSON string is used as the data source:

[
  {
    "company_name": "Text Control, LLC",
    "address":
    {
      "street": "1111 Text Control Way",
      "zip": "28226",
      "city": "Charlotte",
      "country": "United States"
    }
  }
]

In the next code snippet, the MergeJsonData is used to merge the template with the given JSON data.

// enable MS Word merge fields
TXTextControl.LoadSettings ls = new TXTextControl.LoadSettings() {
  ApplicationFieldFormat = TXTextControl.ApplicationFieldFormat.MSWord };

// load JSON data
string jsonData = System.IO.File.ReadAllText("data.json");

// create a temporary ServerTextControl
using (TXTextControl.ServerTextControl serverTextControl = 
       new TXTextControl.ServerTextControl()) {
  serverTextControl.Create();
  
  // load the template
  serverTextControl.Load("template.docx", TXTextControl.StreamType.WordprocessingML, ls);

  // create the mail merge engine
  using (MailMerge mailMerge = new MailMerge()) {
    // connect to ServerTextControl
    mailMerge.TextComponent = serverTextControl;
    // merge data into template
    mailMerge.MergeJsonData(jsonData);
  }
}

The resulting document is shown in the screenshot:

Creating documents with TX Text Control

Exporting the Document

After a successful merge process, the resulting document is loaded into the connected Text Control instance and can be exported to any supported document format. The following code shows how the resulting document is getting exported as an Adobe PDF document.

TXTextControl.LoadSettings ls = new TXTextControl.LoadSettings() {
  ApplicationFieldFormat = TXTextControl.ApplicationFieldFormat.MSWord };

string jsonData = System.IO.File.ReadAllText("data.json");

using (TXTextControl.ServerTextControl serverTextControl =
       new TXTextControl.ServerTextControl()) {
  serverTextControl.Create();
  serverTextControl.Load("template.docx", TXTextControl.StreamType.WordprocessingML, ls);

  using (MailMerge mailMerge = new MailMerge()) {
    mailMerge.TextComponent = serverTextControl;
    mailMerge.MergeJsonData(jsonData);
  }

  // export document as PDF
  serverTextControl.Save("results.pdf", TXTextControl.StreamType.AdobePDF);
}

Mail Merge Events

MailMerge provides many events to control the merge process and to interact with fields by injecting custom data or logic. The following events can be used during the mail merge process:

Event Description
BarcodeMerged Occurs when a barcode has been merged successfully.
BlockMerging Occurs when a merge block is about to be merged.
BlockRowMerged Occurs when a merge block row has been merged successfully.
ChartMerged Occurs when a chart has been merged successfully.
DataRowMerged Occurs when a data row has been merged successfully.
FieldMerged Occurs when a field has been merged.
FormFieldMerged Occurs when a form field has been merged.
ImageFieldMerged Occurs when an image field, i.e., a merge field whose name is prefixed with "image:" has been merged.
ImageMerged Occurs when an image has been merged successfully.
IncludeTextMerging Occurs when an IncludeText field has been merged.

The number and the names of the events show that MailMerge provides way more than a simple mail merge process. MailMerge is a powerful rendering engine that supports repeating merge blocks, 1:n relationships, image merging, barcode support and populating form fields. Generally speaking, all document automation processes can be realized using the MailMerge class.

Reading Tip: Event Handling

MailMerge: Field Mapping and Handling of Unmerged Fields

Read More

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

ASP.NET

Integrate document processing into your applications to create documents such as PDFs and MS Word documents, including client-side document editing, viewing, and electronic signatures.

ASP.NET Core
Angular
Blazor
JavaScript
React
  • Angular
  • Blazor
  • React
  • JavaScript
  • ASP.NET MVC, ASP.NET Core, and WebForms

Learn more Trial token Download trial

Related Posts

ASP.NETWindows FormsWPF

MailMerge: Field Mapping and Handling of Unmerged Fields

Text Control's MailMerge API maps merge fields in templates with columns in supported data sources. This article explains the structure and how to handle unmerged fields.


ASP.NETWindows FormsWPF

Generating Hierarchical Tables from JSON Data in .NET C#

Using TX Text Control, you can generate complex hierarchical tables directly from JSON data. This article explains the code and logic behind it.


ASP.NETWindows FormsWPF

MailMerge: Merging Hyperlinks using the FieldMerged Event

The MailMerge class is used to merge data into merge fields, image placeholders, barcodes and other reporting elements. With the help of the flexible FieldMerged event, additional elements can be…


ASP.NETWindows FormsWPF

MailMerge: Data Structures Explained with a Sample Template and JSON Data

The MailMerge class is used to merge JSON data into templates including merge fields and repeating merge blocks. This article gives an overview of the data structure based on a sample template…


ASP.NETWindows FormsWPF

Adding Sorting and Filter Instructions to Existing MergeBlocks

Merge blocks can be filtered and sorted with linked instructions that help to shape the used data in each merge block. This article shows how to add sorting and filter instructions to existing…