[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 the Java+Freemarker template engine to generate Word documents based on XML template files.

Table of contents

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, a field called [name] needs to be included in the transmitted data.

1.2. Make 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) Introduce dependencies

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

<!-- 引入 freemarker 依赖 -->
<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 a 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 工具类
 */
public class FreemarkerUtil {

    /**
     * 使用 Freemarker 生成 Word 文件
     * @param templateName 模板文件路径名称
     * @param fileName 生成的文件路径以及名称
     * @param dataModel 填充的数据对象
     */
    public static void exportWord(String templateName, String fileName, Map<String, Object> dataModel) {
        generateFile(templateName, fileName, dataModel);
    }

    /**
     * 使用 Freemarker 生成指定文件
     * @param templateName 模板文件路径名称
     * @param fileName 生成的文件路径以及名称
     * @param dataModel 填充的数据对象
     */
    private static void generateFile(String templateName, String fileName, Map<String, Object> dataModel) {
        try {
            // 1、创建配置对象
            Configuration config = new Configuration(Configuration.VERSION_2_3_30);
            config.setDefaultEncoding("utf-8");
            config.setClassForTemplateLoading(FreemarkerUtil.class, "/templates");
            // 2、获取模板文件
            Template template = config.getTemplate(templateName);
            // 3、创建生成的文件对象
            File file = new File(fileName);
            FileOutputStream fos = new FileOutputStream(file);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8));
            // 4、渲染模板文件
            template.process(dataModel, writer);
            // 5、关闭流
            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: 使用 Freemarker 导出 Word 文件
 */
public class ExportWordDemo {
    public static void main(String[] args) {
        String templateName = "freemarker模板文件.xml";
        String fileName = "导出的word文档.docx";
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("name", "张三");
        dataModel.put("sex", "男");
        dataModel.put("age", "20");
        dataModel.put("address", "xxx地址yyy号");
        // 执行导出
        FreemarkerUtil.exportWord(templateName, fileName, dataModel);
    }
}

(4) Operation 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 loop 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 the Java+Freemarker template engine to generate Word documents based on XML template files.

Guess you like

Origin blog.csdn.net/qq_39826207/article/details/132125051