PHP输出excel CSV等文件

<?php
$fileName = "fileName";
header("Content-Type:text/csv;charset=UTF-8"); //'text/csv'是CSV文件,'application/vnd.ms-excel'是excel文件
header("Content-Disposition: attachment; filename=" . $fileName . ".csv"); //$fileName文件名,“.csv”文件扩展名也可是".xls"excel文件
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');

echo "\n" . iconv("utf-8", "gbk", "大连,") . "\t" . iconv("utf-8", "gbk", "大连2");
//echo就是输出内容到文件中,"\n"是换行,"\t"在excel文件里是换格,","在CSV文件里是换格

//生成或补充CSV文件也可用如下方法
$fileName = "test.csv";
$file = fopen($fileName, 'a');//打开指定csv文件,没有则创建
$fields = array( "txt11" ,  "txt21" , "txt31");
fputcsv ( $file ,  $fields );//在打开的csv文件内容末尾另起一行,添加数组中内容,数组一个元素代表一个单元格
$fields = array( "txt12" ,  "txt22" , "txt32");
fputcsv ( $file ,  $fields );//再另起一行添加数组内容
fclose ( $file );//关闭文件句柄



//生成excel还有如下方法
$filename = "导出数据表";
$filename_type = 'xls';
header ( "Content-Type: application/vnd.ms-excel" );
Header ( "Accept-Ranges:bytes" );
Header ( "Content-Disposition:attachment;filename=" . $filename . "." . $filename_type ); // $filename导出的文件名
header ( "Pragma: no-cache" );
header ( "Expires: 0" );
echo '
    <html xmlns:o="urn:schemas-microsoft-com:office:office"
    xmlns:x="urn:schemas-microsoft-com:office:excel"
    xmlns="http://www.w3.org/TR/REC-html40">
    <head>
    <meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT">
    <meta http-equiv=Content-Type content="text/html; charset=gb2312">
    <!--[if gte mso 9]><xml>
    <x:ExcelWorkbook>
    <x:ExcelWorksheets>
    <x:ExcelWorksheet>
    <x:Name></x:Name>
    <x:WorksheetOptions>
    <x:DisplayGridlines/>
    </x:WorksheetOptions>
    </x:ExcelWorksheet>
    </x:ExcelWorksheets>
    </x:ExcelWorkbook>
    </xml><![endif]-->
    </head>'
    ;

echo "<table>";
echo "
    <tr>
    <td>".iconv ( "utf-8", "gbk", "标题一 ")."</td>
    <td>".iconv ( "utf-8", "gbk", "标题二 ")."</td>
    <td>".iconv ( "utf-8", "gbk", "标题三")."</td>
    </tr>
    ";

echo "
    <tr>
    <td>".iconv ( "utf-8", "gbk", '内容一' )."</td>
    <td style='vnd.ms-excel.numberformat:@'>12345678910123456</td>
    <td style='vnd.ms-excel.numberformat:yyyy-mm-dd'>2016/10/24</td>
    </tr>
    ";
echo "</table>";
exit ();
//<td>即代表换格,<tr>代表换行
//style='vnd.ms-excel.numberformat:@'表示避免将表格中长数字用科学计数显示
//style='vnd.ms-excel.numberformat:yyyy-mm-dd' 表示将表格中内容按指定样式显示

 

posted @ 2012-03-21 22:56  风吹屁股凉冰冰  阅读(675)  评论(0编辑  收藏  举报