springMVC使用freemarker导出word文档

首先要学会使用freemarker导出word文档后,再放到ssm项目中。

  • 学会使用freemarker导出word文档
    看这个大佬的博客可以学会基本语法

https://www.cnblogs.com/demodashi/p/8458097.html

总的来说分成这几部
(记得引入freemark的jar包,用maven也可以)

<dependency>
            <groupId>org.freemarkergroupId>
            <artifactId>freemarkerartifactId>
            <version>2.3.23version>
dependency>
<dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>4.1.4.RELEASEversion>
dependency>
  1. 准备好模板.doc
  2. 模板.doc 转换为模板.xml
  3. 按照上边博客的步骤修改模板.xml后保存
  4. 模板.xml 转换为模板.ftl
  5. java找到模板.ftl,然后向里面加载数据数据后,产生XXX.doc放在你指定的目录下
  • springMVC使用freemarker
    1.在web层找resources目录
    springMVC使用freemarker导出word文档_第1张图片
    PS:如果没用resources目录,就先新建一个文件夹叫resources,然后右键springMVC使用freemarker导出word文档_第2张图片
    2.在resources中新建word文件夹放置模板.ftl
    在这里插入图片描述
    3.编写controller代码
import org.apache.ibatis.io.Resources;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.util.Map;
/**
 * @ClassName DownLoadPaperController
 * @Author So on
 * @Description 实现生成doc文档提供下载
 */
@Controller
public class DownLoadPaperController {
    @RequestMapping("/makepaper/download")
    public ModelAndView download(HttpServletRequest request,
                               HttpServletResponse response) throws IOException {
        Map<String, Object> dataMap = new HashMap<String, Object>();//要放到word的数据
        dataMap.put("PaperName", "C++试卷");
        dataMap.put("Semester", "2019-2020第二学期");
        dataMap.put("ExaminationClass", "计科162班");
        List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> list11 = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < 5; i++) {
            //题目
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("number", i+1);
            map.put("question",
                    "一元二次方程表示如下:ax^2+bx+c=0。给定一元二次方程的三个系数a、b、c,计算该方程的根。");
            map.put("input", "输入数据只有一组,在一行上输入三个系数a、b、c。(注意:a!=0,并且b^2>4ac,a、b、c都是实数。)");
            map.put("output", "对于用上述三个系数描述的一元二次方程,输出它的两个根,要求结果保留两位小数并显示。");
            map.put("sample_input", "1 3 1");
            map.put("sample_output", "-0.38 -2.62");
            list1.add(map);
        }
        dataMap.put("table1", list1);
        File file = createDoc(request,dataMap);

        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        java.io.BufferedInputStream bis = null;
        java.io.BufferedOutputStream bos = null;
        try {
            long fileLength = file.length();
            response.setContentType("application/msword");
            response.setHeader("Content-disposition", "attachment; filename="
                    + URLEncoder.encode("试卷.doc", "utf-8"));//试卷.doc是文件名
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        return null;
    }

    private File createDoc(HttpServletRequest request,
                           Map<String, Object> dataMap) throws IOException {

        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setDirectoryForTemplateLoading(Resources.getResourceAsFile("/word"));

        Template t=null;
        String name = "paper.doc";//设置新建的文件名
        File file = new File(name);
        try{
            t = configuration.getTemplate("paper.ftl");
            t.setEncoding("utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name),"UTF-8"));
            t.process(dataMap, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return file;
    }
}

你可能感兴趣的:(SSM,freemarker)