Mail Merge in Word with C# and VB.NET

Mail merge is a process of merging or importing data from a data source to a document.

Following sample demonstrates how to perform a simple mail merge by importing data from an instance of an anonymous type.

Input template document also defines formatting for DateTime field using the field date/time formatting switch (\@).

To view field switches in Microsoft Word, press Alt + F9 to toggle field codes.

Field numeric switch (\#) is also supported for formatting numeric data types in the mail merge process.

Screenshot

Merge Fields Screenshot

See the full code below, use RUN EXAMPLE to execute.

Upload your file (Drag files here)

1using System;
2using System.Collections.Generic;
3using System.Data;
4using System.IO;
5using System.Linq;
6using GemBox.Document;
7using GemBox.Document.MailMerging;
8
9class Sample
10{
11    [STAThread]
12    static void Main(string[] args)
13    {
14        // If using Professional version, put your serial key below.
15        ComponentInfo.SetLicense("FREE-LIMITED-KEY");
16
17        DocumentModel document = DocumentModel.Load("MergeFields.docx");
18
19        var customer = new { CustomerName = "John", Surname = "Doe", Date = DateTime.Now };
20
21        document.MailMerge.Execute(customer);
22
23        document.Save("Merge Fields.docx");
24    }
25}
1Imports System
2Imports System.Collections.Generic
3Imports System.Data
4Imports System.IO
5Imports System.Linq
6Imports GemBox.Document
7Imports GemBox.Document.MailMerging
8
9Module Samples
10
11    Sub Main()
12
13        ' If using Professional version, put your serial key below.
14        ComponentInfo.SetLicense("FREE-LIMITED-KEY")
15
16        Dim document As DocumentModel = DocumentModel.Load("MergeFields.docx")
17
18        Dim customer = New With {.CustomerName = "John", .Surname = "Doe", .Date = DateTime.Now}
19
20        document.MailMerge.Execute(customer)
21
22        document.Save("Merge Fields.docx")
23
24    End Sub
25
26End Module

Check next sample or find out more about GemBox.Document and GemBox Software.