DEV Community

CodeSharing
CodeSharing

Posted on

Java/ Create Mail Merge and Merge Text Value in Word

Mail merge in Word document a very powerful function for users to write and send personalized letters or e-mails to many different people at the same time. This article will demonstrate how to create a mail merge template and then merge the text value into the template with the help of Free Spire.Doc for Java.

Import Jar Dependency (2 methods)
● Download the Free Spire.Doc for Java and unzip it, then add the Spire.Doc.jar file to your Java application as dependency.

● Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<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>3.9.0</version>
   </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Sample Code

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import java.text.SimpleDateFormat;
import java.util.Date;

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

        String output = "mailMerge.docx";

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

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

        //Add 3 paragraphs to the section
        Paragraph para = section.addParagraph();
        Paragraph para2 = section.addParagraph();
        Paragraph para3 = section.addParagraph();

        //Add mail merge templates to each paragraph
        para.setText("Contact Name: ");
        para.appendField("Contact Name", FieldType.Field_Merge_Field);
        para2.setText("Phone: ");
        para2.appendField("Phone", FieldType.Field_Merge_Field);
        para3.setText("Date: ");
        para3.appendField("Date", FieldType.Field_Merge_Field);

        //Set the value for the mail merge template by the field name
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        String[] filedNames = new String[]{"Contact Name", "Phone", "Date"};
        String[] filedValues = new String[]{"Robert Chan", "+1 (69) 123456", dateString};

        //Merge the specified value into template
        document.getMailMerge().execute(filedNames, filedValues);

        //save the document to file
        document.saveToFile(output, FileFormat.Docx);
    }
}
Enter fullscreen mode Exit fullscreen mode

A snapshot of the result document
mail merge

Top comments (0)