This guide describes how to do mail merge in MS Word with Java. It will provide details to set the IDE, a list of steps, and a sample code demonstrating how to do a mail merge in Word with Java. All the desired data is generated in this code for the execution of the code without any missing resources.
Steps to Create a Mail Merge in Word with Java
- Set the environment to use Aspose.Words for Java to create a mail merge
- Create a Word file template into a Document object using the DocumentBuilder class
- Add all the fields in the template using the insertField() method
- Create the input XML file according to the fields in the template Word file
- Load the Word template file into the Document object
- Call the getMailMerge().execute() method in the Document class to generate an output Word file
- Save the output Word file
The above steps describe how to do a mail merge with Word with Java. You may create a new Word template file with fields in it or load an existing template file into the Document object and read the XML file into the DataSet object. Finally, call the getMailMerge().execute() method by passing the selected table and saving the output after calling this function.
Code to Create Mail Merge in MS Word with Java
import com.aspose.words.*; | |
import com.aspose.words.net.System.Data.DataSet; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
public class Main { | |
public static void main(String[] args) throws Exception { | |
License pdfLicense = new License(); | |
pdfLicense.setLicense("license.lic"); | |
// Create a student report template | |
Document document = createStudentReportTemplate(); | |
document.save("ReportTemplate.docx"); | |
System.out.println("Report Template generated successfully."); | |
// Generate an XML file with sample student data | |
String xmlFileName = generateSampleStudentData(); | |
System.out.println("Sample XML file '" + xmlFileName + "' has been created."); | |
// Perform mail merge using the dataset | |
Document doc = new Document("ReportTemplate.docx"); | |
DataSet studentDataset = readXmlToDataSet(xmlFileName); | |
doc.getMailMerge().execute(studentDataset.getTables().get("Student")); | |
// Save the final report | |
doc.save("FinalReports.docx"); | |
System.out.println("Mail merge completed. Output saved as 'FinalReports.docx'."); | |
} | |
static Document createStudentReportTemplate() throws Exception { | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// Insert student name fields | |
builder.insertField("MERGEFIELD StudentFirstName \\\u002A MERGEFORMAT"); | |
builder.insertField("MERGEFIELD StudentLastName \\\u002A MERGEFORMAT"); | |
builder.writeln(); | |
// Insert academic details | |
builder.insertField("MERGEFIELD Subject \\\u002A MERGEFORMAT"); | |
builder.insertBreak(BreakType.LINE_BREAK); | |
builder.insertField("MERGEFIELD MarksObtained \\\u002A MERGEFORMAT"); | |
builder.insertBreak(BreakType.LINE_BREAK); | |
builder.insertField("MERGEFIELD TotalMarks \\\u002A MERGEFORMAT"); | |
builder.insertBreak(BreakType.LINE_BREAK); | |
builder.insertField("MERGEFIELD Grade \\\u002A MERGEFORMAT"); | |
builder.writeln(); | |
// Insert teacher comments | |
builder.insertField("MERGEFIELD TeacherComments \\\u002A MERGEFORMAT"); | |
builder.insertBreak(BreakType.LINE_BREAK); | |
// Insert principal's name | |
builder.insertField("MERGEFIELD PrincipalName \\\u002A MERGEFORMAT"); | |
builder.writeln(); | |
return doc; | |
} | |
static String generateSampleStudentData() throws IOException { | |
String fileName = "StudentData.xml"; | |
String xmlContent = """ | |
<Students> | |
<Student> | |
<StudentFirstName>Emily</StudentFirstName> | |
<StudentLastName>Johnson</StudentLastName> | |
<Subject>Mathematics</Subject> | |
<MarksObtained>85</MarksObtained> | |
<TotalMarks>100</TotalMarks> | |
<Grade>A</Grade> | |
<TeacherComments>Excellent performance!</TeacherComments> | |
<PrincipalName>Dr. William Carter</PrincipalName> | |
</Student> | |
<Student> | |
<StudentFirstName>Liam</StudentFirstName> | |
<StudentLastName>Smith</StudentLastName> | |
<Subject>Science</Subject> | |
<MarksObtained>78</MarksObtained> | |
<TotalMarks>100</TotalMarks> | |
<Grade>B</Grade> | |
<TeacherComments>Good effort, keep improving.</TeacherComments> | |
<PrincipalName>Dr. William Carter</PrincipalName> | |
</Student> | |
</Students> | |
"""; | |
try (FileWriter writer = new FileWriter(fileName)) { | |
writer.write(xmlContent); | |
} | |
return fileName; | |
} | |
static DataSet readXmlToDataSet(String xmlFileName) throws Exception { | |
DataSet dataSet = new DataSet(); | |
dataSet.readXml(xmlFileName); | |
return dataSet; | |
} | |
} |
This code has executed all the mail merge steps in MS Word with Java. The DocumentBuilder class has a number of methods and properties that can be set to customize the template file for formatting a report. This code will generate a separate page in the output Word file against each record in the table.
This article has taught us how to use mail merge in Word with Java. To set the table style in an existing file, refer to the article on Design tables in Word with Java.