匯出CSV檔:
header("Content-type: text/x-csv");
header("Content-Disposition:filename=exportFileName.csv");
echo iconv("UTF-8","big5", "欄位名1, 欄位名2, ...., 欄位名x\n");
echo iconv("UTF-8","big5", "資料1, 資料2, ......, 資料x\n");
匯出Excel檔:
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=exportFileName.xls");
echo iconv("UTF-8","big5","欄位1\t欄位2\t, ...\t欄位x\n");
echo iconv("UTF-8","big5","資料1\t資料2\t, ...\t資料x\n");
差別在於匯出Excel檔的時候每個欄位間隔要加入\t做跳欄動作。
範例
$sql = "select * from users";
$result = mysql_query($sql);
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=users.xls");
while($row = mysql_fetch_array($rs)){
echo "<tr>"
. "<td>". $row['id'] ."</td>"
. "<td>". mb_substr($sname, 0, -1,"UTF-8") ."O</td>"
. "<td>xxxx". mb_substr($row['tel'], 4, 100,"UTF-8") ."</td>"
. "<td>xxx". mb_substr($row['email'], 3, 100,"UTF-8") ."</td>"
."</tr>";
}
先做資料庫的select,再來寫入標頭檔header(),接著就是用while迴圈去跑資料庫所擷取出來的資料並且寫入到Excel檔裡就好了。 |