woff 發表於 2012-6-13 23:59:16

資料匯出CSV Excel

這是個基礎的東西,在設計資料庫匯出做備份時都會需要的。

匯出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做跳欄動作,至於iconv函式是否一定要用,就看個案需要與否做決定。

應用如下所示(以Excel檔為例):$sql = "select * from scoretable";
$rs = $DB_class->DB_query($sql);
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=ScoreTable_buckup.xls");
while($row = mysql_fetch_array($rs)){
    echo mb_convert_encoding("$row\t$row\t$row\t$row\t$row\t$row\t$row\t$row\t$row\t$row\n","big5","UTF8");
} 先做資料庫的select,再來寫入標頭檔header(),接著就是用while迴圈去跑資料庫所擷取出來的資料並且寫入到Excel檔裡就好了。
頁: [1]
查看完整版本: 資料匯出CSV Excel