Use Java to generate Word document from XML template

To accomplish this, we first need a template. I already created a template for the purpose of this sample, which resembles a very simple invoice; please download word_template.xml file should you wish to follow along. In this file, you will see that there are many fields enclosed by “##” markers. For example:

<w:t>Invoice Number: ##INVOICENUMBER##</w:t>

The “##” markers signify places where the program will substitute in values we will provide when we call the Java program. The Java program code is below, with the main() method being an example we can run. The example shown by main() sets values for each required key in a hashtable, as well as setting up the location and file name of the template and output XML files. When we wish to run this example, place the template file in C: and let it go! The output file should look like the content of word_output.xml.

import java.util.Hashtable;

 * This code takes in a hashtable containing key fields required to populate
 * values into a Word template (XML) and output a Word document (also XML).
 * Template should contain ##KEY## fields for each hashtable key with same
 * name (without the ##s); the ##KEY## will be replaced by the value.
 * The main() method is written as an example.
 * Modified from code found at
 * @author C. Peter Chen of
 * @date 20080327

public class msWordUtils {
	 * This main() method is used for demonstration purposes only.
	 * @param args
	 * @author C. Peter Chen of
	 * @date 20080327
	public static void main(String[] args) {
		String templatePathFilename = "c:\word_template.xml";
		String outputPathFilename = "c:\word_output.xml";

		Hashtable ht = new Hashtable();
		ht.put("CUSTOMERNAME","Some Company, LLC.");
		generateWordDoc(ht, templatePathFilename, outputPathFilename);
	 * @param ht
	 * @param templatePathFileName
	 * @param outputPathFileName
	 * @author C. Peter Chen of
	 * @date 20080327
	public static void generateWordDoc(Hashtable ht, String templatePathFilename, String outputPathFilename) {	
		try {
			BufferedReader reader = new BufferedReader(new FileReader(templatePathFilename));
			File destination = new File(outputPathFilename);
			BufferedWriter writer = new BufferedWriter(new FileWriter(destination));
			String thisLine;
			int i = 0;
			while ((thisLine = reader.readLine()) != null) {
				for (java.util.Enumeration e = ht.keys(); e.hasMoreElements();) {
					String name = (String) e.nextElement();
					String value = ht.get(name).toString();
					// Use this if we need to XML-encode the string in hashtable value...
					thisLine = thisLine.replaceAll("##" + name.toUpperCase() + "##", XmlEncode(value));
					// ... or this if we do not need to do XML-encode.
					//thisLine= thisLine.replaceAll("##" + name.toUpperCase() + "##", value);
		catch (Exception e) {
			System.out.println("exception!=" + e);

	 * Encodes regular text to XML.
	 * @param text
	 * @return string
	 * @author
	 * @date 20050328
	private static String XmlEncode(String text) {
		int[] charsRequiringEncoding = {38, 60, 62, 34, 61, 39};
		for(int i = 0; i < charsRequiringEncoding.length - 1; i++) {
			text = text.replaceAll(String.valueOf((char)charsRequiringEncoding[i]),"&#"+charsRequiringEncoding[i]+";");
		return text; 

As noted in the JavaDoc, much of the basis for this code came from Much thanks to the unnamed author!

One Reply to “Use Java to generate Word document from XML template”

  1. Hello,
    Good job!!
    But I am facing issue in generating same in Word Doc file . Doc file is getting corrupted after download . Could you please help me

Leave a Reply

Your email address will not be published. Required fields are marked *