C#: Mail Merge in Word Documents

2024-05-08 03:21:00 Written by  Administrator
Rate this item
(0 votes)

Mail Merge is a powerful feature in Microsoft Word that allows you to create multiple documents such as letters, labels, envelopes, and even e-mails from a single template document and a data source. It's particularly useful for tasks like sending personalized correspondence to a large number of recipients without having to write each letter individually.

In this article, you will learn how to perform a mail merge in a Word document using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Understanding the Components of Mail Merge

  • Main Document: This is the template file where you design your letter, label, or other types of documents with placeholders (also known as merge fields) that will be filled in by data from the data source.
  • Data Source: This is the spreadsheet or database containing the information you want to use to populate your main document. It can be an Excel sheet, Access database, CSV file, XML file or even a simple text file.
  • Merge Fields: These are placeholders in the main document that will be replaced with data from the corresponding record in the data source.

Create a Template Word Document

To generate a template Word document with merge fields, it’s recommended that you use Word editors such as Microsoft Word. The visual interface of the Word editor allows you to design a unique layout, formatting, and other elements interactively for your template.

The following screenshot shows the addition of merge fields to a Word document using MS Word. Remember to use the "Image:FieldName" format if you want to merge an image into a merge field.

C#: Mail Merge in Word Documents

If you wish to create a template Word document using C# code, you can follow these steps.

  • Create a Document object.
  • Add a section.
  • Add a paragraph to the section.
  • Add merge fields to the paragraph using Paragraph.AppendField() method.
  • Save the document to a Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace CreateTemplate
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Add a section
            Section section = document.AddSection();

            // Add a paragraph
            Paragraph paragraph = section.AddParagraph();

            // Add text and mail merge fields to the paragraph
            paragraph.AppendText("Full Name: ");
            paragraph.AppendField("Name", FieldType.FieldMergeField);
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendText("Email Address: ");
            paragraph.AppendField("Email", FieldType.FieldMergeField);
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendText("Avatar: ");
            paragraph.AppendField("Image:Avatar", FieldType.FieldMergeField);

            // Save the document
            document.SaveToFile("Template.docx", FileFormat.Docx2019);

            // Dispose resources
            document.Dispose();
        }
    }
}

Simple Mail Merge in a Word Document

Spire.Doc offers the MailMerge.Execute() method to perform the specified mail merge operation in a Word document. This method has 6 overloads allowing users to perform a mail merge from different data sources, such as DataTable, DataView, and string arrays.

The steps to perform a mail merge using data provided in arrays are as follows.

  • Create a Document object.
  • Load a template Word document from a specified file path.
  • Define an array to hold the field names.
  • Define an array to hold the values that will be used to fill the fields
  • Mail merge data into the fields using MailMerge.Execute() method.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Reporting;
using System.Drawing;

namespace MailMergeInDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Load the template Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");

            // Specify field names
            String[] fieldNames = {

                "Name",
                "Email",
                "Avatar"
            };

            // Specify values that'll be used to fill the fields
            String[] fieldValues = {

                "John Smith",
                "john.smith@e-iceblue.com",
                "C:\\Users\\Administrator\\Desktop\\avatar.png"
            };

            // Register an event which occurs when merging the image filed
            document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField);

            // Mail merge data to the document  
            document.MailMerge.Execute(fieldNames, fieldValues);

            // Save the document  
            document.SaveToFile("MailMerge.docx", FileFormat.Docx2019);

            // Dispose resources
            document.Dispose();
        }

        // Fill an image field with a picture
        private static void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs field)
        {
            string filePath = field.FieldValue as string;

            if (!string.IsNullOrEmpty(filePath))
            {
                field.Image = Image.FromFile(filePath);
            }
        }
    }
}

C#: Mail Merge in Word Documents

Mail Merge with a Region

A region refers to a specific area within a document where you want to insert data from your data source. Mail Merge will repeat that region for each record in the data source. Spire.Doc offers the MailMerge.ExecuteWidthRegion() method to execute mail merge with a region.

The steps to perform a mail merge with a region using the data provided by a DataTable are as follows.

  • Create a Document object.
  • Load a template Word document from a specified file path.
  • Create a DataTable object, which will be used as the data source.
  • Execute mail merge with the region using MailMerge.ExecuteWidthRegion() method.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using System.Data;

namespace MailMergeWithGroup
{
    class Program
    {
        static void Main(string[] args)
        {

            // Create a Document object
            Document document = new Document();

            // Load a template Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");

            // Create a datatable, specifying table name
            DataTable table = new DataTable("Employee");

            // Add sample data to table
            table.Columns.Add("Name");
            table.Columns.Add("Address");
            table.Columns.Add("City");
            table.Rows.Add("John Doe", "123 Main St", "New York");
            table.Rows.Add("Jane Smith", "456 Elm St", "Los Angeles");
            table.Rows.Add("Bob Johnson", "789 Oak St", "Chicago");

            // Mail merge within the region
            document.MailMerge.ExecuteWidthRegion(table);

            // Save the document  
            document.SaveToFile("MailMergeWithRegion.docx", FileFormat.Docx2019);

            // Dispose resources
            document.Dispose();
        }
    }
}

C#: Mail Merge in Word Documents

Mail Merge with Nested Regions

Mail merge for nested groups works by replacing merge fields within nested regions with data that is organized in a hierarchical structure. Nested regions allow you to create more complex layouts where the content of one region depends on the data in another region.

The steps to perform a mail merge with nested regions using the data from an XML file are as follows.

  • Create a Document object.
  • Load a template Word document from a specified file path.
  • Read data from an XML file to a DataSet object.
  • Create a List<DictionaryEntry> object to store the merge field information.
  • Create DicitionaryEntry objects and add them to the list, which specify the merge field names and associated expressions.
  • Execute mail merge with the nested regions using MailMerge.ExecuteWidthNestedRegion() method.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using System.Collections;
using System.Data;

namespace MailMergeWithNestedRegions
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Load a template Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");

            // Read data from an XML file to a DataSet object
            DataSet dataSet = new DataSet();
            dataSet.ReadXml("C:\\Users\\Administrator\\Desktop\\Orders.xml");

            // Create a List object to store the merge field information
            List list = new List();

            // Create two DicitionaryEntry objects and add them to the list (each object specifies the merge field name and associated expression)
            DictionaryEntry dictionaryEntry = new DictionaryEntry("Customer", string.Empty);
            list.Add(dictionaryEntry);

            dictionaryEntry = new DictionaryEntry("Order", "Customer_Id = %Customer.Customer_Id%");
            list.Add(dictionaryEntry);

            // Perform the mail merge operation with the nested region
            document.MailMerge.ExecuteWidthNestedRegion(dataSet, list);

            // Save to file
            document.SaveToFile("MailMergeWithNestedRegions.docx", FileFormat.Docx2019);

            // Dispose resources
            document.Dispose();
        }
    }
}

C#: Mail Merge in Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Wednesday, 08 May 2024 03:29