Introduction

Save time and effort by automating the creation of personalized documents such as reports, letters, and invoices with C# Mail Merge powered by Aspose.Words for .NET. This guide explains how to utilize the Aspose.Words Mail Merge Plugin to perform efficient and scalable document generation within your .NET applications—without the need for MS Word or Office Interop. You will learn to integrate C# mail merge for report automation, allowing you to streamline your reporting workflow.


Contents:


What is Mail Merge?

Mail Merge is a methodology for dynamically generating documents by populating templates with data from various sources. With Aspose.Words, you can seamlessly automate tasks such as:

  • Generating letters and invoices with personalized details.
  • Creating bulk reports using data from structured formats like XML, JSON, or databases, enabling dynamic report generation with C# and Aspose.Words.

Data Sources for Mail Merge

Aspose.Words supports diverse data sources:

  • Objects: Populate templates using class instances.
  • XML: Load structured data for dynamic fields.
  • JSON: Easily integrate with modern APIs.
  • CSV: Leverage tabular data for bulk document generation.
  • DataTable/DataSet: Utilize ADO.NET for database integration.

Preparing Template for Mail Merge

The mail merge template is the document containing merge fields that will be populated with data from your specified data source during execution. The template can be in DOC or DOCX format; it does not necessarily require a specific template style. Follow these steps to create a mail merge template:

  1. Open your document or create a new one in MS Word.
  2. Place the cursor where you want to insert a merge field.
  3. From the Insert menu, select the Field option.
  4. From the Field names list, select MergeField.
  5. Specify a name for the merge field in the Field name box and click OK.
  6. Save the document.

The following screenshot illustrates a sample template document.

Mail Merge Template

.NET Mail Merge API - Installation

You can install Aspose.Words for .NET through various methods:

Perform Mail Merge in Word Document using C#

Once your template is ready, execute the mail merge to generate documents. Here are the steps to perform mail merge on your prepared template:

  1. Load the template document using the Document class.
  2. Set required mail merge options, such as Document.MailMerge.TrimWhitespaces.
  3. Execute the mail merge using the Document.MailMerge.Execute() method, passing the data source as a parameter.
  4. Save the generated document using the Document.Save(String) method.

Here is a code sample demonstrating how to automate report generation in C# using an array of values:


Word Document after Mail Merge

Execute Mail Merge in C#

Perform Mail Merge using XML Data Source in C#

XML files are commonly utilized for storing and transferring data. Aspose.Words for .NET also supports XML as a data source for mail merge operations. Simply read the XML into a DataSet object and execute the mail merge. Below is a sample XML file for our use case.

<customers>
    <customer Name="John Ben Jan" ID="1" Domain="History" City="Boston"/>
    <customer Name="Lisa Lane" ID="2" Domain="Chemistry" City="LA"/>
    <customer Name="Dagomir Zits" ID="3" Domain="Heraldry" City="Milwaukee"/>
    <customer Name="Sara Careira Santy" ID="4" Domain="IT" City="Miami"/>
</customers>

The following code sample retrieves data from an XML data source and executes the mail merge using C#.

Below is the mail merge template that will be populated with data from the XML file.

Mail Merge Template for XML

This image represents the first page of the resultant Word document obtained after executing the mail merge.

Execute Mail Merge with XML in C#

Custom Formatting of Merge Fields

Aspose.Words for .NET provides enhanced control over the mail merge process. The MailMerge.FieldMergingCallback property allows you to configure mail merge behavior as each merge field is encountered. Implementing the IFieldMergingCallback.FieldMerging and IFieldMergingCallback.ImageFieldMerging methods enables customization of the mail merge operation.

Below is a code sample demonstrating how to apply custom formatting during the mail merge through the provided example template:

The following implements the HandleMergeFieldAlternatingRows class.

Mail Merge with Regions using C#

In certain instances, you may need to populate and repeat a specific region within the Word document. For such cases, utilize mail merge with regions. To create a region, specify both the start and end of the region; mail merge will then repeat this region for each record in the data source. The template example below contains two regions—Orders and OrderDetails—utilizing the merge fields «TableStart:Orders», «TableEnd:Orders», «TableStart:OrderDetails», and «TableEnd:OrderDetails».

Mail Merge with Regions

Here is a code sample that executes mail merge based on regions for the previously mentioned template.

The following methods illustrate how to read data from a database.

Nested Mail Merge Regions

Frequently, data from the source is structured in relational formats. For example, “Orders” may have a one-to-many relationship with “OrderDetails,” which keeps records of items within an order. In such scenarios, utilize nested mail merge. Below is a sample invoice template that suits this scenario well.

Mail Merge Template with Regions

The following is an XML data source for our nested mail merge example.

<?xml version="1.0" encoding="utf-8"?>
<Orders xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="OrdersSchema.xsd">
    <Order>
        <Number>23</Number>
        <Address>Nelson Street</Address>
        <Suburb>Howick</Suburb>
        <City>Auckland</City>
        <Phonenumber>543 1234</Phonenumber>
        <Date>03/01/2010</Date>
        <Total>14.00</Total>
        <Item>
            <Name>BBQ Chicken Pizza</Name>
            <Price>6.00</Price>
            <Quantity>1</Quantity>
            <ItemTotal>6.00</ItemTotal>
        </Item>
        <Item>
            <Name>1.5 Litre Coke</Name>
            <Price>4.00</Price>
            <Quantity>2</Quantity>
            <ItemTotal>8.00</ItemTotal>
        </Item>
    </Order>
    <Order>
        <Number>10</Number>
        <Address>Parkville Avenue</Address>
        <Suburb>Pakuranga</Suburb>
        <City>Auckland</City>
        <Phonenumber>548 7342</Phonenumber>
        <Date>05/03/2010</Date>
        <Total>6.00</Total>
        <Item>
            <Name>Hawaiian Pizza</Name>
            <Price>4.00</Price>
            <Quantity>1</Quantity>
            <ItemTotal>4.00</ItemTotal>
        </Item>
        <Item>
            <Name>Fries</Name>
            <Price>1.00</Price>
            <Quantity>2</Quantity>
            <ItemTotal>2.00</ItemTotal>
        </Item>
    </Order>
</Orders>

The corresponding OrderSchema.xsd file for this XML is:

<?xml version="1.0" encoding ="utf-8"?>
<xs:schema id="OrdersSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="Orders">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Order">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="Number"/>
                            <xs:element name="Address"/>
                            <xs:element name="Suburb"/>
                            <xs:element name="City"/>
                            <xs:element name="Phonenumber"/>
                            <xs:element name="Date"/>
                            <xs:element name="Total"/>
                            <xs:element name="Item">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="Name"/>
                                        <xs:element name="Price"/>
                                        <xs:element name="Quantity"/>
                                        <xs:element name="ItemTotal"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

The following code sample executes the nested mail merge using C#.

Word Document after Mail Merge

Below is the first page of the resultant Word document obtained after executing the nested mail merge.

Word Document after Mail Merge

Conclusion

Aspose.Words for .NET is a comprehensive mail merge API that provides both standard and extended features suitable for .NET applications. With just a few lines of code, you can develop simple or complex reports from diverse data sources seamlessly. For guidance on the .NET automated report generation best practices, consult the documentation. To begin with Aspose.Words for .NET, explore the available developer’s guides and sample code on GitHub. The Aspose Plugin also offers advanced functionalities for report generation.

Try Aspose.Words for .NET for Free

You can obtain a free temporary license to try Aspose.Words for .NET without limitations. Get your temporary license now.

See Also