easypoi实现ftl转doc文档(循环填充数据)

1.pom文件

```java
<dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
 </dependency>```
 <!-- EasyPoi依赖 -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.1.0</version>
        </dependency>

2.代码实现

@ApiOperation(value = "easypoi导出(模板)ftl转doc")
    @GetMapping("/export3")
    public void export3(HttpServletResponse response) {
        Map<String, Object> res = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            Map<String, Object> map2 = new HashMap<>();
            map2.put("name", "张三" + i);
            map2.put("sex", "男");
            map2.put("age", i + "岁");
            map2.put("address", "西安市");
            list.add(map2);
        }
        // datas必须和flt文件<#list>标签中的名称一样
        res.put("datas", list);

        PrintWriter out = null;
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            configuration.setDirectoryForTemplateLoading(new File("E:\\codeWork\\hmall\\item-service\\src\\main\\resources\\docx")); // 模版文件前缀路径
            String fileName = "测试文档2.doc";
            //以utf-8的编码读取ftl文件
            Template template = configuration.getTemplate("20240828.ftl", "utf-8"); // 模版名称
            response.reset();
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition", "attachment;filename=\"" + new String(fileName.getBytes("GBK"), "iso8859-1") + "\"");
            response.setCharacterEncoding("utf-8");//此句非常关键,不然word文档全是乱码
            out = response.getWriter();
            template.process(res, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                out.close();
            }
        }

    }

在这里插入图片描述

3. 结果

在这里插入图片描述

注意 :

word转xml(ftl)的时候,一定要用xml格式化,不要直接用idea的代码格式化,如果下载的文件有大小,但是打开没东西,则将文件改为xml双击打开,会有具体的报错行数,看缺失的标签的。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值