<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /?>
最近项目需要将网页上的数据导出为 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就可以了。这个我没有测试。