采用jxl实现数据库结果集导出到excel文件

采用jxl实现数据库结果集导出到excel文件


关键字:

jxl, excel, servlet

代码:

servlet:

None.gif import  jxl.WorkbookSettings;
None.gif
import  jxl.Workbook;
None.gif
import  jxl.write.WritableWorkbook;
None.gif
import  jxl.write.WritableSheet;
None.gif
import  jxl.write.Label;
None.gif
import  jxl.write.WriteException;
None.gif
import  org.springframework.web.context.WebApplicationContext;
None.gif
import  org.springframework.web.context.support.WebApplicationContextUtils;
None.gif
import  org.springframework.jdbc.core.JdbcTemplate;
None.gif
import  org.springframework.jdbc.core.ResultSetExtractor;
None.gif
import  org.springframework.jdbc.support.JdbcUtils;
None.gif
import  org.springframework.dao.DataAccessException;
None.gif
import  org.apache.commons.logging.Log;
None.gif
import  org.apache.commons.logging.LogFactory;
None.gif
import  org.apache.commons.lang.StringUtils;
None.gif
import  org.apache.commons.lang.ArrayUtils;
None.gif
None.gif
import  javax.servlet.http.HttpServlet;
None.gif
import  javax.servlet.http.HttpServletRequest;
None.gif
import  javax.servlet.http.HttpServletResponse;
None.gif
import  javax.servlet.ServletException;
None.gif
import  javax.servlet.ServletConfig;
None.gif
import  java.util.Locale;
None.gif
import  java.util.HashMap;
None.gif
import  java.util.Map;
None.gif
import  java.io.IOException;
None.gif
import  java.sql.ResultSet;
None.gif
import  java.sql.SQLException;
None.gif
import  java.sql.ResultSetMetaData;
None.gif
ExpandedBlockStart.gifContractedBlock.gif
/** */ /**
InBlock.gif * 
Title:ExcelGenerator servlet
InBlock.gif * 
Description: 采用jxl实现数据库结果集导出到excel文件。
InBlock.gif * 
Copyright: Copyright.com (c) 2003
InBlock.gif * 
Company:
InBlock.gif * History:
InBlock.gif * create
InBlock.gif *
InBlock.gif * 
@author youlq
InBlock.gif * 
@version 1.0
ExpandedBlockEnd.gif 
*/

