How to Perform a Mail Merge in a Word Document in Java

Introduction 

 
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.
  1. <repositories>  
  2.         <repository>  
  3.             <id>com.e-iceblue</id>  
  4.             <name>e-iceblue</name>  
  5.             <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>  
  6.         </repository>  
  7. </repositories>  
  8. <dependencies>  
  9.     <dependency>  
  10.         <groupId>e-iceblue</groupId>  
  11.         <artifactId>spire.doc.free</artifactId>  
  12.         <version>2.7.3</version>  
  13.     </dependency>  
  14. </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.
How To Perform Mail Merge In Word Document In Java 
 
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:
  1. import com.spire.doc.Document;  
  2. import com.spire.doc.FieldType;  
  3. import com.spire.doc.FileFormat;  
  4. import com.spire.doc.Section;  
  5. import com.spire.doc.documents.Paragraph;  
  6.   
  7. public class CreateMailMergeTemplate {  
  8.     public static void main(String[] args){  
  9.         //create a Document instance and add a section  
  10.         Document document = new Document();  
  11.         Section section = document.addSection();  
  12.   
  13.         //add a paragraph  
  14.         Paragraph paragraph = section.addParagraph();  
  15.         //append a merge field to the paragraph  
  16.         paragraph.appendField("UserName", FieldType.Field_Merge_Field);  
  17.   
  18.         //save the document  
  19.         document.saveToFile("template.docx", FileFormat.Docx_2013);  
  20.     }  
  21. }  

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:
 
How To Perform Mail Merge In Word Document In Java 
  1. import com.spire.doc.Document;  
  2. import com.spire.doc.FileFormat;  
  3. import com.spire.doc.reporting.MergeImageFieldEventArgs;  
  4. import com.spire.doc.reporting.MergeImageFieldEventHandler;  
  5.   
  6. import java.text.SimpleDateFormat;  
  7. import java.util.Date;  
  8.   
  9. public class SimpleMailMerge {  
  10.     public static void main(String[] args) throws Exception {  
  11.         //create a Document instance  
  12.         Document document = new Document();  
  13.         //load the template document  
  14.         document.loadFromFile("template.docx");  
  15.   
  16.         Date currentTime = new Date();  
  17.         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  18.         String dateString = format.format(currentTime);  
  19.         String[] filedNames = new String[]{"img","userName""emailAddress""date"};  
  20.         String[] filedValues = new String[]{"mailMergedImage.png","John Smith""[email protected]", dateString};  
  21.         document.getMailMerge().MergeImageField = new MergeImageFieldEventHandler() {  
  22.             @Override  
  23.             public void invoke(Object sender, MergeImageFieldEventArgs args) {  
  24.                 mailMerge_MergeImageField(sender, args);  
  25.             }  
  26.         };  
  27.         //call execute method to merge image and string values to the document  
  28.         document.getMailMerge().execute(filedNames, filedValues);  
  29.   
  30.         //save the document  
  31.         document.saveToFile("SimpleMailMerge.docx", FileFormat.Docx_2013);  
  32.     }  
  33.     private static void mailMerge_MergeImageField(Object sender, MergeImageFieldEventArgs field) {  
  34.         String filePath = field.getImageFileName();  
  35.         if (filePath != null && !"".equals(filePath)) {  
  36.             try {  
  37.                 field.setImage(filePath);  
  38.             } catch (Exception e) {  
  39.                 e.printStackTrace();  
  40.             }  
  41.         }  
  42.     }  
  43. }  
The output document:
 
How To Perform Mail Merge In Word Document In Java 
 

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:
 
How To Perform Mail Merge In Word Document In Java 
 
XML File
 
How To Perform Mail Merge In Word Document In Java 
 
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.
  1. import com.spire.doc.Document;  
  2. import com.spire.doc.FileFormat;  
  3.   
  4. public class MailMergeWithRegions {  
  5.     public static void main(String[] args) throws Exception {  
  6.         //create a Document instance  
  7.         Document document = new Document();  
  8.         //load the template document  
  9.         document.loadFromFile("templateWithRegions.docx");  
  10.   
  11.         //call executeWidthRegion to mail merge records from xml file  
  12.         document.getMailMerge().executeWidthRegion("data.xml");  
  13.   
  14.         //save the document  
  15.         document.saveToFile("MailMergeWithRegions.docx", FileFormat.Docx_2013);  
  16.     }  
  17. }  
The output document:
 
How To Perform Mail Merge In Word Document In Java 
 

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:
 
How To Perform Mail Merge In Word Document In Java 
 
XML file
 
How To Perform Mail Merge In Word Document In Java 
  1. import com.spire.doc.Document;  
  2. import com.spire.doc.FileFormat;  
  3.   
  4. import java.util.ArrayList;  
  5. import java.util.HashMap;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. public class NestedMailMerge {  
  10.     public static void main(String[] args) throws Exception {  
  11.         //create a Document instance  
  12.         Document document = new Document();  
  13.         //load the template document  
  14.         document.loadFromFile("nestedMailMergeTemplate.docx");  
  15.           
  16.         List list = new ArrayList();  
  17.         Map<String, String> dictionaryEntry = new HashMap<>();  
  18.         dictionaryEntry.put("Customer""");  
  19.         list.add(dictionaryEntry.entrySet().iterator().next());  
  20.         dictionaryEntry = new HashMap<>();  
  21.         dictionaryEntry.put("Order""Customer_Id = %Customer.Customer_Id%");  
  22.         list.add(dictionaryEntry.entrySet().iterator().next());  
  23.   
  24.         //call executeWidthNestedRegion method to execute mail merge with nested region  
  25.         document.getMailMerge().executeWidthNestedRegion("orders.xml", list);  
  26.   
  27.         //save the document  
  28.         document.saveToFile("nestedMailMerge.docx", FileFormat.Docx_2013);  
  29.     }  
  30. }  
The output document:
 
How To Perform Mail Merge In Word Document In Java 
 

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!