PHP导出excel CSV(前后分离)
Posted 满眼都是她
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP导出excel CSV(前后分离)相关的知识,希望对你有一定的参考价值。
CSV优势:导入导出速度快
缺点:不能倒入图片等
一、前后分离,给前端url
public function excel() { //头部字段 $headlist = [\'name\'=>\'名字\',\'score\'=>\'得分\']; //主体内容 $data = [ [\'name\' => \'张三\', \'score\' => \'80\'], [\'name\' => \'李四\', \'score\' => \'90\'], [\'name\' => \'王五\', \'score\' => \'60\'], ]; $fileName = "导出表格.csv"; $file_path = "uploads/csv/"; if (!file_exists($file_path)) { mkdir($file_path, 0777, true); } $file_path = "/uploads/csv/" . $fileName; $fp = fopen("." . $file_path, "w"); //输出Excel列名信息 foreach ($headlist as $key => $value) { //CSV的Excel支持GBK编码,一定要转换,否则乱码 $headlist[$key] = iconv(\'utf-8\', \'gbk\', $value); } //将数据通过fputcsv写到文件句柄 fputcsv($fp, $headlist); //计数器 $num = 0; //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小 $limit = 100000; //逐行取出数据,不浪费内存 $count = count($data); for ($i = 0; $i < $count; $i++) { $num++; //刷新一下输出buffer,防止由于数据过多造成问题 if ($limit == $num) { ob_flush(); flush(); $num = 0; } $row = $data[$i]; foreach ($row as $key => $value) { $row[$key] = iconv(\'utf-8\', \'gbk\', $value); } fputcsv($fp, $row); } return ["code" => 1, "msg" => "获取成功", "url" => $_SERVER[\'HTTP_HOST\'] . $file_path]; }
二、直接输出浏览器
public function excel(){ //头部字段 $headlist = [\'name\'=>\'名字\',\'score\'=>\'得分\']; //主体内容 $data = [ [\'name\' => \'张三\', \'score\' => \'80\'], [\'name\' => \'李四\', \'score\' => \'90\'], [\'name\' => \'王五\', \'score\' => \'60\'], ]; $fileName = \'导出\'; header(\'Content-Type: application/vnd.ms-excel\'); header(\'Content-Disposition: attachment;filename="\'.$fileName.\'.csv"\'); header(\'Cache-Control: max-age=0\'); //打开php文件句柄,php://output 表示直接输出到浏览器 $fp = fopen(\'php://output\', \'a\'); //输出Excel列名信息 foreach ($headlist as $key => $value) { //CSV的Excel支持GBK编码,一定要转换,否则乱码 $headlist[$key] = iconv(\'utf-8\', \'gbk\', $value); } //将数据通过fputcsv写到文件句柄 fputcsv($fp, $headlist); //计数器 $num = 0; //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小 $limit = 100000; //逐行取出数据,不浪费内存 $count = count($data); for ($i = 0; $i < $count; $i++) { $num++; //刷新一下输出buffer,防止由于数据过多造成问题 if ($limit == $num) { ob_flush(); flush(); $num = 0; } $row = $data[$i]; foreach ($row as $key => $value) { $row[$key] = iconv(\'utf-8\', \'gbk\', $value); } fputcsv($fp, $row); } }
以上是关于PHP导出excel CSV(前后分离)的主要内容,如果未能解决你的问题,请参考以下文章
从零开始搭建django前后端分离项目 系列五(实战之excel流式导出)