java导出数据到word(一)

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

141834_3Z7H_1987856.png

二、把定义好的work转成xml

142002_d6kl_1987856.png

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

144120_tirF_1987856.png

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

142309_rMz2_1987856.png


四、放入具体代码中

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

142520_XRvR_1987856.png

     (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");


转载于:https://my.oschina.net/u/1987856/blog/608926

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值