最近項目需要將網頁上的數據導出為 excel ,雖然處理方法簡單,但是我這做了些不同情況的測試,以及我使用的是 PHP ,并非 JSP 。原理是一樣的,將頭部設置成 excel 對應的格式。所以我還是認為應該做個總結記錄下。希望其他同行遇到同樣的需求的時候我這篇文章能起到一點點微弱的正面作用。
php :
<?
php
???
header
(
"Content-Type:application/vnd.ms-execl"
);
header
(
"Content-Disposition:filename=test.xls"
);
?>
對應的
JSP
:
<%
response.setHeader("Content-disposition","inline; filename=test1.xls");
?%>
其中,inline 線上瀏覽方式,對應 attachment 下載保存。當然不寫,他也會詢問你的。
我的較完整的
php
測試代碼
1
:
<?
php
???
header
(
"Content-Type:application/vnd.ms-execl"
);
???
header
(
"Content-Disposition:filename=test.xls"
);
??? echo "test1\t";
??? echo "test1\t";
??? echo "test1\t";
??? echo "test1\t";
??? echo "test1\n";
??? echo "test2\t";
??? echo "test2\t";
??? echo "test2\t";
??? echo "test2\t";
??? echo "test2\n";
?>
測試打開網頁后,提示保存或者打開
excel
文件。結果也顯示是正確的。代碼中關于
’
\t’,
其實你取數據輪到下一列就用‘
\t
’,而遇到下一行就用‘
\n
’。簡單吧。而我隨后進行了
table
的原始測試,也就是頁面本來就有表格的那種。比如:
php
測試代碼
2
:
<?
php
???
header
(
"Content-Type:application/vnd.ms-execl"
);
???
header
(
"Content-Disposition:filename=test.xls"
);
?>
<
table
cellpadding
="
1
"
cellspacing
="
1
"
border
="
1
"
>
???
<
tr
>
???
<
td
width
="
30
"
>
test1
</
td
>
???
<
td
width
="
60
"
>
test1
</
td
>
???
<
td
width
="
30
"
>
test1
</
td
>
???
<
td
width
="
100
"
>
test1
</
td
>
???
<
td
width
="
80
"
>
test1
</
td
>
???
</
tr
>
???
???
<
tr
>
???
<
td
>
test2
</
td
>
???
<
td
>
test1
</
td
>
???
<
td
>
test1
</
td
>
???
<
td
>
test1
</
td
>
???
<
td
>
test1
</
td
>
???
</
tr
>
</
table
>
測試結果順利導出頁面
table
為
excel
。
說明:
1.???
代碼指定的寬度是起了作用。如果不制定,當然就自由伸縮,以放得下為標準。
2.?????? 剛開始表格 cellpadding =" 1 " cellspacing =" 1 " border =" 1 " 這些屬性我都沒有設置,導的 excel 是沒有單元格邊框的。
3.
還有千萬別在
HTML
里搞那
7788
的頭聲明(因為這里指定了,別沖突了哦)。小心出錯。
o(
∩
_
∩
)o…
4. 當我們要導出word時候呢?
你肯定已經知道方法了。對的,我們只需要把contentType改成"application/msword"以及filename的副檔名改成.doc就可以了。這個我沒有測試。