108.PHP输出CSV和EXCEL两种简单的方法

来源:互联网 发布:坚持 知乎 编辑:程序博客网 时间:2024/06/05 05:01

1.定义 header()
这里写图片描述

header("Content-type:application/vnd.ms-excel");header("Content-Disposition:attachment;filename=test_data.xls");

这里写图片描述

1. csv 格式

csv.php<?phpheader("content-type:application/vnd.ms-excel");header('content-Disposition:filename=php100.xls');echo "A1\t B1\t C1\n";echo "A2\t B2\t C2\n";echo "A3\t B3\t C3\n";

结果:
这里写图片描述


2. 表格格式

excel.php<?phpheader("content-type:application/vnd.ms-excel");header('content-Disposition:filename=php100.xls');Header("Content-type: application/octet-stream;charset=gbk");?><html><head><!--    防止中文乱码-->    <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />  </head><body><table width="200" border="1">    <tr>        <td colspan="3">学员统计</td>    </tr>    <tr>        <td>编号</td>        <td>姓名</td>        <td>年龄</td>    </tr>    <tr>        <td>1</td>        <td>张三</td>        <td>29</td>    </tr>    <tr>        <td>2</td>        <td>李四</td>        <td>25</td>    </tr></table></body></html>

这里写图片描述


3. 使用样式 跟 函数

<?phpheader("content-type:application/vnd.ms-excel");header('content-Disposition:filename=php100.xls');Header("Content-type: application/octet-stream;charset=gbk");?><html><head>    <!--    防止中文乱码-->    <meta http-equiv="Content-type" content="text/html;charset=UTF-8" /></head><body><table width="200" border="1">    <tr>        <td colspan="3"><font color="red">学员统计</font></td>    </tr>    <tr>        <td>编号</td>        <td>姓名</td>        <td>年龄</td>    </tr>    <tr>        <td>1</td>        <td>张三</td>        <td>29</td>    </tr>    <tr>        <td>2</td>        <td>李四</td>        <td>25</td>    </tr>    <tr>        <td>=A3+A4</td>        <td></td>        <td>=SUM(C3:C4)</td>    </tr></table></body></html>

这里写图片描述


输出 excel2007 的header 头部:

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');            header('Content-Disposition: attachment;filename="'.$key.'.xlsx'.'"');            header('Cache-Control: max-age=0');            // If you're serving to IE 9, then the following may be needed            header('Cache-Control: max-age=1');            // If you're serving to IE over SSL, then the following may be needed            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1            header('Pragma: public'); // HTTP/1.0            readfile($fileName);
0 0