Home > Code > C# > Execute Mail Merge & Produce Multiple Word Documents in C# & VB.NET

Execute Mail Merge & Produce Multiple Word Documents in C# & VB.NET

by sher azam   on Sep 25, 2013   Category: C#   |  Views: 7835    |  Points: 25   |  Gold 


This technical tip explains how developers can 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.

You can load the template document from a file or stream before each mail merge, but usually, it is faster to load the document only once and then clone it in memory before each mail merge. Please remember that to perform mail merge you should have a proper template document. This template can be either a Microsoft Word Template or a normal Microsoft Word document, but it needs to contain MERGEFIELD fields in the places where you want the data to be inserted. The name of each field shall be the same as the corresponding field in your data source.

Code samples for producing multiple documents during mail merge.

[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


Read more :http://www.aspose.com/.net/word-component.aspx


Post Code  |  Code Snippet Home

User Responses


No response found, be the first to review this code snippet.

Submit feedback about this code snippet

Please sign in to post feedback

Latest Posts