Over a million developers have joined DZone.

How to Produce Multiple Word Documents during Mail Merge in .NET Apps


This tip allows developers to produce multiple word documents during mail merge.  A typical mail merge operation with Aspose.Words fills just one document with data from your data source (e.g. creates an invoice or a letter). To produce multiple documents you need to mail merge multiple times. If you need to produce a separate document for each record in your data source, you need to do the following:

  • Loop through all rows in the data table.
  • Load (or clone) the original document before mail merge.
  • Mail merge with each row and save the document.

using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Reflection;

using Aspose.Words;

namespace MultipleDocsInMailMerge
    class Program
        public static void Main(string[] args)
            //Sample infrastructure.
            string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
            string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath;

            ProduceMultipleDocuments(dataDir, "TestFile.doc");

        public static void ProduceMultipleDocuments(string dataDir, string srcDoc)
            // Open the database connection.
            string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataDir + "Customers.mdb";
            OleDbConnection conn = new OleDbConnection(connString);
                // Get data from a database.
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM Customers", conn);
                OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                DataTable data = new DataTable();

                // Open the template document.
                Document doc = new Document(dataDir + srcDoc);

                int counter = 1;
                // Loop though all records in the data source.
                foreach (DataRow row in data.Rows)
                    // Clone the template instead of loading it from disk (for speed).
                    Document dstDoc = (Document)doc.Clone(true);

                    // Execute mail merge.

                    // Save the document.
                    dstDoc.Save(string.Format(dataDir + "TestFile Out {0}.doc", counter++));
                // Close the database.

Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.IO
Imports System.Reflection

Imports Aspose.Words

Namespace MultipleDocsInMailMerge
    Friend Class Program
        Public Shared Sub Main(ByVal args() As String)
            'Sample infrastructure.
            Dim exeDir As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar
            Dim dataDir As String = New Uri(New Uri(exeDir), "../../Data/").LocalPath

            ProduceMultipleDocuments(dataDir, "TestFile.doc")
        End Sub

        Public Shared Sub ProduceMultipleDocuments(ByVal dataDir As String, ByVal srcDoc As String)
            ' Open the database connection.
            Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dataDir & "Customers.mdb"
            Dim conn As New OleDbConnection(connString)
                ' Get data from a database.
                Dim cmd As New OleDbCommand("SELECT * FROM Customers", conn)
                Dim da As New OleDbDataAdapter(cmd)
                Dim data As New DataTable()

                ' Open the template document.
                Dim doc As New Document(dataDir & srcDoc)

                Dim counter As Integer = 1
                ' Loop though all records in the data source.
                For Each row As DataRow In data.Rows
                    ' Clone the template instead of loading it from disk (for speed).
                    Dim dstDoc As Document = CType(doc.Clone(True), Document)

                    ' Execute mail merge.

                    ' Save the document.
                    dstDoc.Save(String.Format(dataDir & "TestFile Out {0}.doc", counter))
                    counter += 1
                Next row
                ' Close the database.
            End Try
        End Sub
    End Class
End Namespace

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}