com.aspose.words

Class MailMerge

  • java.lang.Object
    • com.aspose.words.MailMerge
public class MailMerge 
extends java.lang.Object

Represents the mail merge functionality.

For mail merge operation to work, the document should contain Word MERGEFIELD and optionally NEXT fields. During mail merge operation, merge fields in the document are replaced with values from your data source.

There are two distinct ways to use mail merge: with mail merge regions and without.

The simplest mail merge is without regions and it is very similar to how mail merge works in Word. Use Execute methods to merge information from some data source such as DataTable, DataSet or an array of objects into your document. The MailMerge object processes all records of the data source and copies and appends content of the whole document for each record.

Note that when MailMerge object encounters a NEXT field, it selects next record in the data source and continues merging without copying any content.

Use ExecuteWithRegions methods to merge information into a document with mail merge regions defined. You can use com.aspose.words.net.System.Data.DataTable or com.aspose.words.net.System.Data.DataSet as data sources for this operation.

You need to use mail merge regions if you want to dynamically grow portions inside the document. Without mail merge regions whole document will be repeated for every record of the data source.

Example:

Executes mail merge from data stored in a ResultSet.
Document doc = new Document(getMyDir() + "MailMerge.ExecuteDataTable.doc");

// This example creates a table, but you would normally load table from a database. 
DataTable table = new DataTable("Test");
table.getColumns().add("CustomerName");
table.getColumns().add("Address");
table.getRows().add(new Object[] { "Thomas Hardy", "120 Hanover Sq., London" });
table.getRows().add(new Object[] { "Paolo Accorti", "Via Monte Bianco 34, Torino" });

// Field values from the table are inserted into the mail merge fields found in the document.
doc.getMailMerge().execute(table);

doc.save(getMyDir() + "\\Artifacts\\MailMerge.ExecuteDataTable.doc");
See Also:
Document, Document.MailMerge

Property Getters/Setters Summary
intgetCleanupOptions()
void
           Gets or sets a set of flags that specify what items should be removed during mail merge. The value of the property is MailMergeCleanupOptions integer constant.
IFieldMergingCallbackgetFieldMergingCallback()
void
           Occurs during mail merge when a mail merge field is encountered in the document.
IMailMergeCallbackgetMailMergeCallback()
void
           Allows to handle particular events during mail merge.
MappedDataFieldCollectiongetMappedDataFields()
Returns a collection that represents mapped data fields for the mail merge operation.
booleangetMergeDuplicateRegions()
void
           Gets or sets a value indicating whether all of the document mail merge regions with the name of a data source should be merged while executing of a mail merge with regions against the data source or just the first one.
booleangetMergeWholeDocument()
void
setMergeWholeDocument(booleanvalue)
           Gets or sets a value indicating whether fields in whole document is updated while executing of a mail merge with regions.
booleangetPreserveUnusedTags()
void
setPreserveUnusedTags(booleanvalue)
           Gets or sets a value indicating whether the unused "mustache" tags should be preserved.
java.lang.StringgetRegionEndTag()
void
setRegionEndTag(java.lang.Stringvalue)
           Gets or sets a mail merge region end tag.
java.lang.StringgetRegionStartTag()
void
setRegionStartTag(java.lang.Stringvalue)
           Gets or sets a mail merge region start tag.
booleangetTrimWhitespaces()
void
setTrimWhitespaces(booleanvalue)
           Gets or sets a value indicating whether trailing and leading whitespaces are trimmed from mail merge values.
booleangetUnconditionalMergeFieldsAndRegions()
void
           Gets or sets a value indicating whether merge fields and merge regions are merged regardless of the parent IF field's condition.
booleangetUseNonMergeFields()
void
setUseNonMergeFields(booleanvalue)
           When true, specifies that in addition to MERGEFIELD fields, mail merge is performed into some other types of fields and also into "{{fieldName}}" tags.
booleangetUseWholeParagraphAsRegion()
void
           Gets or sets a value indicating whether whole paragraph with TableStart or TableEnd field or particular range between TableStart and TableEnd fields should be included into mail merge region.
 
