在项目的开发中,会经常用到导出报表的功能,比如导出word或excel等,所以网上能完成这部分功能的组件也很多,POI和pageoffice是其中之二,非常不错,下面是利用POI基于word模板操作的一个小例子方法,方便以后使用。
下载POI的包,有三个(poi-3.0.2-FINAL-20080204.jar, poi-contrib-3.0.2-FINAL-20080204.jar, poi-scratchpad-3.0.2-FINAL-20080204.jar)
1、定义word模版文件:
打开你的模版word,另存为xml格式的。
2、准备读写xml文件的环境,和poi环境
使用dom4j,将dom4j的jar包拷到项目中。将poi相关jar包拷入项目中
public void poiuser(HttpServletResponse response,HttpServletRequest request){
try {
request.setCharacterEncoding("UTF-8");
String path=request.getSession().getServletContext().getRealPath("\\");
String pathfileName=path+"WEB-INF\\jsp\\blog\\workrecord.xml";
//用自定义解析类获得document
ReadWordxml readWordxml=new ReadWordxml();
Document document=readWordxml.analizexml(pathfileName);
ByteArrayInputStream bais = new ByteArrayInputStream(document.asXML().getBytes("utf-8"));
POIFSFileSystem fs = new POIFSFileSystem();
DirectoryEntry directory = fs.getRoot();
DocumentEntry de = directory.createDocument("WordDocument", bais);
//文件输出流
OutputStream fos = response.getOutputStream();
//文件输出相关信息
String outputFileName = null; //输出文件名
outputFileName="工作记录表.doc";
String destFile = path + "word_template\\"; //输出文件地址;
destFile = path + outputFileName; //文件的下载地址
response.setContentType("application/octet-stream");
response.setHeader("name", destFile);
response.setHeader("Content-disposition", "attachment; filename=\""
+ URLEncoder.encode(outputFileName, "UTF-8") + "\"");
fs.writeFilesystem(fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
下面给出,我参考过的网上的帖子,都是很不错的,同时也谢谢这些文章的博主辛苦的发帖:
http://blog.csdn.net/sundenskyqq/article/details/7771537?reload
http://blog.sina.com.cn/s/blog_5a15b7d10101a1mp.html
本文介绍如何使用Java POI库来实现Word文档的导出功能,包括定义Word模板、读写XML文件及最终文档的生成与下载。

3032

被折叠的 条评论
为什么被折叠?



