Wednesday, 12 May 2021

[Java] create mail merge and merge text value in Word

This article will introduce how to create a mail merge template and then merge the text value using Java codes with the help pf a free API called Free Spire.Doc for Java.

Before running codes, we should add a Jar file in the API to IDEA. You can get it from the link, or refer to it by using the following Maven configurations.

<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>

Using the 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 {
//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[]{"John Smith", "+1 (69) 123456", dateString};

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

//save the document to file
document.saveToFile("output/mailMerge.docx", FileFormat.Docx);
}
}

Output


No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...