velocity&java 完美解决word下载


开发步骤:

1、将定制好的word另存为xml格式,后缀改为.vm

2、在网站上找到 xml format online格式化xml,以便自己查找对应的位置填充velocity代码,

3、将要填充到word的数据变量用velocity'填充,完成后保存到相应的位置,

4、新建项目,导入velocity的包,新建类,主要代码如下:


               VelocityEngine ve = new VelocityEngine();                    //实例化velocity
               String modulePath = "d:/path";
               ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,modulePath );//这句不设置的话会导致 file not found Exception
               ve.setProperty(Velocity.INPUT_ENCODING,"utf-8");              //设置输入输出流的编码格式
               ve.setProperty(Velocity.OUTPUT_ENCODING,"utf-8");
               try {
			ve.init();  	
			Template tem = ve.getTemplate("exportAliExpressModule.vm");   //得到模版内容
			
			VelocityContext context = new VelocityContext();             VelocityContext用来存取数据,相当于一个map类型的容器
			context.put("list", allList);
			
			StringWriter writer = new StringWriter();                     
			tem.merge(context, writer);                                   //velocity填充数据
			
			response.reset();											  //下载实现
	                response.setContentType("application/download");
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Content-disposition", "attachment;filename="+new String("需要的word.doc".getBytes(), "ISO8859-1"));
			
			OutputStream toClient = response.getOutputStream();
			toClient.write(writer.toString().getBytes("utf-8"));         //切记在此设置输出文件的编码格式,在此纠结了两天
			toClient.flush();
			toClient.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		} 

5、测试成功


总结:1、该方案的局限性:根据已有的模版填充数据下载比较方便,不能绘制自定义的word.

            2、模板引擎freemarker也测试了,同样可达到效果


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值