Java使用模板生成Word发给前端下载

之前使用POI组件生成Excel,表格的布局和内容填充都比较简单。Word文档布局更加复杂,字体、排版、字号等等因素不好调整,于是使用模板来生成Word文档,瞬间舒服多了。
1.导入freeMarker包或者建立maven依赖

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

2.新建一个Word文档作为模板,需要动态变量的地方用${xxx}进行替代,例如
在这里插入图片描述
在文档中可以根据自己的需求更改字号,字体等等排版格式。

3.将该文档另存为Word.xml格式,不能直接修改文件后缀
在这里插入图片描述
打开该xml文件,检查动态变量处必须为 ${xxx}格式:
在这里插入图片描述
4.将该xml文件后缀直接改为.ftl,然后把文档放进项目中

后台我使用的ssm框架,前端请求到controller层。为了便捷,我直接在controller层调用util类返回Word文档给前端,大家可以根据自己的需求进行修改。
controller

  @ResponseBody
    @RequestMapping("/exporta")
    public void expota(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String year = request.getParameter("year");
        Map<String,Object> map = new HashMap<>();
        map.put("name","吕小宾");
        //exportMillCertificateWord会根据动态变量Map将Word对应变量替换,然后返回给前端
        toWord.exportMillCertificateWord(request,response,map);
    }

toWord

public class toWord {
    private static Configuration configuration = null;
    //注意这个地方的path是Word文档所在的路径
    private static final String templateFolder = toWord.class.getClassLoader().getResource("../../").getPath() + "word/";
    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try {
            configuration.setDirectoryForTemplateLoading(new File(templateFolder));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private toWord() {
        throw new AssertionError();
    }
    public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map) throws IOException {
        Template freemarkerTemplate = configuration.getTemplate("模板生成Word.ftl");
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            // 调用工具类的createDoc方法生成Word文档
            file = createDoc(map,freemarkerTemplate);
            fin = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件名
            String fileName = "模板生成Word.doc";
            response.setHeader("Content-Disposition", "attachment;filename="                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));             out = response.getOutputStream();
            byte[] buffer = new byte[512];
            // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } finally {
            if(fin != null) {
                fin.close();
            }
            if(out != null) {
                out.close();
            }
            if(file != null) {
                file.delete();
            }
            }
    }
    private static File createDoc(Map<?, ?> dataMap, Template template) {
        String name =  "模板生成Word.doc";
        File f = new File(name);
        Template t = template;
        try {
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }
}

然后前端请求就能得到我们的Word文档啦
在这里插入图片描述
在这里插入图片描述

原创文章 12 获赞 51 访问量 5834

猜你喜欢

转载自blog.csdn.net/weixin_44582716/article/details/105483774