在web業務中,有時候會需要把查詢結果以excel保存下來。實現的方法有很多,這里以jxl.jar+servlet為例。
假定查詢頁面為cx.jsp
cx.jsp中添加了兩個按鈕,即將分頁查詢的當前頁結果轉存為excel,或將所有頁記錄轉存為excel。
代碼如下:
<!-- 查詢頁面 cx.jsp -->
<html>
<head></head>
<body>
<form>
<table>
……
<tr>
<td><input type="submit" name="excel1" onclick= "pageThis(0)" value="本頁轉Excel保存" class="mybutton"></td>
<td><input type="submit" name="excel2" onclick= "pageThis(1)" value="所有頁轉Excel保存" class="mybutton"></td>
</tr>
<table>
</form>
<script language="JavaScript">
//轉存為excel
function pageThis(key)
{
form1.action="cx_impexcel.jsp?key="+key;
form1.submit();
}
</script>
</body>
</html>
點擊按鈕,調用excel導出頁面 cx_impexcel.jsp
cx_impexcel.jsp中的action.getMethodA(),action.getMethodB()方法即查詢當前頁和所有頁記錄的集合。
調用ActionImpExcel.writeExcel()方法生成excel數據文件到服務器端的指定配置路徑,并通過servlet讀取該文件轉存到客戶端。
代碼如下:
<!-- excel導出頁面 cx_impexcel.jsp -->
<html>
<head>
</head>
<body>
<%
// 配置文件中定義的放置excel的路徑。
String sFilePath = PropertyManager.getProperty("tempfilepath");
// 獲取該項目的絕對路徑
String url=request.getRealPath("/")+"\\"+sFilePath;
String path = request.getContextPath();
// 獲取該項目的相對路徑
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
// 查詢結果集
ArrayList listall =new ArrayList();
// 生成excel數據的結果
boolean rtn=false;
String key = request.getParameter("key");
// 定義將要導出記錄的字段列名,用自定義的分隔符隔開(這里用的是';')
String colName= "columnA;columnB;columnC;columnD;columnE";
// 定義生成的文件名MakeFileName()
String fileName=MakeFileName() + ".xls";
// 返回滿足條件的記錄列表
if(key.equals("0"))
{
// TODO 調用自己定義的方法,返回查詢的當前頁記錄
listall= action.getMethodA();
}
else
{
// TODO 調用自己定義的方法,返回查詢的所有頁記錄
listall= action.getMethodB();
}
// 生成EXCEL數據
rtn = ActionImpExcel.writeExcel(url+fileName,listall,colName,";");
if (rtn) {
// 自動文件下載
response.sendRedirect(basePath+"servletdownloadfile?filename="+fileName+"&downloadFlag=1");
} else
out.print("<div align=center >導出EXCEL失敗</div>");
%>
</body>
</html>
用于生成excel的ActionImpExcel類:
/**生成excel文件*/
public class ActionImpExcel {
static int rowcount = 0;
static HashMap hmp = new HashMap();
static String arrColName[] = null;
static int colcount = 0;
/**
* 將查詢結果寫入生成的excel
* @param filename String 帶路徑的文件名
* @param list ArrayList 待寫入的查詢結果
* @param colName String 導出的列名集合
* @param sign String 列名的分隔符
* @return
**/
public static boolean writeExcel(String fileName, ArrayList list,
String colName,String sign) {
String key = "";
WritableWorkbook wwb = null;
try {
// 首先要使用Workbook類的工廠方法創建一個可寫入的工作薄(Workbook)對象
wwb = Workbook.createWorkbook(new File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
if (wwb != null) {
// 創建一個可寫入的工作表
// Workbook的createSheet方法有兩個參數,第一個是工作表的名稱,第二個是工作表在工作薄中的位置
WritableSheet ws = wwb.createSheet("sheet1", 0);
arrColName = colName.split(sign);
for (int k = 0; k < arrColName.length; k++) {
Label labelName = new Label(k, 0, arrColName[k]);
try {
ws.addCell(labelName);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
// 下面開始添加單元格
for (int i = 0; i < list.size(); i++) {
hmp = (HashMap) list.get(i);
for (int j = 0; j < hmp.size(); j++) {
// 這里需要注意的是,在Excel中,第一個參數表示列,第二個表示行
key = String.valueOf(j+1);
String colvalue = (String) hmp.get(key);
Label labelC = new Label(j, i + 1, colvalue);
try {
// 將生成的單元格添加到工作表中
ws.addCell(labelC);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
try {
// 從內存中寫入文件中
wwb.write();
// 關閉資源,釋放內存
wwb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
return true;
}
}
用于文件下載的servlet類:
public class ServletDownLoadFile extends HttpServlet {
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sFileName = "";//文件名
String sFilePath = "";//文件路徑
sFileName = request.getParameter("filename");
// 配置文件中定義的存放excel的路徑
sFilePath = PropertyManager.getProperty("tempfilepath");
sFilePath=(sFilePath==null)?"":sFilePath;
response.reset();
if("1".equals(request.getParameter("downloadFlag")))
{
//downloadFlag為1時為下載文件
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition","faxfile; filename="+new String(sFileName.getBytes("GBK"), "ISO8859_1"));
}
else if("0".equals(request.getParameter("downloadFlag")))
{
//downloadFlag為0時為用指定的程序打開文件
response.setContentType("application/x-msdownload");
}//downloadFlag為其他值時用IE默認的方式打開文件
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
bis = new BufferedInputStream(new FileInputStream(getServletContext().getRealPath(sFilePath+ sFileName)));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length)))
{
bos.write(buff,0,bytesRead);
}
}
catch(final IOException e)
{
System.out.println ( "IOException." + e );
}
finally
{
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
//Clean up resources
public void destroy() {
}
}
好了,最后在web.xml中添加servlet的配置信息;并在application.properties配置好存放excel的目錄變量tempfilepath即可。