ExpandedBlockStart.gifContractedBlock.gif
public   class  ExcelGenerator  extends  HttpServlet dot.gif {
InBlock.gif  
//设定每个Sheet的行数
InBlock.gif
  private int pagesize=5000;
InBlock.gif  
private WorkbookSettings workbookSettings=new WorkbookSettings();
InBlock.gif  
//springframework 的 WebApplicationContext
InBlock.gif
  public static WebApplicationContext wac=null;
InBlock.gif  
//springframework 的 jdbc 操作模版类
InBlock.gif
  public static JdbcTemplate jdbcTemplate=null;
InBlock.gif  
protected final Log logger=LogFactory.getLog(getClass());
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif  
/** *//**
InBlock.gif   * 初始化
InBlock.gif   *
InBlock.gif   * 
@param config
InBlock.gif   * 
@throws ServletException
ExpandedSubBlockEnd.gif   
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif  
public void init(ServletConfig config) throws ServletExceptiondot.gif{
InBlock.gif    
super.init(config);
ExpandedSubBlockStart.gifContractedSubBlock.gif    
trydot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif      
if(null!=getInitParameter("pagesize"))dot.gif{
InBlock.gif        pagesize
=Integer.parseInt(getInitParameter("pagesize"));
ExpandedSubBlockEnd.gif      }

InBlock.gif      workbookSettings.setLocale(Locale.getDefault());
InBlock.gif      wac
=WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
InBlock.gif      jdbcTemplate
=(JdbcTemplate)wac.getBean("jdbcTemplate");
ExpandedSubBlockStart.gifContractedSubBlock.gif    }
 catch(Exception e)dot.gif{
InBlock.gif      logger.error(
"ExcelGenerator init() error !"+e, e.getCause());
InBlock.gif      e.printStackTrace();
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockEnd.gif  }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif  
public String getServletInfo()dot.gif{
InBlock.gif    
return "Servlet used to generate excel output";
ExpandedSubBlockEnd.gif  }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif  
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOExceptiondot.gif{
InBlock.gif    generateExcel(request, response);
ExpandedSubBlockEnd.gif  }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif  
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOExceptiondot.gif{
InBlock.gif    generateExcel(request, response);
ExpandedSubBlockEnd.gif  }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif  
/** *//**
InBlock.gif   * in:
InBlock.gif   * field1#Title&field2#Title&field3#Title
InBlock.gif   * out:
InBlock.gif   * {
InBlock.gif   * field1:Title,
InBlock.gif   * field2:Title
InBlock.gif   * field3:Title
InBlock.gif   * }
InBlock.gif   *
InBlock.gif   * 
@param columnTitle
ExpandedSubBlockEnd.gif   
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif  
public static HashMap generateColumnTitleMap(String columnTitle)dot.gif{
InBlock.gif    HashMap map
=new HashMap();
InBlock.gif    String[] level1
=StringUtils.split(columnTitle, "&");
InBlock.gif    
if(ArrayUtils.isEmpty(level1)) return null;
ExpandedSubBlockStart.gifContractedSubBlock.gif    
for(int i=0;i<level1.length;i++)dot.gif{
InBlock.gif      String[] level2
=StringUtils.split(level1[i], "#");
InBlock.gif      
if(ArrayUtils.isEmpty(level2)||level2.length!=2return null;
InBlock.gif      map.put(level2[
0].toLowerCase(), level2[1]);
ExpandedSubBlockEnd.gif    }

InBlock.gif    
return map;
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
public void generateExcel(HttpServletRequest request, HttpServletResponse response)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
throws ServletException, IOExceptiondot.gif{
InBlock.gif    
//todo 只允许本机调用。
InBlock.gif
    request.getRemoteHost();
InBlock.gif    request.getServerName();
InBlock.gif    response.setHeader(
"Content-Disposition""attachment;");
InBlock.gif    response.setContentType(
"application/x-msdownload");
InBlock.gif    String sql
=(String)request.getSession().getAttribute("ExcelGenerator_sql");
InBlock.gif    String columnTitle
=(String)request.getSession().getAttribute("ExcelGenerator_columntitle");
InBlock.gif    Map columnTitleMap
=null;
InBlock.gif
InBlock.gif    
if(StringUtils.isBlank(sql)) throw new ServletException("sql 字符串为空!");
ExpandedSubBlockStart.gifContractedSubBlock.gif    
if(!StringUtils.isBlank(columnTitle))dot.gif{
InBlock.gif      columnTitleMap
=generateColumnTitleMap(columnTitle);
ExpandedSubBlockStart.gifContractedSubBlock.gif      
if(null==columnTitleMap)dot.gif{
InBlock.gif        logger.error(
"generateColumnTitleMap error !columnTitle="+columnTitle);
ExpandedSubBlockEnd.gif      }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
final WritableWorkbook writableWorkbook=Workbook.createWorkbook(response.getOutputStream(), workbookSettings);
InBlock.gif    
if(jdbcTemplate==nullthrow new ServletException("ExcelGenerator 没有初始化成功!jdbcTemplate==null。");
InBlock.gif    
final Map columnTitleMap1=columnTitleMap;
ExpandedSubBlockStart.gifContractedSubBlock.gif    jdbcTemplate.query(sql, 
new ResultSetExtractor()dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif      
public Object extractData(ResultSet rs) throws SQLException, DataAccessExceptiondot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
trydot.gif{
InBlock.gif          
int counter=0;
InBlock.gif          
int page=1;
InBlock.gif          WritableSheet writableSheet
=writableWorkbook.createSheet(""+page+""0);
InBlock.gif          ResultSetMetaData rsmd
=rs.getMetaData();
InBlock.gif          
int columnCount=rsmd.getColumnCount();
InBlock.gif          String[] columnNames
=new String[columnCount];
ExpandedSubBlockStart.gifContractedSubBlock.gif          
for(int i=1;i<=columnCount;i++)dot.gif{
InBlock.gif            columnNames[i
-1]=rsmd.getColumnName(i).toLowerCase();
ExpandedSubBlockStart.gifContractedSubBlock.gif            
if(columnTitleMap1==null)dot.gif{
InBlock.gif              writableSheet.addCell(
new Label(i-1, counter, columnNames[i-1]));
ExpandedSubBlockStart.gifContractedSubBlock.gif            }
 elsedot.gif{
InBlock.gif              writableSheet.addCell(
new Label(i-1, counter, (String)columnTitleMap1.get(columnNames[i-1])));
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif          }

InBlock.gif          counter
=1;
InBlock.gif          Object oValue
=null;
InBlock.gif          String value
=null;
ExpandedSubBlockStart.gifContractedSubBlock.gif          
while(rs.next())dot.gif{
InBlock.gif            
//row
ExpandedSubBlockStart.gifContractedSubBlock.gif
            for(int i=1;i<=columnCount;i++)dot.gif{
InBlock.gif              oValue
=JdbcUtils.getResultSetValue(rs, i);
ExpandedSubBlockStart.gifContractedSubBlock.gif              
if(oValue==null)dot.gif{
InBlock.gif                value
="";
ExpandedSubBlockStart.gifContractedSubBlock.gif              }
 elsedot.gif{
InBlock.gif                value
=oValue.toString();
ExpandedSubBlockEnd.gif              }

InBlock.gif              writableSheet.addCell(
new Label(i-1, counter, value));
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockStart.gifContractedSubBlock.gif            
if(counter++>pagesize)dot.gif{
InBlock.gif              counter
=0;
InBlock.gif              writableSheet
=writableWorkbook.createSheet(""+(++page)+""0);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif          }

ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch(WriteException e)dot.gif{
InBlock.gif          e.printStackTrace();
ExpandedSubBlockEnd.gif        }

InBlock.gif        
return null;
ExpandedSubBlockEnd.gif      }

ExpandedSubBlockEnd.gif    }

InBlock.gif    );
InBlock.gif    writableWorkbook.write();
ExpandedSubBlockStart.gifContractedSubBlock.gif    
trydot.gif{
InBlock.gif      writableWorkbook.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值