一、首先再work上定义好模板
二、把定义好的work转成xml
如果出现下图错误,请百度msxml5.0,下载并安装,功能就可以正常使用。
三、打开xml,把对应要编辑的数据改成freemarker标签
四、放入具体代码中
(1)把文件名改为 ftl后缀,并放入对于工程目录下
(2)Java后台代码实现数据填充,并输出
/**
*
*
【导出doc文档】
*
条件:
*
备注:
*
例子:
*
日志:
*
* @author:zhu [2016年2月3日 下午5:11:04]
*/
public void outOfDocGeneral() {
Writer out = null;
try {
//获取数据,内容不允许有类似HTML的标签(
、
hdJyList = hdJyService.findAll();
hd = hdService.load(hd.getId());
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
//configuration.setDirectoryForTemplateLoading(new File("/WEB-INF/docTemplate")); //FTL文件所存在的位置
//我的Action在 com.a.b.c包下,所以需要跳到5层目录
configuration.setClassForTemplateLoading(this.getClass(), "../../../../../docTemplate");
Map dataMap = new HashMap();
dataMap.put("title", hd.getHdbt());
dataMap.put("creater", hd.getLrr());
dataMap.put("content", hd.getHdnr());
dataMap.put("createTime", hd.getLrsj());
dataMap.put("hdJyList", hdJyList);
Template temp = configuration.getTemplate("hdJyList.ftl");
//调试时候用,输出到指定文件夹下
//File outFile = new File("D:/outFilessa" + Math.random() * 10000 + ".doc");
//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
//super.getWWResponse()获取的是HttpServletResponse
out = super.getWWResponse().getWriter();// 取得输出流
super.getWWResponse().reset();// 清空输出流
super.getWWResponse().setHeader("Content-disposition", "attachment; filename=proposal.doc");// 设定输出文件头
super.getWWResponse().setContentType("application/vnd.ms-word;charset=UTF-8");// 定义输出类型
temp.process(dataMap, out);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
五、页面
//后缀有个 .doc,页面就不会打开,自动下载关闭页面
window.open (url+"/hdAction!outOfDocGeneral.shtml?file=proposal.doc");