Aspose.Words

How-to: Produce Multiple Documents during Mail Merge

You can download the complete source code of the MultipleDocsInMailMerge sample here.

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.

Example MultipleDocsInMailMerge

Produce multiple documents during mail merge.

[Java]

 

package MultipleDocsInMailMerge;

 

import java.io.File;

import java.net.URI;

import java.sql.*;

import java.text.MessageFormat;

import java.util.Hashtable;

 

import com.aspose.words.Document;

 

 

class Program

{

    public static void main(String[] args) throws Exception

    {

        //Sample infrastructure.

        URI exeDir = Program.class.getResource("").toURI();

        String dataDir = new File(exeDir.resolve("../../Data")) + File.separator;

 

        produceMultipleDocuments(dataDir, "TestFile.doc");

    }

 

    public static void produceMultipleDocuments(String dataDir, String srcDoc) throws Exception

    {

        // Open the database connection.

        ResultSet rs = getData(dataDir, "SELECT * FROM Customers");

 

        // Open the template document.

        Document doc = new Document(dataDir + srcDoc);

 

        // A record of how many documents that have been generated so far.

        int counter = 1;

 

        // Loop though all records in the data source.

        while(rs.next())

        {

            // Clone the template instead of loading it from disk (for speed).

            Document dstDoc = (Document)doc.deepClone(true);

 

            // Extract the data from the current row of the ResultSet into a Hashtable.

            Hashtable dataMap = getRowData(rs);

 

            // Execute mail merge.

            dstDoc.getMailMerge().execute(keySetToArray(dataMap), dataMap.values().toArray());

 

            // Save the document.

            dstDoc.save(MessageFormat.format(dataDir + "TestFile Out {0}.doc", counter++));

        }

    }

 

    /**

     * Creates a Hashtable from the name and value of each column in the current row of the ResultSet.

     */

    public static Hashtable getRowData(ResultSet rs) throws Exception

    {

        ResultSetMetaData metaData = rs.getMetaData();

        Hashtable values = new Hashtable();

 

        for(int i = 1; i <= metaData.getColumnCount(); i++)

        {

            values.put(metaData.getColumnName(i), rs.getObject(i));

        }

 

        return values;

    }

 

    /**

     * Utility function that returns the keys of a Hashtable as an array of Strings.

     */

    public static String[] keySetToArray(Hashtable table)

    {

        return (String[])table.keySet().toArray(new String[table.size()]);

    }

 

    /**

     * Utility function that creates a connection to the Database.

     */

    public static ResultSet getData(String dataDir, String query) throws Exception

    {

        // Load a DB driver that is used by the demos

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        // Compose connection string.

        String connectionString = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};" +

                                  "DBQ=" + new File(dataDir, "Customers.mdb") + ";UID=Admin";

        // DSN-less DB connection.

        Connection connection = DriverManager.getConnection(connectionString);

 

        Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

 

        return statement.executeQuery(query);

    }

}