我们用到了JXL的一些知识,关于JXL我懂得也不是很多,但是找到了一篇很不错的文章,我想也该推荐大家去看看。好东西,自然是大家分享。
http://blog.youkuaiyun.com/airskys/archive/2005/03/31/334548.aspx
接下来看看我们的通用程序是怎么写的。其实也没有什么敲门,只是传进去了一个将要从数据库中读出数据的SQL语句,将执行出来的结果写入到 Excel中显示出来而已。
import
jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public void getExcelResult(String sql,OutputStream os) throws SQLException,IOException, WriteException{
// 首先获取结果集
// 这里获取RowSet的方法可以自己写
CachedRowSet crs = this .GetResult(sql);
// 然后将结果集转化为Excel输出
// 初始化工作
WritableWorkbook wwb = null ;
try {
wwb = Workbook.createWorkbook(os);
// 创建工作表
jxl.write.WritableSheet ws = wwb.createSheet( " Sheet1 " , 0 );
// 逐行添加数据
int i = 0 ;
while (crs.next()){
for ( int j = 1 ;j <= crs.getMetaData().getColumnCount();j ++ ){
String s = crs.getString(j);
Label labelC = new Label(j - 1 , i, s);
ws.addCell(labelC);
}
i ++ ;
}
} catch (Exception e) {
logger.error( " export excel error: " + e);
e.printStackTrace();
} finally {
if (wwb != null ){
wwb.write();
wwb.close();
}
}
}
import jxl.write.Label;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public void getExcelResult(String sql,OutputStream os) throws SQLException,IOException, WriteException{
// 首先获取结果集
// 这里获取RowSet的方法可以自己写
CachedRowSet crs = this .GetResult(sql);
// 然后将结果集转化为Excel输出
// 初始化工作
WritableWorkbook wwb = null ;
try {
wwb = Workbook.createWorkbook(os);
// 创建工作表
jxl.write.WritableSheet ws = wwb.createSheet( " Sheet1 " , 0 );
// 逐行添加数据
int i = 0 ;
while (crs.next()){
for ( int j = 1 ;j <= crs.getMetaData().getColumnCount();j ++ ){
String s = crs.getString(j);
Label labelC = new Label(j - 1 , i, s);
ws.addCell(labelC);
}
i ++ ;
}
} catch (Exception e) {
logger.error( " export excel error: " + e);
e.printStackTrace();
} finally {
if (wwb != null ){
wwb.write();
wwb.close();
}
}
}
看到了吧!其实这个方法很简单,就是提供一个查询的SQL语句和一个OutPutStream对象就可以了。
接下来看看我是怎么在JSP页面中调用并且生成文档,然后提示用户是打开还是保存的。
<
body
>
<%
response.reset();
response.setContentType( " application/vnd.ms-excel " );
String sql = request.getParameter( " sql " );
Sqlconn.getExcelResult(sql,response.getOutputStream());
%>
</ body >
<%
response.reset();
response.setContentType( " application/vnd.ms-excel " );
String sql = request.getParameter( " sql " );
Sqlconn.getExcelResult(sql,response.getOutputStream());
%>
</ body >
在前一个页面中提交要查询的SQL语句,在这里得到后,调用getExcelResult()方法创建Excel文件,就在这里一步完成了。可以看到,这里的OutPutStream对象我使用了Response的getOutPutSteam()方法得到了一个OutPutSteam,执行的结果将会对response进行操作。在此之前,已经设定JSP文件的ContentType为application/vnd.ms-excel,即会得到这个response对象操作形成的excel文件。
当然,这样执行出来的结果不是很好看。所以,可以想办法修改生成文档的样式等。关于这方面,上面的地址中有很详细的介绍。非常使用。大家可以根据自己的情况写出各种各样的样式来,真是不错啊。