Skip to main content
You are viewing help content for pre-release software. This document and the features it describes are subject to change.
All docs
V26.2
  • Perform Mail Merge

    • 13 minutes to read

    Mail merge combines a template document with records from a data source. The Word Processing Document API replaces merge fields in the template with data source values and generates a single document for all records or a separate document for each record. Mail merge allows you to create letters, invoices, labels, and master-detail reports.

    Follow the steps below to merge data into a document:

    1. Create or load a template document that contains MERGEFIELD fields.
    2. Create a MailMergeOptions object and assign a data source to the MailMergeOptions.DataSource property.
    3. Call a MailMerge method of the template document.

    MailMerge methods do not modify the template document.

    Create a Template

    A template is a document that contains MERGEFIELD fields. The MERGEFIELD FieldName field code specifies the name of a data field (for example, a property name of a list item or a column name of a data table). For each record, the API replaces the MERGEFIELD field with a data field value.

    You can load a template that you create in Microsoft Word (the Insert Merge Field command). To add a merge field in code, pass the field code to the Field(code) constructor and add the Field object to the Paragraph.InlineElements collection.

    Refer to the following help topics for additional information:

    Specify a Data Source

    Assign one of the following objects to the MailMergeOptions.DataSource property:

    To merge a range of records, set MailMergeOptions.FirstRecordIndex and MailMergeOptions.LastRecordIndex properties to zero-based indexes of the first and last records.

    Merge Data and Save the Result

    Call one of the following WordDocument methods to merge data:

    Method Result
    MailMerge(options) Returns a new WordDocument object with merged content.
    MailMerge(options, stream, documentFormat) Saves the merged document to a stream in the specified format.
    MailMerge(options, documentFormat) Returns the merged document in the specified format as a byte array.
    MailMerge(options, consumer) Creates a separate document for each record.

    The following code snippet creates a template with Name and City merge fields, merges a list of customers into the template, and saves the letters to a DOCX file:

    using System.Collections.Generic;
    using System.IO;
    using DevExpress.Docs.Word;
    
    var customers = new List<Customer> {
        new Customer { Name = "Maria Anders", City = "Berlin" },
        new Customer { Name = "Thomas Hardy", City = "London" }
    };
    
    // Create a template with merge fields.
    using var template = new WordDocument();
    var greeting = new Paragraph("Dear ");
    greeting.InlineElements.Add(new Field("MERGEFIELD Name"));
    greeting.AddText(",");
    template.Body.Add(greeting);
    var message = new Paragraph("We opened a new store in ");
    message.InlineElements.Add(new Field("MERGEFIELD City"));
    message.AddText(". Visit us and get a 10% discount.");
    template.Body.Add(message);
    
    // Merge data and save the letters.
    var options = new MailMergeOptions {
        DataSource = customers,
        MergeMode = MergeMode.NewSection
    };
    Directory.CreateDirectory("output");
    using var stream = File.Create(Path.Combine("output", "Document.docx"));
    template.MailMerge(options, stream, DocumentFormat.Docx);
    
    public class Customer {
        public string Name { get; set; }
        public string City { get; set; }
    }
    

    Specify How to Separate Records

    The merged document contains a copy of the template content for each record. Use the MailMergeOptions.MergeMode property to specify how the merged document separates records:

    • Set the MergeMode property to NewParagraph to start each record in a new paragraph.
    • Set the MergeMode property to NewSection to start each record in a new section.
    • Set the MergeMode property to JoinTables to merge records into rows of a single table if the template contains a table row with merge fields. In other modes, the merged document contains a separate table for each record.

    Merge Fields in Headers and Footers

    If template headers or footers contain merge fields, set the MergeMode property to NewSection and the MailMergeOptions.HeaderFooterLinkToPrevious property to false. The header and footer of each section display values of the corresponding record.

    If the HeaderFooterLinkToPrevious property is true, the API links headers and footers of each section to the previous section. Headers and footers of all sections display values of the first record.

    Create Master-Detail Reports

    A merge region is a template part that the API repeats for each item of a nested collection (detail records). To mark a region, add the following merge fields to the template:

    • MERGEFIELD TableStart:RegionName at the region start.
    • MERGEFIELD TableEnd:RegionName at the region end.

    RegionName is the name of the data field that contains detail records (for example, the Orders property of a Customer object). If the template marks regions with other tags (for example, MERGEFIELD BeginGroup:Orders), set MailMergeOptions.RegionStartTag and MailMergeOptions.RegionEndTag properties to the start and end tags.

    A paragraph cannot contain both the start and end of a region or multiple region markers. To repeat a table row, put the region start field into the first cell of the row and the region end field into the last cell.

    The following code snippet creates a template with a table of orders and merges a list of customers with nested order lists:

    using System.Collections.Generic;
    using System.IO;
    using DevExpress.Docs.Word;
    
    var customers = new List<Customer> {
        new Customer {
            Name = "Maria Anders",
            Orders = new List<Order> {
                new Order { Product = "Chai", Quantity = 10 },
                new Order { Product = "Chang", Quantity = 5 }
            }
        },
        new Customer {
            Name = "Thomas Hardy",
            Orders = new List<Order> {
                new Order { Product = "Tofu", Quantity = 8 }
            }
        }
    };
    
    using var template = new WordDocument();
    var title = new Paragraph("Orders of ");
    title.InlineElements.Add(new Field("MERGEFIELD Name"));
    template.Body.Add(title);
    
    // Create a table with a header row and a detail row.
    var table = new Table(2, 2);
    table.Rows[0].Cells[0].Content.Add(new Paragraph("Product"));
    table.Rows[0].Cells[1].Content.Add(new Paragraph("Quantity"));
    
    // Mark the detail row as the Orders region.
    var product = new Paragraph();
    product.InlineElements.Add(new Field("MERGEFIELD TableStart:Orders"));
    product.InlineElements.Add(new Field("MERGEFIELD Product"));
    table.Rows[1].Cells[0].Content.Add(product);
    var quantity = new Paragraph();
    quantity.InlineElements.Add(new Field("MERGEFIELD Quantity"));
    quantity.InlineElements.Add(new Field("MERGEFIELD TableEnd:Orders"));
    table.Rows[1].Cells[1].Content.Add(quantity);
    template.Body.Add(table);
    
    var options = new MailMergeOptions {
        DataSource = customers,
        MergeMode = MergeMode.NewSection
    };
    using var report = template.MailMerge(options);
    
    Directory.CreateDirectory("output");
    using var stream = File.Create(Path.Combine("output", "Document.docx"));
    report.Save(stream);
    
    public class Customer {
        public string Name { get; set; }
        public List<Order> Orders { get; set; }
    }
    
    public class Order {
        public string Product { get; set; }
        public int Quantity { get; set; }
    }
    

    Create a Separate Document for Each Record

    To create a separate document for each record, implement the IMailMergeDocumentConsumer interface and pass the implementation to the WordDocument.MailMerge(options, consumer) method. The API calls the IMailMergeDocumentConsumer.Consume(recordIndex, document) method for each record. Dispose the document object after you process it.

    The following code snippet merges a list of customers into a template and saves each letter to a separate DOCX file:

    using System.Collections.Generic;
    using System.IO;
    using DevExpress.Docs.Word;
    
    var customers = new List<Customer> {
        new Customer { Name = "Maria Anders" },
        new Customer { Name = "Thomas Hardy" }
    };
    
    using var template = new WordDocument();
    var greeting = new Paragraph("Dear ");
    greeting.InlineElements.Add(new Field("MERGEFIELD Name"));
    greeting.AddText(",");
    template.Body.Add(greeting);
    
    Directory.CreateDirectory("output");
    template.MailMerge(new MailMergeOptions { DataSource = customers }, new LetterWriter());
    
    public class Customer {
        public string Name { get; set; }
    }
    
    class LetterWriter : IMailMergeDocumentConsumer {
        public void Consume(int recordIndex, WordDocument document) {
            using (document) {
                using var stream = File.Create(Path.Combine("output", $"Letter{recordIndex + 1}.docx"));
                document.Save(stream);
            }
        }
    }
    

    Track and Cancel the Merge Process

    Implement the IMailMergeCallback interface and assign the implementation to the MailMergeOptions.Callback property. The API calls the following IMailMergeCallback methods during the merge:

    Method Call Time
    MergeStarted(target) Before the API merges the first record.
    RecordStarted(recordIndex, target, record) Before the API merges a record. The record document contains template content with merge fields.
    RecordFinished(recordIndex, target, record) After the API merges a record and before the API adds the record to the target document. The record document contains merged content.
    MergeFinished(target) After the API merges the last record or after you cancel the merge in the RecordStarted or RecordFinished method.

    To modify merged content of a record, modify the record document in the RecordFinished method. To modify the merged document, modify the target document in the MergeFinished method.

    To cancel the merge, return false from the MergeStarted, RecordStarted, or RecordFinished method. If the RecordFinished method returns false, the merged document does not include the current record.

    The following code snippet prints the index of each merged record to the console, adds a paragraph to the end of the merged document, and saves the document to a DOCX file:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using DevExpress.Docs.Word;
    
    var customers = new List<Customer> {
        new Customer { Name = "Maria Anders" },
        new Customer { Name = "Thomas Hardy" }
    };
    
    using var template = new WordDocument();
    var greeting = new Paragraph("Dear ");
    greeting.InlineElements.Add(new Field("MERGEFIELD Name"));
    greeting.AddText(",");
    template.Body.Add(greeting);
    
    using var merged = template.MailMerge(new MailMergeOptions {
        DataSource = customers,
        Callback = new MergeTracker()
    });
    
    Directory.CreateDirectory("output");
    using var stream = File.Create(Path.Combine("output", "Document.docx"));
    merged.Save(stream);
    
    public class Customer {
        public string Name { get; set; }
    }
    
    class MergeTracker : IMailMergeCallback {
        public bool MergeStarted(WordDocument target) => true;
    
        public bool RecordStarted(int recordIndex, WordDocument target, WordDocument record) => true;
    
        public bool RecordFinished(int recordIndex, WordDocument target, WordDocument record) {
            Console.WriteLine($"Record {recordIndex} is merged.");
            return true;
        }
    
        public void MergeFinished(WordDocument target) {
            target.Body.AddParagraph("Contact us if you have questions about your order.");
        }
    }
    

    Add Data from a Single Record to the Template

    To use data of a single record in the template document without a merge operation, call the WordDocument.UpdateAllFields(options) method. Use the following FieldUpdateOptions properties to specify the data source and the record:

    The UpdateAllFields method updates merge field results in the template document. The template keeps merge fields.

    The following code snippet displays data of the second customer in the template from the first example:

    template.UpdateAllFields(new FieldUpdateOptions {
        DataSource = customers,
        ActiveRecordIndex = 1
    });
    

    Configure Styles and Numbered Lists

    Copy Template Styles
    The merged document contains styles that merged content uses. Set the MailMergeOptions.CopyTemplateStyles property to true to copy all template styles to the merged document.
    Restart List Numbering
    If the template contains a numbered list, list numbering continues through all records. To restart list numbering for each record, set the MailMergeOptions.NumberedListRestart property to a MailMergeNumberingRestart value other than None.

    Handle Merge Errors

    If the API cannot merge the document, MailMerge methods throw a System.Exception with the “Cannot merge the document.” message. The InnerException property contains the original exception (for example, an InvalidOperationException if a paragraph contains both the start and end of a merge region).

    If you pass null as options, a stream, or a consumer, MailMerge methods throw an ArgumentNullException.

    Next Steps