How to Perform a Mail Merge in Microsoft Word documents using Java

Mail merge is a very useful functionality in Microsoft Word that lets us quickly and easily generate a batch of documents from specific templates. In this article, I am going to introduce how to perform a mail merge in Microsoft Word documents using Java. This article uses Free Spire.Doc for Java library to achieve mail merge.

Dependencies

First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that.

If you use maven, you need to add the following code to your project’s pom.xml file.

<repositories>  
        <repository>  
            <id>com.e-iceblue</id>  
            <name>e-iceblue</name>  
            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>  
        </repository>  
</repositories>  
<dependencies>  
    <dependency>  
        <groupId>e-iceblue</groupId>  
        <artifactId>spire.doc.free</artifactId>  
        <version>2.7.3</version>  
    </dependency>  
</dependencies>  

For non-maven projects, download Free Spire. Doc for Java pack from this website and add Spire.Doc.jar in the lib folder into your project as a dependency.

Create a Word Document Template

To perform a mail merge, you first need to create a template document with merge fields. This can be easily achieved using Microsoft Word. Here are the steps I followed:

  • Create a Word document and open it.
  • Click where you want to add merge fields.
  • Open the Insert menu, click Quick Parts and in the drop-down list select Field… to open the Field dialog.
  • In the Field names list, select MergeField.
  • In the Field name text box, enter a name for the merge field and press OK.

This is image title

If you would like to merge an image into a merge filed, the merge field name should be like this: Image:FieldName. You can also create a template document with merge fields programmatically using Free Spire.Doc for Java. Here is the code for your reference:

import com.spire.doc.Document;  
import com.spire.doc.FieldType;  
import com.spire.doc.FileFormat;  
import com.spire.doc.Section;  
import com.spire.doc.documents.Paragraph;  
  
public class CreateMailMergeTemplate {  
    public static void main(String[] args){  
        //create a Document instance and add a section  
        Document document = new Document();  
        Section section = document.addSection();  
  
        //add a paragraph  
        Paragraph paragraph = section.addParagraph();  
        //append a merge field to the paragraph  
        paragraph.appendField("UserName", FieldType.Field_Merge_Field);  
  
        //save the document  
        document.saveToFile("template.docx", FileFormat.Docx_2013);  
    }  
}  

Perform Mail Merge

There are two ways to use mail merges: with regions and without regions. The simplest mail merge is without regions. The following examples elaborate on how to perform a mail merge with and without regions.

Simple Mail Merge without Regions

You can perform a simple mail merge without regions in a template document by using the execute method in MailMerge class. The MailMerge class provides two overloads for the execute method to perform a mail merge from different data sources like string arrays and lists. The following example shows how to mail merge from string arrays.

The template document:

This is image title

import com.spire.doc.Document;  
import com.spire.doc.FileFormat;  
import com.spire.doc.reporting.MergeImageFieldEventArgs;  
import com.spire.doc.reporting.MergeImageFieldEventHandler;  
  
import java.text.SimpleDateFormat;  
import java.util.Date;  
  
public class SimpleMailMerge {  
    public static void main(String[] args) throws Exception {  
        //create a Document instance  
        Document document = new Document();  
        //load the template document  
        document.loadFromFile("template.docx");  
  
        Date currentTime = new Date();  
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        String dateString = format.format(currentTime);  
        String[] filedNames = new String[]{"img","userName", "emailAddress", "date"};  
        String[] filedValues = new String[]{"mailMergedImage.png","John Smith", "Contact@happy-coding.com", dateString};  
        document.getMailMerge().MergeImageField = new MergeImageFieldEventHandler() {  
            @Override  
            public void invoke(Object sender, MergeImageFieldEventArgs args) {  
                mailMerge_MergeImageField(sender, args);  
            }  
        };  
        //call execute method to merge image and string values to the document  
        document.getMailMerge().execute(filedNames, filedValues);  
  
        //save the document  
        document.saveToFile("SimpleMailMerge.docx", FileFormat.Docx_2013);  
    }  
    private static void mailMerge_MergeImageField(Object sender, MergeImageFieldEventArgs field) {  
        String filePath = field.getImageFileName();  
        if (filePath != null && !"".equals(filePath)) {  
            try {  
                field.setImage(filePath);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}  

The output document:

This is image title

Mail Merge with Regions

The region that you are going to execute mail merge must be marked by two merge fields with names like TableStart:XXX and TableEnd:XXX or BeginGroup:XXX and EndGroup:XXX. The TableStart and TableEnd regions are used for executing Mail merge within a table, and the BeginGroup and EndGroup regions are used for executing a mail merge within the document body.

The following screenshot shows the template document with a region named Country:

This is image title

XML File

This is image title

The following example shows how to perform a mail merge with a region in the template document by using the executeWidthRegion method in MailMerge class. The executeWidthRegion method accepts a String parameter that specifies the path of an XML file that contains source data to merge. The region duplicates for every record in the XML file.

import com.spire.doc.Document;  
import com.spire.doc.FileFormat;  
  
public class MailMergeWithRegions {  
    public static void main(String[] args) throws Exception {  
        //create a Document instance  
        Document document = new Document();  
        //load the template document  
        document.loadFromFile("templateWithRegions.docx");  
  
        //call executeWidthRegion to mail merge records from xml file  
        document.getMailMerge().executeWidthRegion("data.xml");  
  
        //save the document  
        document.saveToFile("MailMergeWithRegions.docx", FileFormat.Docx_2013);  
    }  
}  

The output document:

This is image title

Mail Merge with Nested Regions

We can use the executeWidthNestedRegion method in the MailMerge class to perform a mail merge with nested regions.

The following template document has an owner region named Customer and a nested region named Order:

This is image title

XML file

This is image title

import com.spire.doc.Document;  
import com.spire.doc.FileFormat;  
  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  
  
public class NestedMailMerge {  
    public static void main(String[] args) throws Exception {  
        //create a Document instance  
        Document document = new Document();  
        //load the template document  
        document.loadFromFile("nestedMailMergeTemplate.docx");  
          
        List list = new ArrayList();  
        Map<String, String> dictionaryEntry = new HashMap<>();  
        dictionaryEntry.put("Customer", "");  
        list.add(dictionaryEntry.entrySet().iterator().next());  
        dictionaryEntry = new HashMap<>();  
        dictionaryEntry.put("Order", "Customer_Id = %Customer.Customer_Id%");  
        list.add(dictionaryEntry.entrySet().iterator().next());  
  
        //call executeWidthNestedRegion method to execute mail merge with nested region  
        document.getMailMerge().executeWidthNestedRegion("orders.xml", list);  
  
        //save the document  
        document.saveToFile("nestedMailMerge.docx", FileFormat.Docx_2013);  
    }  
}  

The output document:

This is image title

Conclusion

I hope you learned how to create a Word template with merge fields and how to perform simple mail merge without regions and with regions in Java using Free Spire.Doc for Java from my article. There are still some useful features that I haven’t mentioned, such as a mail merge with form fields and a mail merge with conditional fields. However, I am ending the article here to keep it within limits. You can give them a try by yourself if you’re interested.

Happy learning!

#java #programming

How to Perform a Mail Merge in Microsoft Word documents using Java
5.75 GEEK