美文网首页
5.java word使用freemarker模板替换

5.java word使用freemarker模板替换

作者: _少年不知愁 | 来源:发表于2021-07-10 22:14 被阅读0次

1.模板准备

首先使用word文档配置好,将word文档另存为并以xml格式存储

然后使用idea打开,ctrl+alt+L 格式化下代码,
将带有${}的代码样式去除
这样模板制作成功
image.png

2.代码实现

引入依赖
    <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>

    public static void main(String[] args) {
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding("UTF-8");
        Map<String, Object> dataMap = getData();

        configuration.setClassForTemplateLoading(WordTest.class, "/");

        try {
            //获取模板文件
            Template t = configuration.getTemplate("temp.xml");
            //导出文件
            File outFile = new File("D:/test/outFile" + Math.random() * 10000 + ".docx");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
            //将填充数据填入模板文件并输出到目标文件
            t.process(dataMap, out);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static Map<String, Object> getData() {
        Map<String, Object> dataMap = new HashMap<>(8);
        dataMap.put("tradeConfirmId", "123456");
        dataMap.put("counterPartyName", "今天是个好日子");
        return dataMap;
    }

打开word,发现变量被替换,
ok!!

相关文章

网友评论

      本文标题:5.java word使用freemarker模板替换

      本文链接:https://www.haomeiwen.com/subject/qljhpltx.html