Mail merge Word file in C# and VB.NET

Mail merge Word file (DOCX) with any .NET data source object in C# and VB.NET with GemBox.Document component.

Mail merge is a process of merging or importing data from a .NET object, also known as data source, to a DocumentModel instance, also known as template document.
Binding between data source and template document is provided by Field class whose FieldType property is MergeField (usually called a merge field).
GemBox.Document supports almost any .NET object to be used as a mail merge data source. For more details, see GemBox.Document Mail Merge.

Following example creates a template document and mail merges it with a .NET anonymous type object. Both template and resulting documents are saved as Word files (DOCX) and opened in Microsoft Word.

C# code

// Create a new empty document.
var document = new DocumentModel();

// Add document content.
document.Sections.Add(
new Section(document,
new Paragraph(document,
new Field(document, FieldType.MergeField, "FullName"))));

// Save the document to a file and open it with Microsoft Word.
document.Save("TemplateDocument.docx");
// If document appears empty in Microsoft Word, press Alt + F9.
Process.Start("TemplateDocument.docx");

// Initialize mail merge data source.
var dataSource = new { FullName = "John Doe" };

// Execute mail merge.
document.MailMerge.Execute(dataSource);

// Save the document to a file and open it with Microsoft Word.
document.Save("Document.docx");
Process.Start("Document.docx");

VB.NET code

' Create a new empty document.
Dim document = New DocumentModel()

' Add document content.
document.Sections.Add(
New Section(document,
New Paragraph(document,
New Field(document, FieldType.MergeField, "FullName"))))

' Save the document to a file and open it with Microsoft Word.
document.Save("TemplateDocument.docx")
' If document appears empty in Microsoft Word, press Alt + F9.
Process.Start("TemplateDocument.docx")

' Initialize mail merge data source.
Dim dataSource = New With {.FullName = "John Doe"}

' Execute mail merge.
document.MailMerge.Execute(dataSource)

' Save the document to a file and open it with Microsoft Word.
document.Save("Document.docx")
Process.Start("Document.docx")

For more detailed examples, see Mail Merge samples from GemBox.Document Sample Explorer.