导出抽奖信息,查询sql忽略,导出数据,添加BOM头,防止excel打开csv文件乱码,代码如下:
public function prizeExport(Request $request)
{
$filename = '中奖信息'.date('Ymd',time()).'.csv';
header('Content-Type: application/vnd.ms-excel;charset=utf-8');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
header('Access-Control-Allow-Origin: *');
//预设标题行
$pre_titles = [
'id' => '中奖ID',
'name' => '奖品名称',
'created_at' => '中奖时间',
'nickname' => '用户昵称',
'activity_name' => '活动名称',
'addressee_name' => '收件人姓名',
'addressee_mobile' => '收件人电话',
'email' => '邮箱',
'school_name' => '学校名称',
'address' => '收件人地址',
'delivery_type' => '快递类型',
'delivery_status' => '发货状态',
'express_number' => '快递单号',
];
$real_head = array_values($pre_titles);
$select = array_keys($pre_titles);
$params = $request->all();
$instance = $this->search($params);
$total = $instance->count();
$page_size = $limit = 10000;
$counter = 0;
$fp = fopen('php://output', 'a');
fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//添加BOM,以防excel打开乱码
fputcsv($fp, $real_head);
for ($page = 0; $page < ceil($total / $page_size); $page++) {
$offset = $page * $page_size;
$lists = $instance->limit($page_size)->offset($offset)->select($select)->get()->toArray();
foreach ($lists as $chunk) {
$counter++;
if ($limit == $counter) {
//刷新一下输出buffer
ob_flush();
flush();
$counter = 0;
}
fputcsv($fp, $chunk); //写入第一行数据
}
}
fclose($fp);
exit();
}