直接上代碼
public function doExcel($data)
{
// 文件名
$filename = date('YmdHis') . '.csv';
// 文件完整路徑
$filepath = dirname(dirname(__FILE__)) . '/' . $filename;
// 打開文件,沒有自動創建
$fp = fopen($filepath, 'a');
// 設置導航欄
$headers = array('手機號','地市');
$content = implode(',', $headers) . PHP_EOL;
// 填充數據
foreach ($data as $value) {
$content .= $value['phone'] . ',' . $value['name'] . PHP_EOL;
}
// 寫入數據
fwrite($fp, $content);
// 關閉文件
fclose($fp);
// 設置header
header("Pragma: public");
header("Expires: 0");
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type:application/vnd.ms-execl");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");;
header('Content-Disposition:attachment;filename='.$filename);
header("Content-Transfer-Encoding:binary");
// 輸出到瀏覽器
readfile($filepath);
// 刪除本地文件
unlink($filepath);
}