[Export Word] How to use the Java+Freemarker template engine to generate a Word document (template containing only text content) based on an XML template file

This article mainly introduces how to use Java + Freemarker template engine to generate Word documents based on XML template files.

Directory

1. Export Word document

1.1. Basic knowledge

1.2. Make template files

1.3, code implementation

(1) Introduce dependencies

(2) Create a Freemarker tool class

(3) Test case code

(4) Operation effect


1. Export Word document

1.1, basic knowledge

Word files have two suffix formats, namely: doc and docx. doc is used before Word2003, and docx is used after Word2007. It can be said that docx is an extension and optimization of doc. The response speed, performance, and space occupied by docx are better than docx. In addition, docx is essentially a compressed file in zip format. The bottom layer is based on OOXML to organize data. That is to say, the bottom layer of docx is actually a series of files composed of XML. , and then use the program to render the XML file, and finally it is the Word file style we see.

The Word template file I used in this article uses the docx suffix. The core idea is to convert the docx file into the corresponding XML file, and then modify the content in the XML file to change it into a placeholder in the Freemarker template engine. Afterwards, the placeholder is replaced with actual data through the Freemarker rendering program, and the replaced template file is converted into a docx document, so that the Word document is generated according to the template file.

  • Note: The placeholder in freemarker is ${}, for example, if the form of [${name}] is used here, then there needs to be a field called [name] in the transmitted data.

1.2, making template files

First create a Word file with a docx suffix. You can write the content in the file according to your actual needs. The content of the docx file I created is as follows:

After editing the content, save it as an XML file, as shown in the following figure:

After exporting the XML file, open the file, and you will see that there are XML tags in it. Format it first, so that it looks more comfortable. You can check whether your placeholder content meets the freemarker syntax. Because sometimes, in the XML file we export, [${xxx}] may be separated into two lines, which will cause the placeholder to become invalid, so sometimes it is necessary to manually modify the placeholder. The content of the exported Word XML file is roughly as follows:

After the replacement is completed, our Word template file is ready. This XML file is the Word template file we will eventually need, which will be used later.

1.3, code implementation

(1) Import dependencies

If it is a SpringBoot project, SpringBoot has provided us with a freemarker starter, which allows us to quickly integrate freemarker, as follows:

<!-- import freemarker dependency -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

If it is an ordinary Java project, you can introduce the following dependencies:

<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
</dependency>

(2) Create Freemarker tool class

After introducing the freemarker dependency, you can use Freemarker to write a tool class that is specially used to process file export and data rendering.

package com.gitcode.demo.util;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @version 1.0.0
 * @Date: 2023/8/4 15:05
 * @Author ZhuYouBin
 * @Description: Freemarker tool class
 */
public class FreemarkerUtil {

    /**
     * Generate Word files using Freemarker
     * @param templateName template file path name
     * @param fileName generated file path and name
     * @param dataModel filled data object
     */
    public static void exportWord(String templateName, String fileName, Map<String, Object> dataModel) {
        generateFile(templateName, fileName, dataModel);
    }

    /**
     * Use Freemarker to generate specified files
     * @param templateName template file path name
     * @param fileName generated file path and name
     * @param dataModel filled data object
     */
    private static void generateFile(String templateName, String fileName, Map<String, Object> dataModel) {
        try {
            // 1. Create a configuration object
            Configuration config = new Configuration(Configuration.VERSION_2_3_30);
            config.setDefaultEncoding("utf-8");
            config.setClassForTemplateLoading(FreemarkerUtil.class, "/templates");
            // 2. Get the template file
            Template template = config. getTemplate(templateName);
            // 3. Create the generated file object
            File file = new File(fileName);
            FileOutputStream fos = new FileOutputStream(file);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8));
            // 4. Render the template file
            template.process(dataModel, writer);
            // 5. Close the stream
            writer. close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

(3) Test case code

package com.gitcode.demo.word;

import com.gitcode.demo.util.FreemarkerUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0.0
 * @Date: 2023/8/4 15:26
 * @Author ZhuYouBin
 * @Description: Export Word file using Freemarker
 */
public class ExportWordDemo {
    public static void main(String[] args) {
        String templateName = "freemarker template file.xml";
        String fileName = "Exported word document.docx";
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("name", "Zhang San");
        dataModel.put("sex", "male");
        dataModel. put("age", "20");
        dataModel.put("address", "xxx address yyy number");
        // execute the export
        FreemarkerUtil.exportWord(templateName, fileName, dataModel);
    }
}

(4) Running effect

Run the code of the test case, and then in the project directory, you can see the generated Word document, the content is as follows:

The template file above is just a simple text, you can also add tables, pictures and other content to the template file, you can use the cycle tag in Freemarker to automatically add table data, the content of the picture is encoded by base64, so you need to read the picture will be After it is converted into base64 encoding, it is then rendered into an XML file. The following articles will introduce the template export of tables and pictures.

At this point, the introduction of Freemarker exporting Word documents is over.

In summary, this article is over. It mainly introduces how to use Java + Freemarker template engine to generate Word documents based on XML template files.

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Java skill treeHomepageOverview 126451 people are studying systematically