Mail Merge in Word with C# and VB.NET
Mail merge is the process of merging or importing data from a data source to a Word document. With GemBox.Document you can do a mail merge programmatically, using C# and VB.NET. In essence, the process involves replacing the Field
elements of the MergeField
type with values from from provided objects.
GemBox.Document exposes all mail merge related operations and options through the DocumentModel.MailMerge
property.
You can read the complete documentation on the Mail Merge help page.
The following example shows how you can perform a simple mail merge by importing data from an anonymous type object.
using GemBox.Document;
using System;
class Program
{
static void Main()
{
// If using the Professional version, put your serial key below.
ComponentInfo.SetLicense("FREE-LIMITED-KEY");
var document = DocumentModel.Load("%InputFileName%");
// Create data source for mail merge process.
var data = new
{
Number = 10203,
Date = DateTime.Now,
Company = "ACME Corp",
Address = "240 Old Country Road, Springfield, IL",
Country = "USA",
FullName = "Joe Smith"
};
// Execute mail merge process.
document.MailMerge.Execute(data);
document.Save("Mail Merge Output.%OutputFileType%");
}
}
Imports GemBox.Document
Imports System
Module Program
Sub Main()
' If using the Professional version, put your serial key below.
ComponentInfo.SetLicense("FREE-LIMITED-KEY")
Dim document = DocumentModel.Load("%InputFileName%")
' Create data source for mail merge process.
Dim data = New With
{
.Number = 10203,
.Date = DateTime.Now,
.Company = "ACME Corp",
.Address = "240 Old Country Road, Springfield, IL",
.Country = "USA",
.FullName = "Joe Smith"
}
' Execute mail merge process.
document.MailMerge.Execute(data)
document.Save("Mail Merge Output.%OutputFileType%")
End Sub
End Module