freemarker使用ftl生成word

使用freemarker生成word相对来说是一种比较简单的方式,下面来说说使用ftl生成word的方法。

 

代码和ftl存放地址:https://download.csdn.net/download/caileigood/12513200

1、编写需要生成的word模板,如下图

2、将需要替换的内容修改为参数形式,如下图

3、将word另存为xml,格式化,并将错乱的参数修改正确,如下图

修改后的参数,如下图

4、将xml修改为ftl

5、生成代码

public class Test {
    public static void main(String[] args) {

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("title", "关于生成word的步骤介绍");
        List<Map<String, Object>> versionList = new ArrayList<>();
        //这只是一个demo,不必较真
        for (int i = 0; i < 5; i++) {
            Map<String, Object> version = new HashMap<>();
            version.put("author", "作者" + (i + 1));
            version.put("date", "2020-06-0" + (i + 1));
            version.put("version", "v1." + i);
            versionList.add(version);
        }
        dataMap.put("versionList", versionList);
        dataMap.put("firstStep", "完成word模板");
        dataMap.put("secondStep", "将word另存为xml");
        dataMap.put("thirdStep", "打开xml将其格式化,调整删除过程中错乱的参数");
        dataMap.put("fourthStep", "将xml文件后缀修改为ftl");
        dataMap.put("fifthStep", "组织数据");
        dataMap.put("sixthStep", "生成word");


        try {

            Configuration configure = new Configuration();
            configure.setDefaultEncoding("utf-8");

            //加载需要装填的模板
            Template template=null;

            //设置模板装置方法和路径,
            configure.setDirectoryForTemplateLoading(new File("/demo"));


            //设置异常处理器
            configure.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);

            //定义Template对象,注意模板类型名字与downloadType要一致
            template=configure.getTemplate("demo.ftl");

            File outFile=new File("/demo/word模板生成demo.doc");
            Writer out=null;
            //指定编码表需使用转换流,转换流对象要接收一个字节输出流
            out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
            template.process(dataMap, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }


    }

}

6、最后生成的word

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值