DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

David has posted 93 posts at DZone. View Full User Profile

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

10.06.2013
| 3877 views |
  • submit to reddit
//[C#]

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);
            conn.Open();
            try
            {
                // Get data from a database.
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM Customers", conn);
                OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                DataTable data = new DataTable();
                da.Fill(data);

                // 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.
                    dstDoc.MailMerge.Execute(row);

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

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)
            conn.Open()
            Try
                ' 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()
                da.Fill(data)

                ' 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.
                    dstDoc.MailMerge.Execute(row)

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

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.