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

velocity&java 完美解决word下载

2012-08-30 18:36 190 查看
开发步骤:

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也测试了,同样可达到效果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