先了解如何生成后缀为 .csv文件的方法 传送门
# 数组,调用下面方法然后直接下载
public function index(){
$array = [
['name' => '张三','age' => 17],
['name' => '李四','age' => 18],
['name' => '王五','age' => 19],
['name' => '麻二','age' => 20],
];
return $this->export_csv($array);
}
/*** * 导出下载excel * @param [array] $array [要转换excel数组] */
public function export_csv($array){
$temp = '';
foreach ($array as $value)
{
foreach ($value as $k => $val)
{
$value[$k] = iconv('utf-8','gb2312',$value[$k]);
}
$temp .= implode(",",$value)."\n"; //用英文“逗号”分开,获取值
}
# 获取name,age做标题【这里我没有想到更好的方法,做个flag以便以后更加完善】
## 就是要取出 ‘name’,'age' 这两个key
$keyname = array_keys($array[0])[0] . ',' . array_keys($array[0])[1] ."\n";
$string = $keyname. $temp;//拼接
$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');
echo $string;
}
最终导出的excel如下:
以上是没有使用类库的生成简单excel方法!