根据ftl模板生成word

本文介绍如何使用Java和Freemarker技术,通过模板文件将数据动态插入到Word文档中,包括创建Word文档、转存为XML并转换为FTL格式,最后实现模板的下载与替换操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先创建word文档,编辑好模板,使用 ${} 作为媒介标识待填入的值
在这里插入图片描述

另存为xml格式
在这里插入图片描述

改为ftl格式
在这里插入图片描述

上传至项目目录下
在这里插入图片描述

 /**
 * 1, 新建一个word文档, 输入模板内容:值用${}代替   比如->  姓名:${name}
 * 2, 将该word文件另存为xml格式(注意是另存为,不是直接改扩展名)
 * 3, 将xml文件的扩展名直接改为ftl模板
 * 4, 用java代码完成导出(需要导入freemarker.jar)
 * 指定ftl文件所在目录路径的方式,注意是
 * 指定ftl文件所在目录的路径,而不是ftl文件的路径
 * @param TemplatePath  ftl模板路径
 * @param dataMap  模板替换值
 */

 @ApiOperation(value="测试获取word")
 @PostMapping(value = "/WordDownload")
 public Result<?> WordDownload() {
     //封装需要替换的值,替换模板${}里面的值
     Map<String,Object> dataMap = new HashMap<>();
     dataMap.put("title", "qwer");
     dataMap.put("id", "123658749");
     dataMap.put("name", "张三");
     dataMap.put("content", "张三qwer001");
     dataMap.put("time", new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
     boolean b = WordUtil.uploadWord(TemplatePath,dataMap,response);
     if (b){
         return Result.ok("操作成功");
     }
     return Result.error("操作失败");
 }

 public static boolean uploadWord(String TemplatePath,Map<String,Object> dataMap,HttpServletResponse response){
    try {
        //Configuration 用于读取ftl文件
        Configuration configuration = new Configuration(new Version("2.3.0"));
        configuration.setDefaultEncoding("utf-8");
        //指定模板文件路径
        //指定路径
        configuration.setDirectoryForTemplateLoading(new File(TemplatePath));
        //configuration.setDirectoryForTemplateLoading(new File("jeecg-boot-module-system"+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"test"));
        //以utf-8的编码读取ftl文件
        response.setContentType("application/msword;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("test"+ System.currentTimeMillis()+".doc","UTF-8"));
        //此句非常关键,不然word文档全是乱码
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        //以utf-8的编码读取ftl文件
        Template template =  configuration.getTemplate("test.ftl","utf-8");
        template.process(dataMap, out);
        out.close();
        return true;
    } catch (Exception e) {
        log.error("导出失败"+e.getMessage());
        return false;
    }
}

使用postman 调用下载测试 结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值