利用php导出excel我们大多会直接生成 csv文件,这种方便快捷如果不是要求很高,完全可以利用csv 来实例了,这是最简单的了,代码如下:
- <?php
- header("Content-type:application/vnd.ms-excel");
- header("Content-Disposition:attachment;filename=test_data.xls");
-
- $tx=’表头’;
- echo $tx."nn";
-
- echo "姓名"."t";
- echo "年龄"."t";
- echo "学历"."t";
- echo "n";
- echo "张三"."t";
- echo "25"."t";
- echo "本科"."t";
- ?>
如果你一定要输入xls标准的excel文件可参考下面方法,代码如下:
-
-
-
-
-
-
-
- function outputXlsHeader($data,$file_name = 'export')
- {
- header('Content-Type: text/xls');
- header ( "Content-type:application/vnd.ms-excel;charset=utf-8" );
- $str = mb_convert_encoding($file_name, 'gbk', 'utf-8');
- header('Content-Disposition: attachment;filename="' .$str . '.xls"');
- header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
- header('Expires:0');
- header('Pragma:public');
- $table_data = '<table border="1">';
- foreach ($data as $line)
- {
- $table_data .= '<tr>';
- foreach ($line as $key => &$item)
- {
- $item = mb_convert_encoding($item, 'gbk', 'utf-8');
- $table_data .= '<td>' . $item . '</td>';
- }
- $table_data .= '</tr>';
- }
- $table_data .='</table>';
- echo $table_data;
- die();
- }
下面还推荐一下第三方的做法.
引用google code中推荐的小类库(大体同方法一,比较复杂点):http://code.google.com/p/php-excel/downloads/list
PHPEXCEL 类库,功能强大,支持win Excel2003 ,Win Excel2007. |