GemBox.Document is a .NET component that enables you to read, write, edit, convert, and print document files from your .NET applications using one simple API.

Customize Merge

Mail merging in GemBox.Document is very flexible and customizable.

Following example shows how to customize mail merge operation by handling FieldMerging event and import data in a specific format or as a picture.

For formatting date/time or numeric values you can use even simpler approach by using field formatting switches (\@ for date/ime and \# for numbers) in the input template document.

Screenshot
Customize Merge Screenshot

See the full code below, use Run Example to execute.

Upload your file(Drag files here)

Download a sample file

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using GemBox.Document;
using GemBox.Document.MailMerging;

class Sample
{
    [STAThread]
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        DocumentModel document = DocumentModel.Load("InvoiceForMailMerge.docx");

        int numberOfItems = 10;
        string pathToResources = "Resources";

        document.MailMerge.FieldMerging += (sender, e) =>
        {
            if (e.IsValueFound)
                switch (e.FieldName)
                {
                    case "Date":
                        ((Run)e.Inline).Text = ((DateTime)e.Value).ToString("dddd, MMMM d, yyyy");
                        break;
                    case "Price":
                    case "Total":
                    case "TotalPrice":
                        ((Run)e.Inline).Text = ((double)e.Value).ToString("0.00");
                        break;
                    case "Name":
                        e.Inline = new Picture(e.Document, Path.Combine(pathToResources, "Acme.png"));
                        break;
                }
        };

        // Fill items (amount and prices).
        DataTable dt = new DataTable()
        {
            TableName = "Item"
        };
        dt.Columns.Add("Date", typeof(DateTime));
        dt.Columns.Add("Hours", typeof(double));
        dt.Columns.Add("Price", typeof(double));
        dt.Columns.Add("Total", typeof(double));

        DateTime startDate = DateTime.Now.AddDays(-numberOfItems);
        for (int i = 0; i < numberOfItems; i++)
        {
            // We worked between 6 and 8 hours per day.
            int workHours = i % 3 + 6;
            double totalPrice = workHours * 35;

            dt.Rows.Add(startDate.AddDays(i), workHours, 35, totalPrice);
        }

        document.MailMerge.Execute(dt);

        // Fill invoice number and date.
        int invoiceNumber = 14;
        document.MailMerge.Execute(
            new
            {
                Number = invoiceNumber,
                InvoiceDate = DateTime.Now.ToShortDateString()
            });


        // Fill customer data.
        document.MailMerge.Execute(
            new Dictionary<string, object>()
            { 
                { "Name", "ACME Corp" },
                { "Address" , "240 Old Country Road, Springfield, IL" },
                { "Country" , "USA" },
                { "ContactPerson" , "Joe Smith" }
            });

        // Fill total.
        document.MailMerge.Execute(new { TotalPrice = dt.Rows.Cast<DataRow>().Sum(row => (double)row["Total"]) });

        // Fill notes.
        document.MailMerge.Execute(
            new KeyValuePair<string, object>[]
            {
                new KeyValuePair<string, object>("Notes", "Payment via check.")
            });

        document.Save("Customize Merge.docx");
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Data
Imports System.IO
Imports System.Linq
Imports GemBox.Document
Imports GemBox.Document.MailMerging

Module Samples

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Dim document As DocumentModel = DocumentModel.Load("InvoiceForMailMerge.docx")

        Dim numberOfItems As Integer = 10
        Dim pathToResources As String = "Resources"

        AddHandler document.MailMerge.FieldMerging, _
            Sub(sender, e)
                If e.IsValueFound Then
                    Select Case e.FieldName
                        Case "Date"
                            DirectCast(e.Inline, Run).Text = DirectCast(e.Value, DateTime).ToString("dddd, MMMM d, yyyy")
                            Exit Select
                        Case "Price", "Total", "TotalPrice"
                            DirectCast(e.Inline, Run).Text = CDbl(e.Value).ToString("0.00")
                            Exit Select
                        Case "Name"
                            e.Inline = New Picture(e.Document, Path.Combine(pathToResources, "Acme.png"))
                            Exit Select
                    End Select
                End If
            End Sub

        ' Fill items (amount and prices).
        Dim dt As New DataTable()
        dt.TableName = "Item"
        dt.Columns.Add("Date", GetType(DateTime))
        dt.Columns.Add("Hours", GetType(Double))
        dt.Columns.Add("Price", GetType(Double))
        dt.Columns.Add("Total", GetType(Double))

        Dim startDate As DateTime = DateTime.Now.AddDays(-numberOfItems)
        For i As Integer = 0 To numberOfItems - 1
            ' We worked between 6 and 8 hours per day.
            Dim workHours As Integer = i Mod 3 + 6
            Dim totalPrice As Double = workHours * 35

            dt.Rows.Add(startDate.AddDays(i), workHours, 35, totalPrice)
        Next

        document.MailMerge.Execute(dt)

        ' Fill invoice number and date.
        Dim invoiceNumber As Integer = 14
        document.MailMerge.Execute(New With {
            .Number = invoiceNumber,
            .InvoiceDate = DateTime.Now.ToShortDateString()
        })


        ' Fill customer data.
        document.MailMerge.Execute(New Dictionary(Of String, Object)() From {
            {"Name", "ACME Corp"},
            {"Address", "240 Old Country Road, Springfield, IL"},
            {"Country", "USA"},
            {"ContactPerson", "Joe Smith"}
        })

        ' Fill total.
        document.MailMerge.Execute(New With {
            .TotalPrice = dt.Rows.Cast(Of DataRow)().Sum(Function(row) CDbl(row("Total")))
        })

        ' Fill notes.
        document.MailMerge.Execute(New KeyValuePair(Of String, Object)() {New KeyValuePair(Of String, Object)("Notes", "Payment via check.")})

        document.Save("Customize Merge.docx")

    End Sub

End Module

Check next sample.