记录freemarker实现word下载和前端请求

记录freemarker实现word下载和前端请求


适用于固定模板word实现
创建word模板,将word另存为xml文件,把文档内容中的动态数据,换成freemarker的标识,如${name},修改文件后缀为ftl文件,放在模板文件夹下
controller

@PostMapping(value = "/load")
    @ResponseBody
    public void WordLoad(@RequestParam(value = "json") String json, HttpServletResponse response) {
        System.out.println("controller");
        wordService.wirteContent(json,response);

    }

service

 @Override
    public void wirteContent(String json, HttpServletResponse response) {
        try {

            String fileName = "a.doc"; //文件名称
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("qSource", "a");

            new ExportWord("UTF-8").exportDoc(response, fileName, "a.ftl", dataMap);
        } catch (Exception e) {
            e.getMessage();
        }

    }

模板util类

public class ExportWord {
    private static Logger logger = LoggerFactory.getLogger(ExportWord.class);
    private Configuration configuration;
    private String encoding;
    private String exportPath = "D:\\test\\";

    /**
     * 构造函数
     * 配置模板路径
     * @param encoding
     */
    public ExportWord(String encoding) {
        this.encoding = encoding;
        configuration = new Configuration(Configuration.VERSION_2_3_30);
        configuration.setDefaultEncoding(encoding);
        configuration.setClassForTemplateLoading(this.getClass(), "/templates/word");
    }

    /**
     * 获取模板
     * @param name
     * @return
     * @throws Exception
     */
    public Template getTemplate(String name) throws Exception {
        return configuration.getTemplate(name);
    }

    /**
     * 导出word文档到指定目录
     * @param fileName
     * @param tplName
     * @param data
     * @throws Exception
     */
    public void exportDocFile(String fileName, String tplName, Map<String, Object> data) throws Exception {
        logger.debug("导出word到D:\test");
        //如果目录不存在,则创建目录
        File exportDirs = new File(exportPath);
        if (!exportDirs.exists()) {
            exportDirs.mkdirs();
        }
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + fileName), encoding));
        getTemplate(tplName).process(data, writer);
    }

    /**
     * 导出word文档到客户端
     * @param response
     * @param fileName
     * @param tplName
     * @param data
     * @throws Exception
     */
    public void exportDoc(HttpServletResponse response, String fileName, String tplName, Map<String, Object> data) throws Exception {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/msword");
        response.setHeader("Content-Disposition", "attachment; filename=" +  URLEncoder.encode(fileName , "UTF-8"));
        // 把本地文件发送给客户端
        Writer out = response.getWriter();
        Template template = getTemplate(tplName);
        template.process(data, out);
        out.close();
    }
}

前端请求

var form = $("<form>");//定义一个form表单
            form.attr("id", "downloadform");
            form.attr("style", "display:none");
            form.attr("target", "_blank");
            form.attr("method", "post");
            form.attr("action", "http://127.0.0.1:9999/word/load");
            var input1 = $("<input>");
            input1.attr("type", "hidden");
            input1.attr("name", "json");
            input1.attr("value", JSON.stringify(allData));
            form.append(input1);
            $("body").append(form);//将表单放置在web中
            form.submit();//表单提交
            $("#downloadform").remove();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

已秃头的菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值