FreeMarker实现Word导出

来源:互联网 发布:怎么查淘宝是不是黑号 编辑:程序博客网 时间:2024/06/06 20:02

1、freemarker版本:

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


2、将word模板文件写好:



3、将word文件,另存为 xml文件(我用的是wps)

此时需注意:很有可能这个动作会将 文件中写好的 ${AGE} 解析出错 变成:

 xxxxxxx${xxxxx

xxxAGExxxx

xxx}xxxxxxxxxx……

的样子(文件已经修改,没有截图。。。)

这个时候,你要做的就是 将 中间多余的字符 删除即可,还原 ${AGE}


4、更改xml文件后缀 为:.ftl


5、将模板文件 放入项目中特定位置


6、代码中:我只使用到了Map,来存放数据


7、生成代码:

/** *  生成word文件 * @param dataMap 原始数据 * @param templateName 文件名称 * @param filePath 文件路径 */public static void createWord(Map dataMap,String templateName,String filePath){ Writer out = null;        try {        //创建配置实例         Configuration configuration = new Configuration();        //设置编码            configuration.setDefaultEncoding("UTF-8");            //ftl模板文件统一放至/ftl/createCode            configuration.setClassForTemplateLoading(ExcelUtil.class,"/ftl/createCode/");            //获取模板             Template template = configuration.getTemplate(templateName);            //输出文件            File outFile = new File(filePath);            //如果输出目标文件夹不存在,则创建            if (!outFile.getParentFile().exists()){                outFile.getParentFile().mkdirs();            }            //将模板和数据模型合并生成文件             out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));            //生成文件            template.process(dataMap, out);            //关闭流            out.flush();        } catch (Exception e) {            e.printStackTrace();        }finally {if(out != null ){            try {out.close();} catch (IOException e) {e.printStackTrace();}}}    }

8、再提供 下载的repsonse:

response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment; filename=demo.doc");
ServletOutputStream os = response.getOutputStream();
通过 response的os输出流,将文件写回客户端,实现下载。


9、测试。



另:想实现Word导出时单元格内容换行:加标签 <w:br />




原创粉丝点击