Method Summary
voiddeleteFields()
Removes mail merge related fields from the document.
voidexecute(IMailMergeDataSource dataSource)
Performs a mail merge from a custom data source.
voidexecute(com.aspose.words.net.System.Data.DataTable table)
Performs mail merge from a com.aspose.words.net.System.Data.DataTable into the document.
voidexecute(java.lang.String[] fieldNames, java.lang.Object[] values)
Performs a mail merge operation for a single record.
voidexecuteWithRegions(IMailMergeDataSource dataSource)
Performs a mail merge from a custom data source with mail merge regions.
voidexecuteWithRegions(IMailMergeDataSourceRoot dataSourceRoot)
Performs a mail merge from a custom data source with mail merge regions.
voidexecuteWithRegions(com.aspose.words.net.System.Data.DataSet dataSet)
Performs mail merge from a DataSet into a document with mail merge regions.
voidexecuteWithRegions(com.aspose.words.net.System.Data.DataTable dataTable)
Performs mail merge from a DataTable into the document with mail merge regions.
java.lang.String[]getFieldNames()
Returns a collection of mail merge field names available in the document.
java.lang.String[]getFieldNamesForRegion(java.lang.String regionName)
Returns a collection of mail merge field names available in the region.
java.lang.String[]getFieldNamesForRegion(java.lang.String regionName, int regionIndex)
Returns a collection of mail merge field names available in the region.
java.util.ArrayList<MailMergeRegionInfo>getRegionsByName(java.lang.String regionName)
Returns a collection of mail merge regions with the specified name.
MailMergeRegionInfogetRegionsHierarchy()
Returns a full hierarchy of regions (with fields) available in the document.
 

    • Property Getters/Setters Detail

      • getCleanupOptions/setCleanupOptions

        public int getCleanupOptions() / public void setCleanupOptions(int value)
        
        Gets or sets a set of flags that specify what items should be removed during mail merge. The value of the property is MailMergeCleanupOptions integer constant.

        Example:

        Shows how to automatically remove unmerged merge fields during mail merge.
        doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_FIELDS);

        Example:

        Shows how to make sure empty paragraphs that result from merging fields with no data are removed from the document.
        doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_EMPTY_PARAGRAPHS);

        Example:

        Shows how to instruct the mail merge engine to remove any containing fields from around a merge field during mail merge.
        doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_CONTAINING_FIELDS);
      • getFieldMergingCallback/setFieldMergingCallback

        public IFieldMergingCallback getFieldMergingCallback() / public void setFieldMergingCallback(IFieldMergingCallback value)
        
        Occurs during mail merge when a mail merge field is encountered in the document.

        Example:

        Shows how to insert images stored in a database BLOB field into a report.
        public void mailMergeImageFromBlob() throws Exception
        {
            Document doc = new Document(getMyDir() + "MailMerge.MergeImage.doc");
        
            // Set up the event handler for image fields.
            doc.getMailMerge().setFieldMergingCallback(new HandleMergeImageFieldFromBlob());
        
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); // Loads the driver
        
            // Open the database connection.
            String connString = "jdbc:ucanaccess://" + getDatabaseDir() + "Northwind.mdb";
        
            // DSN-less DB connection.
            java.sql.Connection conn = java.sql.DriverManager.getConnection(connString, "Admin", "");
        
            // Create and execute a command.
            java.sql.Statement statement = conn.createStatement();
            java.sql.ResultSet resultSet = statement.executeQuery("SELECT * FROM Employees");
        
            DataTable table = new DataTable(resultSet, "Employees");
        
            // Perform mail merge.
            doc.getMailMerge().executeWithRegions(table);
        
            // Close the database.
            conn.close();
        
            doc.save(getMyDir() + "\\Artifacts\\MailMerge.MergeImage.doc");
        }
        
        private class HandleMergeImageFieldFromBlob implements IFieldMergingCallback
        {
            public void fieldMerging(FieldMergingArgs args)
            {
                // Do nothing.
            }
        
            /**
             * This is called when mail merge engine encounters Image:XXX merge field in the document.
             * You have a chance to return an Image object, file name or a stream that contains the image.
             */
            public void imageFieldMerging(ImageFieldMergingArgs e)
            {
                // The field value is a byte array, just cast it and create a stream on it.
                ByteArrayInputStream imageStream = new ByteArrayInputStream((byte[]) e.getFieldValue());
                // Now the mail merge engine will retrieve the image from the stream.
                e.setImageStream(imageStream);
            }
        }

        Example:

        Shows how to mail merge HTML data into a document.
        // File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
        // File 'MailMerge.HtmlData.html' contains some valid HTML data.
        // The same approach can be used when merging HTML data from database.
        
        public void mailMergeInsertHtml() throws Exception
        {
            Document doc = new Document(getMyDir() + "MailMerge.InsertHtml.doc");
        
            // Add a handler for the MergeField event.
            doc.getMailMerge().setFieldMergingCallback(new HandleMergeFieldInsertHtml());
        
            // Load some Html from file.
            StringBuilder htmlText = new StringBuilder();
            BufferedReader reader = new BufferedReader(new FileReader(getMyDir() + "MailMerge.HtmlData.html"));
            String line;
            while ((line = reader.readLine()) != null)
            {
                htmlText.append(line);
                htmlText.append("\r\n");
            }
        
            // Execute mail merge.
            doc.getMailMerge().execute(new String[]{"htmlField1"}, new String[]{htmlText.toString()});
        
            // Save resulting document with a new name.
            doc.save(getMyDir() + "\\Artifacts\\MailMerge.InsertHtml.doc");
        }
        
        private class HandleMergeFieldInsertHtml implements IFieldMergingCallback
        {
            /**
             * This is called when merge field is actually merged with data in the document.
             */
            public void fieldMerging(FieldMergingArgs e) throws Exception
            {
                // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
                if (e.getDocumentFieldName().startsWith("html"))
                {
                    // Insert the text for this merge field as HTML data, using DocumentBuilder.
                    DocumentBuilder builder = new DocumentBuilder(e.getDocument());
                    builder.moveToMergeField(e.getDocumentFieldName());
                    builder.insertHtml((String) e.getFieldValue());
        
                    // The HTML text itself should not be inserted.
                    // We have already inserted it as an HTML.
                    e.setText("");
                }
            }
        
            public void imageFieldMerging(ImageFieldMergingArgs e)
            {
                // Do nothing.
            }
        }
      • getMailMergeCallback/setMailMergeCallback

        public IMailMergeCallback getMailMergeCallback() / public void setMailMergeCallback(IMailMergeCallback value)
        
        Allows to handle particular events during mail merge.
      • getMappedDataFields

        public MappedDataFieldCollection getMappedDataFields()
        
        Returns a collection that represents mapped data fields for the mail merge operation.

        Mapped data fields allow to automatically map between names of fields in your data source and names of mail merge fields in the document.

        Example:

        Shows how to add a mapping when a merge field in a document and a data field in a data source have different names.
        doc.getMailMerge().getMappedDataFields().add("MyFieldName_InDocument", "MyFieldName_InDataSource");
      • getMergeDuplicateRegions/setMergeDuplicateRegions

        public boolean getMergeDuplicateRegions() / public void setMergeDuplicateRegions(boolean value)
        
        Gets or sets a value indicating whether all of the document mail merge regions with the name of a data source should be merged while executing of a mail merge with regions against the data source or just the first one. The default value is false.
      • getMergeWholeDocument/setMergeWholeDocument

        public boolean getMergeWholeDocument() / public void setMergeWholeDocument(boolean value)
        
        Gets or sets a value indicating whether fields in whole document is updated while executing of a mail merge with regions. The default value is false.
      • getPreserveUnusedTags/setPreserveUnusedTags

        public boolean getPreserveUnusedTags() / public void setPreserveUnusedTags(boolean value)
        
        Gets or sets a value indicating whether the unused "mustache" tags should be preserved. The default value is false.
        See Also:
        UseNonMergeFields
      • getRegionEndTag/setRegionEndTag

        public java.lang.String getRegionEndTag() / public void setRegionEndTag(java.lang.String value)
        
        Gets or sets a mail merge region end tag.
      • getRegionStartTag/setRegionStartTag

        public java.lang.String getRegionStartTag() / public void setRegionStartTag(java.lang.String value)
        
        Gets or sets a mail merge region start tag.
      • getTrimWhitespaces/setTrimWhitespaces

        public boolean getTrimWhitespaces() / public void setTrimWhitespaces(boolean value)
        
        Gets or sets a value indicating whether trailing and leading whitespaces are trimmed from mail merge values. The default value is true.

        Example:

        Shows how to trimmed whitespaces from mail merge values.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.insertField("MERGEFIELD field", null);
        
        doc.getMailMerge().setTrimWhitespaces(true);
        doc.getMailMerge().execute(new String[]{"field"}, new Object[]{" first line\rsecond line\rthird line "});
        
        Assert.assertEquals(doc.getText(), "first line\rsecond line\rthird line\f");
      • getUnconditionalMergeFieldsAndRegions/setUnconditionalMergeFieldsAndRegions

        public boolean getUnconditionalMergeFieldsAndRegions() / public void setUnconditionalMergeFieldsAndRegions(boolean value)
        
        Gets or sets a value indicating whether merge fields and merge regions are merged regardless of the parent IF field's condition. The default value is false.
      • getUseNonMergeFields/setUseNonMergeFields

        public boolean getUseNonMergeFields() / public void setUseNonMergeFields(boolean value)
        
        When true, specifies that in addition to MERGEFIELD fields, mail merge is performed into some other types of fields and also into "{{fieldName}}" tags.

        Normally, mail merge is only performed into MERGEFIELD fields, but several customers had their reporting built using other fields and had many documents created this way. To simplify migration (and because this approach was independently used by several customers) the ability to mail merge into other fields was introduced.

        When UseNonMergeFields is set to true, Aspose.Words will perform mail merge into the following fields:

        MERGEFIELD FieldName

        MACROBUTTON NOMACRO FieldName

        IF 0 = 0 "{FieldName}" ""

        Also, when UserNonMergeFields is set to true, Aspose.Words will perform mail merge into text tags "{{fieldName}}". These are not fields, but just text tags.

        Example:

        Shows how to perform mail merge into merge fields and into additional fields types.
        doc.getMailMerge().setUseNonMergeFields(true);
      • getUseWholeParagraphAsRegion/setUseWholeParagraphAsRegion

        public boolean getUseWholeParagraphAsRegion() / public void setUseWholeParagraphAsRegion(boolean value)
        
        Gets or sets a value indicating whether whole paragraph with TableStart or TableEnd field or particular range between TableStart and TableEnd fields should be included into mail merge region. The default value is true.
    • Method Detail

      • deleteFields

        public void deleteFields()
                         throws java.lang.Exception
        Removes mail merge related fields from the document.

        This method removes MERGEFIELD and NEXT fields from the document.

        This method could be useful if your mail merge operation does not always need to populate all fields in the document. Use this method to remove all remaining mail merge fields.

        Example:

        Shows how to delete all merge fields from a document without executing mail merge.
        doc.getMailMerge().deleteFields();
      • execute

        public void execute(IMailMergeDataSource dataSource)
                    throws java.lang.Exception
        Performs a mail merge from a custom data source.

        Use this method to fill mail merge fields in the document with values from any data source such as a list or hashtable or objects. You need to write your own class that implements the IMailMergeDataSource interface.

        You can use this method only when FieldOptions.IsBidiTextSupportedOnUpdate is false, that is you do not need Right-To-Left language (such as Arabic or Hebrew) compatibility.

        This method ignores the MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS option.

        Parameters:
        dataSource - An object that implements the custom mail merge data source interface.

        Example:

        Performs mail merge from a custom data source.
        public void mailMergeCustomDataSource() throws Exception
        {
            // Create some data that we will use in the mail merge.
            CustomerList customers = new CustomerList();
            customers.add(new Customer("Thomas Hardy", "120 Hanover Sq., London"));
            customers.add(new Customer("Paolo Accorti", "Via Monte Bianco 34, Torino"));
        
            // Open the template document.
            Document doc = new Document(getMyDir() + "MailMerge.CustomDataSource.doc");
        
            // To be able to mail merge from your own data source, it must be wrapped
            // into an object that implements the IMailMergeDataSource interface.
            CustomerMailMergeDataSource customersDataSource = new CustomerMailMergeDataSource(customers);
        
            // Now you can pass your data source into Aspose.Words.
            doc.getMailMerge().execute(customersDataSource);
        
            doc.save(getMyDir() + "\\Artifacts\\MailMerge.CustomDataSource.doc");
        }
        
        /**
         * An example of a "data entity" class in your application.
         */
        public class Customer
        {
            public Customer(String aFullName, String anAddress)
            {
                mFullName = aFullName;
                mAddress = anAddress;
            }
        
            public String getFullName()
            {
                return mFullName;
            }
        
            public void setFullName(String value)
            {
                mFullName = value;
            }
        
            public String getAddress()
            {
                return mAddress;
            }
        
            public void setAddress(String value)
            {
                mAddress = value;
            }
        
            private String mFullName;
            private String mAddress;
        }
        
        /**
         * An example of a typed collection that contains your "data" objects.
         */
        public class CustomerList extends ArrayList
        {
            public Customer get(int index)
            {
                return (Customer) super.get(index);
            }
        
            public void set(int index, Customer value)
            {
                super.set(index, value);
            }
        }
        
        /**
         * A custom mail merge data source that you implement to allow Aspose.Words
         * to mail merge data from your Customer objects into Microsoft Word documents.
         */
        public class CustomerMailMergeDataSource implements IMailMergeDataSource
        {
            public CustomerMailMergeDataSource(CustomerList customers)
            {
                mCustomers = customers;
        
                // When the data source is initialized, it must be positioned before the first record.
                mRecordIndex = -1;
            }
        
            /**
             * The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
             */
            public String getTableName()
            {
                return "Customer";
            }
        
            /**
             * Aspose.Words calls this method to get a value for every data field.
             */
            public boolean getValue(String fieldName, Ref<Object> fieldValue) throws Exception
            {
                if (fieldName.equals("FullName"))
                {
                    fieldValue.set(mCustomers.get(mRecordIndex).getFullName());
                    return true;
                } else if (fieldName.equals("Address"))
                {
                    fieldValue.set(mCustomers.get(mRecordIndex).getAddress());
                    return true;
                } else
                {
                    // A field with this name was not found,
                    // return false to the Aspose.Words mail merge engine.
                    fieldValue.set(null);
                    return false;
                }
            }
        
            /**
             * A standard implementation for moving to a next record in a collection.
             */
            public boolean moveNext() throws Exception
            {
                if (!isEof()) mRecordIndex++;
        
                return (!isEof());
            }
        
            public IMailMergeDataSource getChildDataSource(String tableName)
            {
                return null;
            }
        
            private boolean isEof()
            {
                return (mRecordIndex >= mCustomers.size());
            }
        
            private final CustomerList mCustomers;
            private int mRecordIndex;
        }
      • execute

        public void execute(com.aspose.words.net.System.Data.DataTable table)
                    throws java.lang.Exception
        Performs mail merge from a com.aspose.words.net.System.Data.DataTable into the document.

        Use this method to fill mail merge fields in the document with values from a DataTable.

        All records from the table are merged into the document.

        You can use NEXT field in the Word document to cause MailMerge object to select next record from the DataTable and continue merging. This can be used when creating documents such as mailing labels.

        When MailMerge object reaches end of the main document and there are still more rows in the DataTable, it copies entire content of the main document and appends it to the end of the destination document using a section break as a separator.

        This method ignores the MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS option.

        Parameters:
        table - Table that contains data to be inserted into mail merge fields. Field names are not case sensitive. If a field name that is not found in the document is encountered, it is ignored.

        Example:

        Executes mail merge from data stored in a ResultSet.
        Document doc = new Document(getMyDir() + "MailMerge.ExecuteDataTable.doc");
        
        // This example creates a table, but you would normally load table from a database. 
        DataTable table = new DataTable("Test");
        table.getColumns().add("CustomerName");
        table.getColumns().add("Address");
        table.getRows().add(new Object[] { "Thomas Hardy", "120 Hanover Sq., London" });
        table.getRows().add(new Object[] { "Paolo Accorti", "Via Monte Bianco 34, Torino" });
        
        // Field values from the table are inserted into the mail merge fields found in the document.
        doc.getMailMerge().execute(table);
        
        doc.save(getMyDir() + "\\Artifacts\\MailMerge.ExecuteDataTable.doc");
      • execute

        public void execute(java.lang.String[] fieldNames, java.lang.Object[] values)
                    throws java.lang.Exception
        Performs a mail merge operation for a single record.

        Use this method to fill mail merge fields in the document with values from an array of objects.

        This method merges data for one record only. The array of field names and the array of values represent the data of a single record.

        This method does not use mail merge regions.

        This method ignores the MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS option.

        Parameters:
        fieldNames - Array of merge field names. Field names are not case sensitive. If a field name that is not found in the document is encountered, it is ignored.
        values - Array of values to be inserted into the merge fields. Number of elements in this array must be the same as the number of elements in fieldNames.

        Example:

        Performs a simple insertion of data into merge fields.
        // Open an existing document.
        Document doc = new Document(getMyDir() + "MailMerge.ExecuteArray.doc");
        
        // Fill the fields in the document with user data.
        doc.getMailMerge().execute(new String[]{"FullName", "Company", "Address", "Address2", "City"}, new Object[]{"James Bond", "MI5 Headquarters", "Milbank", "", "London"});
        
        doc.save(getMyDir() + "\\Artifacts\\MailMerge.ExecuteArray.doc");

        Example:

        Demonstrates how to merge an image from a web address using an Image field.
        Document doc = new Document(getMyDir() + "MailMerge.MergeImageSimple.doc");
        
        // Pass a URL which points to the image to merge into the document.
        doc.getMailMerge().execute(new String[]{"Logo"}, new Object[]{"http://www.aspose.com/images/aspose-logo.gif"});
        
        doc.save(getMyDir() + "\\Artifacts\\MailMerge.MergeImageFromUrl.doc");
      • executeWithRegions

        public void executeWithRegions(IMailMergeDataSource dataSource)
                               throws java.lang.Exception
        Performs a mail merge from a custom data source with mail merge regions.

        Use this method to fill mail merge fields in the document with values from any custom data source such as an XML file or collections of business objects. You need to write your own class that implements the IMailMergeDataSource interface.

        You can use this method only when FieldOptions.IsBidiTextSupportedOnUpdate is false, that is you do not need Right-To-Left language (such as Arabic or Hebrew) compatibility.

        Parameters:
        dataSource - An object that implements the custom mail merge data source interface.
      • executeWithRegions

        public void executeWithRegions(IMailMergeDataSourceRoot dataSourceRoot)
                               throws java.lang.Exception
        Performs a mail merge from a custom data source with mail merge regions.

        Use this method to fill mail merge fields in the document with values from any custom data source such as an XML file or collections of business objects. You need to write your own classes that implement the IMailMergeDataSourceRoot and IMailMergeDataSource interfaces.

        You can use this method only when FieldOptions.IsBidiTextSupportedOnUpdate is false, that is you do not need Right-To-Left language (such as Arabic or Hebrew) compatibility.

        Parameters:
        dataSourceRoot - An object that implements the custom mail merge data source root interface.
      • executeWithRegions

        public void executeWithRegions(com.aspose.words.net.System.Data.DataSet dataSet)
                               throws java.lang.Exception
        Performs mail merge from a DataSet into a document with mail merge regions.

        Use this method to perform mail merge from one or more tables into repeatable mail merge regions in the document. The mail merge regions inside the document will dynamically grow to accommodate records in the corresponding tables.

        The document must have mail merge regions defined with names that refer to the tables in the DataSet.

        To specify a mail merge region in the document you need to insert two mail merge fields to mark beginning and end of the mail merge region.

        All document content that is included inside a mail merge region will be automatically repeated for every record in the DataTable.

        To mark beginning of a mail merge region insert a MERGEFIELD with name TableStart:MyTable, where MyTable corresponds to one of the table names in your DataSet.

        To mark the end of the mail merge region insert another MERGEFIELD with name TableEnd:MyTable.

        To insert a MERGEFIELD in Word use Insert/Field command and select MergeField then type the name of the field.

        The TableStart and TableEnd fields must be inside the same section in your document.

        If used inside a table, TableStart and TableEnd must be inside the same row in the table.

        Mail merge regions in a document should be well formed (there always needs to be a pair of matching TableStart and TableEnd merge fields with the same table name).

        Parameters:
        dataSet - DataSet that contains data to be inserted into mail merge fields.

        Example:

        Executes a mail merge with repeatable regions from an ADO.NET DataSet.
        // Open the document.
        // For a mail merge with repeatable regions, the document should have mail merge regions
        // in the document designated with MERGEFIELD TableStart:MyTableName and TableEnd:MyTableName.
        Document doc = new Document(getMyDir() + "MailMerge.ExecuteWithRegions.doc");
        
        int orderId = 10444;
        
        // Populate tables and add them to the dataset.
        // For a mail merge with repeatable regions, DataTable.TableName should be
        // set to match the name of the region defined in the document.
        DataSet dataSet = new DataSet();
        
        DataTable orderTable = getTestOrder(orderId);
        dataSet.getTables().add(orderTable);
        
        DataTable orderDetailsTable = getTestOrderDetails(orderId, "ProductID");
        dataSet.getTables().add(orderDetailsTable);
        
        // This looks through all mail merge regions inside the document and for each
        // region tries to find a DataTable with a matching name inside the DataSet.
        // If a table is found, its content is merged into the mail merge region in the document.
        doc.getMailMerge().executeWithRegions(dataSet);
        
        doc.save(getMyDir() + "\\Artifacts\\MailMerge.ExecuteWithRegionsDataSet.doc");
      • executeWithRegions

        public void executeWithRegions(com.aspose.words.net.System.Data.DataTable dataTable)
                               throws java.lang.Exception
        Performs mail merge from a DataTable into the document with mail merge regions.

        If there are other mail merge regions defined in the document they are left intact. This allows to perform several mail merge operations.

        Parameters:
        dataTable - Data source for the mail merge operation. The table must have its TableName property set.

        Example:

        Executes a mail merge with repeatable regions.
        public void executeWithRegionsDataTable() throws Exception
        {
            Document doc = new Document(getMyDir() + "MailMerge.ExecuteWithRegions.doc");
        
            int orderId = 10444;
        
            // Perform several mail merge operations populating only part of the document each time.
        
            // Use DataTable as a data source.
            // The table name property should be set to match the name of the region defined in the document.
            DataTable orderTable = getTestOrder(orderId);
            doc.getMailMerge().executeWithRegions(orderTable);
        
            DataTable orderDetailsTable = getTestOrderDetails(orderId, "ExtendedPrice DESC");
            doc.getMailMerge().executeWithRegions(orderDetailsTable);
        
            doc.save(getMyDir() + "\\Artifacts\\MailMerge.ExecuteWithRegionsDataTable.doc");
        }
        
        private static DataTable getTestOrder(int orderId) throws Exception
        {
            java.sql.ResultSet resultSet = executeDataTable(java.text.MessageFormat.format("SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", Integer.toString(orderId)));
        
            return new DataTable(resultSet, "Orders");
        }
        
        private static DataTable getTestOrderDetails(int orderId, String orderBy) throws Exception
        {
            StringBuilder builder = new StringBuilder();
        
            builder.append(java.text.MessageFormat.format("SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0}", Integer.toString(orderId)));
        
            if ((orderBy != null) && (orderBy.length() > 0))
            {
                builder.append(" ORDER BY ");
                builder.append(orderBy);
            }
        
            java.sql.ResultSet resultSet = executeDataTable(builder.toString());
            return new DataTable(resultSet, "OrderDetails");
        }
        
        /**
         * Utility function that creates a connection, command,
         * executes the command and return the result in a DataTable.
         */
        private static java.sql.ResultSet executeDataTable(String commandText) throws Exception
        {
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");// Loads the driver
        
            // Open the database connection.
            String connString = "jdbc:ucanaccess://" + getDatabaseDir() + "Northwind.mdb";
        
            // From Wikipedia: The Sun driver has a known issue with character encoding and Microsoft Access databases.
            // Microsoft Access may use an encoding that is not correctly translated by the driver, leading to the replacement
            // in strings of, for example, accented characters by question marks.
            //
            // In this case I have to set CP1252 for the european characters to come through in the data values.
            java.util.Properties props = new java.util.Properties();
            props.put("charSet", "Cp1252");
            props.put("UID", "Admin");
        
            // DSN-less DB connection.
            java.sql.Connection conn = java.sql.DriverManager.getConnection(connString, props);
        
            // Create and execute a command.
            java.sql.Statement statement = conn.createStatement();
            return statement.executeQuery(commandText);
        }
      • getFieldNames

        public java.lang.String[] getFieldNames()
                              throws java.lang.Exception
        Returns a collection of mail merge field names available in the document.

        Returns full merge field names including optional prefix. Does not eliminate duplicate field names.

        A new string[] array is created on every call.

        Includes "mustache" field names if UseNonMergeFields is true.

        Example:

        Shows how to get names of all merge fields in a document.
        String[] fieldNames = doc.getMailMerge().getFieldNames();
      • getFieldNamesForRegion

        public java.lang.String[] getFieldNamesForRegion(java.lang.String regionName)
                                       throws java.lang.Exception
        Returns a collection of mail merge field names available in the region.

        Returns full merge field names including optional prefix. Does not eliminate duplicate field names.

        If document contains multiple regions with the same name the very first region is processed.

        A new string array is created on every call.

        Parameters:
        regionName - Region name (case-insensitive).
      • getFieldNamesForRegion

        public java.lang.String[] getFieldNamesForRegion(java.lang.String regionName, int regionIndex)
                                       throws java.lang.Exception
        Returns a collection of mail merge field names available in the region.

        Returns full merge field names including optional prefix. Does not eliminate duplicate field names.

        If document contains multiple regions with the same name the Nth region (zero-based) is processed.

        A new string array is created on every call.

        Parameters:
        regionName - Region name (case-insensitive).
        regionIndex - Region index (zero-based).
      • getRegionsByName

        public java.util.ArrayList<MailMergeRegionInfo> getRegionsByName(java.lang.String regionName)
        Returns a collection of mail merge regions with the specified name.
        Parameters:
        regionName - Region name (case-insensitive).
        Returns:
        The list of regions.
      • getRegionsHierarchy

        public MailMergeRegionInfo getRegionsHierarchy()
        Returns a full hierarchy of regions (with fields) available in the document.

        Hierarchy is returned in the form of the MailMergeRegionInfo class.

        Returns:
        Regions' hierarchy.

        Example:

        Shows how to get MailMergeRegionInfo and work with it
        Document doc = new Document(getMyDir() + "MailMerge.TestRegionsHierarchy.doc");
        
        //Returns a full hierarchy of regions (with fields) available in the document.
        MailMergeRegionInfo regionInfo = doc.getMailMerge().getRegionsHierarchy();
        
        //Get top regions in the document
        ArrayList topRegions = regionInfo.getRegions();
        Assert.assertEquals(topRegions.size(), 2);
        Assert.assertEquals(((MailMergeRegionInfo)topRegions.get(0)).getName(), "Region1");
        Assert.assertEquals(((MailMergeRegionInfo)topRegions.get(1)).getName(), "Region2");
        Assert.assertEquals(((MailMergeRegionInfo)topRegions.get(0)).getLevel(), 1);
        Assert.assertEquals(((MailMergeRegionInfo)topRegions.get(1)).getLevel(), 1);
        
        //Get nested region in first top region
        ArrayList nestedRegions = ((MailMergeRegionInfo)topRegions.get(0)).getRegions();
        Assert.assertEquals(nestedRegions.size(), 2);
        Assert.assertEquals(((MailMergeRegionInfo)nestedRegions.get(0)).getName(), "NestedRegion1");
        Assert.assertEquals(((MailMergeRegionInfo)nestedRegions.get(1)).getName(), "NestedRegion2");
        Assert.assertEquals(((MailMergeRegionInfo)nestedRegions.get(0)).getLevel(), 2);
        Assert.assertEquals(((MailMergeRegionInfo)nestedRegions.get(1)).getLevel(), 2);
        
        //Get field list in first top region
        ArrayList fieldList = ((MailMergeRegionInfo)topRegions.get(0)).getFields();
        Assert.assertEquals(fieldList.size(), 4);
        
        FieldMergeField startFieldMergeField = ((MailMergeRegionInfo)nestedRegions.get(0)).getStartField();
        Assert.assertEquals(startFieldMergeField.getFieldName(), "TableStart:NestedRegion1");
        
        FieldMergeField endFieldMergeField = ((MailMergeRegionInfo)nestedRegions.get(0)).getEndField();
        Assert.assertEquals(endFieldMergeField.getFieldName(), "TableEnd:NestedRegion1");