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.
- <repositories>
- <repository>
- <id>com.e-iceblue</id>
- <name>e-iceblue</name>
- <url>http:
- </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.
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){
-
- Document document = new Document();
- Section section = document.addSection();
-
-
- Paragraph paragraph = section.addParagraph();
-
- paragraph.appendField("UserName", FieldType.Field_Merge_Field);
-
-
- 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:
- 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 {
-
- Document document = new 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", "[email protected]", dateString};
- document.getMailMerge().MergeImageField = new MergeImageFieldEventHandler() {
- @Override
- public void invoke(Object sender, MergeImageFieldEventArgs args) {
- mailMerge_MergeImageField(sender, args);
- }
- };
-
- document.getMailMerge().execute(filedNames, filedValues);
-
-
- 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:
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:
XML File
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 {
-
- Document document = new Document();
-
- document.loadFromFile("templateWithRegions.docx");
-
-
- document.getMailMerge().executeWidthRegion("data.xml");
-
-
- document.saveToFile("MailMergeWithRegions.docx", FileFormat.Docx_2013);
- }
- }
The output document:
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:
XML file
- 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 {
-
- Document document = new 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());
-
-
- document.getMailMerge().executeWidthNestedRegion("orders.xml", list);
-
-
- document.saveToFile("nestedMailMerge.docx", FileFormat.Docx_2013);
- }
- }
The output document:
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!