您的位置:首页 > 编程语言 > Java开发

java导出数据到word(一)

2016-01-25 00:00 225 查看
摘要: 利用freemarker的模板以及标签,把数据渲染到自定义work模板(doc转xml转ftl)上,利用doc和xml的互转。

一、首先再work上定义好模板



二、把定义好的work转成xml



如果出现下图错误,请百度msxml5.0,下载并安装,功能就可以正常使用。



三、打开xml,把对应要编辑的数据改成freemarker标签



四、放入具体代码中

(1)把文件名改为 ftl后缀,并放入对于工程目录下



(2)Java后台代码实现数据填充,并输出

/**
*
* <p>【导出doc文档】</p>
* <p>条件:</p>
* <p>备注:</p>
* <p>例子:</p>
* <p>日志:</p>
*
* @author:zhu  [2016年2月3日 下午5:11:04]
*/
public void outOfDocGeneral() {
Writer out = null;
try {
//获取数据,内容不允许有类似HTML的标签(<p>、<table>),xml转doc会出错,必须文本
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<String, Object> dataMap = new HashMap<String, Object>();
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");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java work doc