public function export($search)
{
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename={$filename}.csv");
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
$header = 'ID,时间,订单号';
$header .= "\n";
$excel_out = iconv('utf-8', 'gbk', $header);//生成字段
foreach ($data as $val) {
$id = iconv('utf-8', 'gbk', $val['id']);
$dtCreated = iconv('utf-8', 'gbk', $val['dt_created']);
$order_no = iconv('utf-8', 'gbk', $val['order_no']."\t");
$excel_out .= "{$id},{$dtCreated},{$order_no}";
$excel_out .= "\n";
}
return $excel_out;
}
上面是一段导出csv 数据的处理逻辑。导出数据主要有两个问题注意
- iconv(‘utf-8’, ‘gbk’, ‘原始字段内容’) ,防止execl查看中文乱码,需要转码
- 数字字符串如20210507102211520088265 订单号,一般会自动转成科学计数法展示,需要添加"\t"制表符,防止转译。iconv(‘utf-8’, ‘gbk’, ‘原始字段内容’."\t")