因為聽到有同事討論JSP輸出Excel文件的,就是在頁面上有一個【導出】按鈕,能夠將查詢結果導出到Excel文件讓用戶下載。有人說要用POI在后臺生成臨時的Excel文件,然后通過讀取FileStream寫入到OutputStream來解決。其實這個功能不需要這么重型的武器的,雖然很多人討厭MS,但是不得不承認MS絕對不是亂蓋的,IE和Office產品的幾近完美的結合就是一個列子。頁面里面的Table很容易就可以導出到Excel文件,而且格式都能夠完好的保存,所以如果要將查詢結果導出到Excel,只需將頁面的Context-Type修改一下就可以了:
<%@ page language="java" contentType="application/vnd.ms-excel"%>
然后請求這個頁面的時候,就會出現這樣的IE窗口:
看到上面的菜單了么?出了IE的,還有Excel的。而且在點擊“文件”->“另存為”的時候,如果選擇“Excel工作簿”,那么保存的文件就是真正的轉換到Excel文件的存儲格式了。
不過,有一個問題是,如果我不希望直接在IE里面打開Excel文件,我希望能夠提供那個打開/保存的對話框,應該如何做?
模模糊糊記得很久很久以前用過一個參數,于是乎,google一下吧,找到了,就是這個Content-Disposition參數,HTTP Response Header的一個參數。但是這個不是標準參數,查看一下HTTP/1.1的規范文檔,對于這個參數的解釋大意如下:
Content-Disposition參數本來是為了在客戶端另存文件時提供一個建議的文件名,但是考慮到安全的原因,就從規范中去掉了這個參數。但是由于很多瀏覽器已經能夠支持這個參數,所以只是在規范文檔中列出,但是要注意這個不是HTTP/1.1的標準參數。
于是,在頁面加入一行代碼:
<%
response.addHeader("Content-Disposition", "attachment;filename=test.xls");
%>
能夠看到“文件下載”的對話框了:
測試了一下,其實IE是根據Content-Disposition中filename這個段中文件名的后綴來識別這個文件類型的,所以,如果有很多種文件類型的時候,可以將Content-Type設置為二進制模式的:
<%@ page language="java" contentType="application/octet-stream"%>
附Content-Disposition的解釋:
19.5.1 Content-Disposition The Content-Disposition response-header field has been proposed as a means for the origin server to suggest a default filename if the user requests that the content is saved to a file. This usage is derived from the definition of Content-Disposition in RFC 1806 [35].
content-disposition = "Content-Disposition" ":" disposition-type *( ";" disposition-parm )
disposition-type = "attachment" | disp-extension-token
disposition-parm = filename-parm | disp-extension-parm
filename-parm = "filename" "=" quoted-string
disp-extension-token = token
disp-extension-parm = token "=" ( token | quoted-string )
An example is
Content-Disposition: attachment; filename="fname.ext"
The receiving user agent SHOULD NOT respect any directory path information present in the filename-parm parameter, which is the only parameter believed to apply to HTTP implementations at this time. The filename SHOULD be treated as a terminal component only.
If this header is used in a response with the application/octet- stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as...' dialog.
posted on 2008-04-23 18:23
YODA 閱讀(11859)
評論(4) 編輯 收藏