花了一天的时间,遇到各种坑。
借鉴这篇文章实现导出功能:https://www.yiichina.com/tutorial/1839
转载里面的代码时,发现数据里面出现:空格、逗号、就会使excel不正常,做了以下改进解决问题:
1、将空格、换行符之类的替换为空。
2、将英文的逗号替换为中文的逗号。
public static function exportCsv(Array $csv_header, Array $data, $filename='')
{
$filename =$filename?$filename:date('Ymd').'.csv'; //设置文件名
header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=".$filename);
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
foreach ($csv_header as $k => $v) {
$csv_header[$k] = iconv('utf-8','gb2312',$v);
}
echo implode(',', $csv_header) . "\n";
$str = '';
$qian = array(" "," ","\t","\n","\r"); //需要替换的换行符,空格,等。
foreach($data as $v){
foreach ($v as $key => $col){
//$v[$key] = str_replace(" ","",iconv('utf-8','gb2312//IGNORE',$col));
$v[$key] = str_replace(",",",",$col); //将英文逗号换成中文逗号
$v[$key] = str_replace($qian,"",trim(iconv('utf-8','gb2312//IGNORE',$v[$key])));
}
$abc = implode(',',$v);
$str .= $abc. "\n";
}
echo $str;
flush();
}
2019.4.19日出现提示问题:
Cannot modify header information - headers already sent by
分析原因:
因为这个是类的函数,而一般调用这个函数方法时都会重复调用,导致重复输出header
解决办法代码:
public static function exportCsv(Array $csv_header, Array $data, $filename='')
{
static $i = 1;
$filename =$filename?$filename:date('Ymd').'.csv';
if($i<2){
header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=".$filename);
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
}
foreach ($csv_header as $k => $v) {
$csv_header[$k] = iconv('utf-8','gb2312',$v);
}
echo implode(',', $csv_header) . "\n";
$str = '';
$qian = array(" "," ","\t","\n","\r"); //需要替换的换行符,空格,等。
foreach($data as $v){
foreach ($v as $key => $col){
//$v[$key] = str_replace(" ","",iconv('utf-8','gb2312//IGNORE',$col));
$v[$key] = str_replace(",",",",$col);
$v[$key] = str_replace($qian,"",trim(iconv('utf-8','gb2312//IGNORE',$v[$key])));
}
$abc = implode(',',$v);
$str .= $abc. "\n";
}
echo $str;
flush();
$i++;
}