FreeMarker实现Word导出

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 />




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值