springboot使用freemaker导出word文档

1、Controller

/**
     * 下载协议到word模板
     */
    @GetMapping("/downloadtest")
    public void downloadtest(Test test, HttpServletRequest request, HttpServletResponse response) {
        //数据赋值
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("name", test.getName());

        String templateName = "model.ftl";
        String filePath = "E:\modelfile";
        String fileName = "Test.doc";
        try {
            FreemarkerUtil.createWord(dataMap, templateName, filePath, fileName);//数据和模板合并生成word

            //下载文件
            // 本地资源路径
            String localPath = filePath;
            // 数据库资源地址
            String downloadPath = "E:/modelfile/Test.doc";
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
            FileUtils.writeBytes(downloadPath, response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件下载失败");
        }
    }

    //处理特殊字符 增加换行
    public String handleData(String data) {
        data = data.replaceAll("&", "&amp;")
                .replaceAll("<", "&lt;").replaceAll(">", "&gt;")
                .replaceAll("<LF>", "&lt;LF&gt;<w:p></w:p>");
        return data;
    }

  2、html

 <form  method="GET" action="/system/test/downloadtest">
                                <input  id="name" name="name"  th:value="${data.name}" type="hidden">

                                <input type="submit" value="协议下载" />
                            </form>

  3、创建Freemarker操作类

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

public class FreemarkerUtil {
    /**
     * 生成word文件
     * @param dataMap word中需要展示的动态数据,用map集合来保存
     * @param templateName word模板名称,例如:model.ftl
     * @param filePath 文件生成的目标路径,例如:E:\freemarker
     * @param fileName 生成的文件名称,例如:Test.doc
     */   public static void createWord(Map dataMap, String templateName, String filePath, String fileName) {
        try {
            //创建配置实例
            Configuration configuration = new Configuration();

            //设置编码
            configuration.setDefaultEncoding("utf-8");

            //ftl模板文件
            configuration.setClassForTemplateLoading(FreemarkerUtil.class, "/");

            //获取模板
            Template template = configuration.getTemplate(templateName);

            //输出文件
            File outFile = new File(filePath + File.separator + fileName);

            //如果输出目标文件夹不存在,则创建
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }

            //将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));


            //生成文件
            template.process(dataMap, out);

            //关闭流
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  4、引入pom依赖

<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.22</version>
		</dependency>

  5、下载模板放入 resource下

    创建模板:先创建一个word文档,使用notepad++转换成.xml文件,再直接改后缀改成.ftl格式。

原文地址:https://www.cnblogs.com/webttt/p/11868024.html