使用Freemarker 导出word 文档

1.首先在world 里面定义好文本,需要动态添加的字段都使用字母表示.

2.把文件保存为 *.ftl 的格式

3.用 Firstobject free XML edito 打开,将你需要动态生成的字段打上标记,${} 这样就可以

4把*.ftl 模板文件引入到自己的项目中去

5. 编写后台代码,实现下载

 

使用前在当前页面注入

private Configuration configuration = null ;
@RequestMapping(value = "downLoadWord", method = RequestMethod.GET)
public void downloadExcel(String constCheckId, HttpServletResponse response) throws IOException, TemplateException {
     ConstCheck     constCheck=constCheckService.getDownLoadNewSById(constCheckId);
    Group groupSG = groupService.findGroupByGroupId(constCheck.getTaskSGGroupId());
    Group groupJL = groupService.findGroupByGroupId(constCheck.getTaskJLGroupId());
    constCheck.setTaskSGGroupName(groupSG.getGroupName());
    constCheck.setTaskJLGroupName(groupJL.getGroupName());
    Map<String, String> constCheckMap = new HashMap<>();
    if(StringUtils.isBlank(constCheck.getTaskName())){
        constCheckMap.put("task","无项目名称");
    }else{
        constCheckMap.put("task",constCheck.getTaskName());
    }

    if(StringUtils.isBlank(constCheck.getCheckResult())){
        constCheckMap.put("check","无监理工作情况");
    }else{
        constCheckMap.put("check",constCheck.getCheckResult());
    }
    if(StringUtils.isBlank(constCheck.getRemark())){
        constCheckMap.put("remark","无备注");
    }else{
        constCheckMap.put("remark",constCheck.getRemark());
    }
    if(StringUtils.isBlank(constCheck.getTaskSGGroupName())){
        constCheckMap.put("SG","无施工单位");
    }else{
        constCheckMap.put("SG",constCheck.getTaskSGGroupName());
    }
    if(StringUtils.isBlank(constCheck.getTaskJLGroupName())){
        constCheckMap.put("JL","无监理单位");
    }else{
        constCheckMap.put("JL",constCheck.getTaskJLGroupName());
    }
    if(StringUtils.isBlank(constCheck.getCheckLocalDesc())){
        constCheckMap.put("desc","无施工地点");
    }else{
        constCheckMap.put("desc",constCheck.getCheckLocalDesc());
    }
    if(StringUtils.isBlank(constCheck.getUserName())){
        constCheckMap.put("user","无相关记录人");
    }else{
        constCheckMap.put("user",constCheck.getUserName());
    }
    configuration = new Configuration();
    configuration.setDefaultEncoding("UTF-8");
    configuration.setClassForTemplateLoading(this.getClass(), "/templates/pages/domain/pro"); // FTL文件所存在的位置
    Template t=null;
    t = configuration.getTemplate("createReport.ftl");  // 读取相应的ftl 文件
    Writer out = null;
    response.setContentType("application/vnd.ms-excel");
    String fileName = constCheck.getTaskName() + ".doc";
    fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
    response.addHeader("Content-Disposition", "attachment;filename="+ fileName);
    out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
    t.process(constCheckMap, out);
    out.close();

}