首页 > php开发 > php导出生成excel表格几种方法介绍

php导出生成excel表格几种方法介绍

利用php导出excel我们大多会直接生成 csv文件,这种方便快捷如果不是要求很高,完全可以利用csv 来实例了,这是最简单的了,代码如下:

<?php
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=test_data.xls");
$tx = '表头';
echo $tx . "\n\n";
//输出内容如下:
echo "姓名" . "\t";
echo "年龄" . "\t";
echo "学历" . "\t";
echo "n";
echo "张三" . "\t";
echo "25" . "\t";
echo "本科" . "\t";
?>

如果你一定要输入xls标准的excel文件可参考下面方法,代码如下:

<?php
/**  
 * 输出XLS的头信息
 * 注:使用此函数前后都不应有任何数据输出
 * @param $data Array 下载的数据
 * @param $file_name String 下载的文件名
 */
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.


文章网址:http://www.phprm.com/develop/fs4104.html

随意转载^^但请附上教程地址。

标签:php导出excel 生成excel

相关文章

发表留言