2010/1/15

(php) 將 mysql 的資料轉成 csv 檔

最近因需求, 必需提供使用者將自己的來賓資料轉成 excel 檔

所以開始 study 怎樣將資料轉成會員所需的 csv 檔

以下便是我的程式

1. 標題列的產生

$exportString = 'Customer No'.",".'Serial No'.",".'Guest Name';
$exportString .= ",".'Sex'.",".'Age'.",".'Telephone'.",".'Mobile'.",";
$exportString .= "Address".","."Remark".","."Create Date".","."Last Modify Date";
$exportString .= "\r\n";

2. 到 table 去將資料找出來

$sql = "select * from guest_file where cno = '".$cno."' order by uid desc";

3. 將找出來的資料一一組合到 string 裏面去

$res2 = @$mdb2->query($sql);
$row2 = $res2->fetchAll();
$num2 = $res2->numRows();
for( $i=0; $i<$num2; $i++)
{
$exportString .= $cno.",".$row2[$i]['uid'].",".$row2[$i]['uname'].",";
$exportString .= $row2[$i]['usex'].",".$row2[$i]['uage'].",".$row2[$i]['utel'].",".$row2[$i]['umobile'].",";
$exportString .= $row2[$i]['uaddress'].",".$row2[$i]['remark'].",".$row2[$i]['create_date'].",".$row2[$i]['tx_date'];
$exportString .= "\r\n";
}

4. 將存在 string 內的變數丟成 csv 檔

header('Content-Type: text/html; charset=utf-8');
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=Mydata-" . date("Y-m-d").".csv");
print $exportString;

==> 其中預設的 csv 檔先給一個檔名 Mydata-YYYYMMDD.csv 的日期檔名...

沒有留言:

張貼留言