php導出csv格式數據實現:
先定義一個字符串 存儲內容,例如
$exportdata = '規則111,規則222,審222,規222,服2222,規則1,規則2,規則3,匹配字符,設置時間,有效期'."\n";
然後對需要保存csv的數組進行foreach循環,例如
if (!empty($lists)){
foreach($lists as $key => $value){
$time = date("Y-m-d_H:i:s", $value['add_time']);
$exportdata .= "\"\t".$value['Rule_id']."\",\"\t".$value['Rule_name']."\",\"\t".$value['Matching_level']."\",\"\t"."{$value['Rule_action']}"."\",\"\t".$value['Service_type']."\",\"\t".$value['Keyword1']."\",\"\t".$value['Keyword2']."\",\"\t".$value['Keyword3']."\",\"\t".$value['Matching_word']."\",\"\t".$value['Set_time']."\",\"\t".$value['Validation_time']."\"\n";
}
}
csv格式的內容用','隔開,在現實的時候就能分格了。每一行後面就一個'\n'就能分行了。
然後在後面執行輸出就行了。例如
$filename = "plcnetinfo_{$date}.csv";
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$filename");
header("Expires: 0");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
echo(mb_convert_encoding($exportdata,"gb2312","UTF-8"));
但是在導出數字的時候csv就會把前面的0去掉,例如 我想顯示 00001 ,如果輸出的話就會顯示1.這種解決辦法就是在輸出的時候就一個'\"\t',這個是制表符,會顯示成空格。就能把數值轉化成文本了。不過在導入的時候會出現'" '.這種東西,用一下php自帶的trim函數就好了。完整代碼如下:
//var_dump($sql);
$lists = $this->dbo->query($sql);
$exportdata = '規則111,規則222,審222,規222,服2222,規則1,規則2,規則3,匹配字符,設置時間,有效期'."\n";
$date = date("YmdHis");
if (!empty($lists)){
foreach($lists as $key => $value){
$time = date("Y-m-d_H:i:s", $value['add_time']);
$exportdata .= "\"\t".$value['Rule_id']."\",\"\t".$value['Rule_name']."\",\"\t".$value['Matching_level']."\",\"\t"."{$value['Rule_action']}"."\",\"\t".$value['Service_type']."\",\"\t".$value['Keyword1']."\",\"\t".$value['Keyword2']."\",\"\t".$value['Keyword3']."\",\"\t".$value['Matching_word']."\",\"\t".$value['Set_time']."\",\"\t".$value['Validation_time']."\"\n";
}
}
$filename = "plcnetinfo_{$date}.csv";
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$filename");
header("Expires: 0");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
echo(mb_convert_encoding($exportdata,"gb2312","UTF-8"));