Create and Preform Mail Merge in Word in Java
Tags: java, mailmerge, word
Published: 2021-05-21 05:58:04

---
title: Create and Preform Mail Merge in Word in Java
published: true
description: This article shows you how to create and preform mail merge in Word in Java.
tags: java,mailmerge,word
//cover_image: https://direct_url_to_image.jpg
---
Mail merge is a process of merging data from data source to a Word template document. In this article, I am going to introduce how to create a template document with merge fields, and how to merge text and images into merge fields programmatically using Spire.Doc for Java.

##Installing Spire.Doc.jar

If you create a Maven project, you can easily import the jar in your application using the following configurations. For non-Maven projects, download the jar file from [this link](https://www.e-iceblue.com/Download/doc-for-java.html) and add it as a dependency in your application.
```java
<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</artifactId>
        <version>4.5.1</version>
    </dependency>
</dependencies>
```
##Example 1. Create mail merge fields in Word
Spire.Doc offers the Paragraph.appendField(fieldname, fieldType) method to insert merge fields to a certain paragraph. It’s worth mentioning that the field name of an image merge field should be something like “Image:RealFieldName”.
```java
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.BreakType;
import com.spire.doc.documents.Paragraph;

public class CreateMailMergeFields {

    public static void main(String[] args) {

        //Create a Document object
        Document document = new Document();

        //Add a section
        Section section = document.addSection();

        //Add a paragraph
        Paragraph paragraph = section.addParagraph();

        //Add text and mail merge fields to the paragraph
        paragraph.appendText("Name: ");
        paragraph.appendField("Name", FieldType.Field_Merge_Field);
        paragraph.appendBreak(BreakType.Line_Break);
        paragraph.appendText("Phone: ");
        paragraph.appendField("Phone", FieldType.Field_Merge_Field);
        paragraph.appendBreak(BreakType.Line_Break);
        paragraph.appendText("Date: ");
        paragraph.appendField("Date", FieldType.Field_Merge_Field);
        paragraph.appendBreak(BreakType.Line_Break);
        paragraph.appendText("Portrait: ");
        paragraph.appendField("Image:Portrait", FieldType.Field_Merge_Field);

        //Save the document
        document.saveToFile("Template.docx", FileFormat.Docx_2013);
    }
}
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96w0iekhy5s58hvuh3ie.png)
##Example 2. Mail merge text and images into fields
The following code example shows how to merge text and image values in above Word template using string arrays as data source. You can customize the merging image during mail merge process by using the MergeImageField event.
```java
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 MergeTextAndImages {

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

        //Create a Document instance
        Document document = new Document();

        //Load the template
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");

        //Specify mail merge fields' names
        String[] filedNames = new String[]{"Name", "Phone", "Date", "Portrait"};

        //Specify values for mail merge
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        String imageURL = "C:\\Users\\Administrator\\Desktop\\portrait.jpg";
        String[] filedValues = new String[]{"John Smith", "+1 (69) 123456", dateString,imageURL};

        //Invoke the custom method to load image
        document.getMailMerge().MergeImageField = new MergeImageFieldEventHandler() {
            public void invoke(Object sender, MergeImageFieldEventArgs args) {
                mailMerge_MergeImageField(sender, args);
            }
        };

        //Merge values into fields
        document.getMailMerge().execute(filedNames, filedValues);

        //Save the document to file
        document.saveToFile("MergeValuesToFields.docx", FileFormat.Docx_2013);
    }

    //Create a custom method to set image for image field
    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();
            }
        }
    }
}
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bz0oouv4kjl3xk2ihvz2.png)