常规导出xlsx 更多的是导出小数据 需要大数据导出的时候 需要临时更改内存大小 ini_set('memory_limit', '1024M'); 不更改内存的情况 可以选择队列导出到服务器后另行下载;
导出csv 由于一般浏览器都是默认解析输出模式 所以一般加header头
这里说两种:
1/
use Illuminate\Support\Facades\Response;
$data = [1,2,3,4];
$headers = array(
"Access-Control-Expose-Headers" => "Content-Disposition"
);
$filename = storage_path('attend_member_list.csv');
$output = fopen($filename, 'w+');
foreach ($data as $line) {
fputcsv($output, $line);
}
return Response::download($filename, '参与列表.csv', $headers);
2/
use Maatwebsite\Excel\Facades\Excel;
$header = [];
$excelData =[];
$headers = array(
"Access-Control-Expose-Headers" => "Content-Disposition"
);
return Excel::download((new ExcelExport($excelData->toArray(), $header)), '参与列表.csv', null, $headers);
new ExcelExport 是创建导出类库
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
class ExcelExport implements FromCollection, WithHeadings
{
use Exportable;
private $data;
private $headings;
//数据注入
public function __construct($data, $headings)
{
$this->data = $data;
$this->headings = $headings;
}
//实现FromCollection接口
public function collection()
{
return collect($this->data);
}
//实现WithHeadings接口
public function headings(): array
{
return $this->headings;
}
}