PHP快速导出数据到EXCEL/CSV
快速导出数据到EXCEL/CSV
/** 快速导出数据到EXCEL/CSV
*/
public function exportDataAction()
{
set_time_limit(0);
ini_set('memory_limit', '1024M');
$list = [['测试1','测试2','测试3','测试4','测试5','测试6','测试7','测试8'],['测试21','测试22','测试23','测试24','测试25','测试26']];
$columns = ['渠道ID','商品名称', '商品编号', '商品类型', '面值', '供货价', '销售状态'];
$fileName = '导出数据-'.date('Y-m-d', time()).'.csv';
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename={$fileName}");
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$fp = fopen('php://output', 'a');//打开output流
mb_convert_variables('GBK', 'UTF-8', $columns);
fputcsv($fp, $columns);//将数据格式化为CSV格式并写入到output流中
foreach($list as $key=>$row) {
//需要格式转换,否则会乱码
mb_convert_variables('GBK', 'UTF-8', $row);
fputcsv($fp, $row);
}
ob_flush(); //必须同时使用 ob_flush() 和flush() 函数来刷新输出缓冲。
flush();
fclose($fp);
exit();
}

被折叠的 条评论
为什么被折叠?



