Java word模版数据替换与填充

测试word内容

引入依赖

<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.5.0</version>
</dependency>

Java代码

注:word模版中的变量要用双括号{{变量}}

public static void main(String[] args) throws IOException {
        // 模板文件路径
        String registerTemplatePath = "/Users/test.docx";
        // 输出结果文件路径
        String putFileName = "/Users/test01.docx";

        // 替换内容集合
        Map<String, String> textMap = new LinkedHashMap<>();
        textMap.put("name", "张三");
        textMap.put("age", "18");

        // 调用工具类,registerTemplatePath 模板路径,textMap 文字内容
        XWPFTemplate render = XWPFTemplate.compile(registerTemplatePath).render(textMap);
        // 输出文件到磁盘
        render.writeToFile(putFileName);
    }

执行之后的效果