freemarker模板动态生成word文档

本文使用例子

  1. 单插表格
  2. list表格
  3. checkbox

环境

  1. SpringBoot:2.1.7.RELEASE
  2. freemarker 2.1.9
  3. IDEA:2020.1.1
  4. WPS:11.1

配置

一、maven添加freemarker模板引擎

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

二、application.yml配置freemarker

  #    设置freemarker
  freemarker:
    allow-request-override: false
    #    开发过程建议关闭缓存
    cache: true
    check-template-location: false
    charset: UTF-8
    content-type: text/html; charset=utf-8
    expose-request-attributes: false
    expose-session-attributes: false
    expose-spring-macro-helpers: false
    request-context-attribute:
    # 默认后缀就是.ftl
    suffix: .ftl
    template-loader-path: classPath:/templates/code/    

正文

一.word文档

1.单插表格
在这里插入图片描述

  1. list表格
    在这里插入图片描述
    3.checkbox
    在这里插入图片描述

二、另存为xml文件

在这里插入图片描述
三、修改文件后缀为 .ftl 并添加到IDEA中,点击Code -> Reformat Code格式化代码。

1.变量有可能会分离,要手动调整,不知道怎么调整的可手动查看ftl文件中其他正确的地方是怎么写的。

  • 变量分离情况

在这里插入图片描述

  • 调整后

在这里插入图片描述
2、单插表格变量

3.循环list表格,在下图 2 的位置加入循环语句,并把${id}改成 ${user.id}
在这里插入图片描述在这里插入图片描述
在这里插入图片描述
4.checkbox,在后端添加一个控制checkbox的key-value,key为check,value为true/false
在这里插入图片描述
在这里插入图片描述
四、Controller代码(一份代码可执行以上3种格式)

    @PostMapping("user/doc")
    @ResponseBody
    @ApiOperation(value="导出用户doc", httpMethod = "POST",produces="application/json",notes = "导出用户doc")
    public String exportDoc(String data) throws  IOException{
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(this.getClass(), "/templates/code");
        Template template = configuration.getTemplate("test.ftl");
        //data为Json格式
        Map<String, String> dataMap = (Map<String, String>)JSON.parse(data);
        File outFile = new File("test.doc");
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
        try {
            template.process(dataMap,out);
            out.flush();
            out.close();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return "导出成功";
    }
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值