点击 ExportCSV 路径时,它会显示浏览器上的所有数据,而不是(下载)导出 CSV 文件。
控制器:
public function export()
{
$datas = DeviceStorage::all();
$csvFileName = 'min_value.csv';
$headers = [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="' . $csvFileName . '"',
];
$handle = fopen('php://output', 'w');
fputcsv($handle, ['device_id', 'device_name' , 'min_sale_price']);
foreach ($datas as $data) {
fputcsv($handle, [$data->device_id, $data->Device->device_name, $data->min_sale_price]);
}
fclose($handle);
return Response::make('', 200, $headers);
}
路线:
Route::get('export/csv' , [DeviceController::class , 'export'])->name('export.csv');
刀片文件:
<a class="btn btn-primary" href="{{ url('export/csv') }}">Export CSV</a>
要解决此问题,请执行以下步骤:
public function exportCsv()
{
$data = YourModel::all();
$csvFileName = 'export.csv';
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$csvFileName",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate",
"Expires" => "0",
);
$handle = fopen('php://output', 'w');
// Add CSV header
fputcsv($handle, array_keys($data->first()->toArray()));
// Add CSV rows
foreach ($data as $row) {
fputcsv($handle, $row->toArray());
}
fclose($handle);
return response()->stream(
function () use ($handle) {
fclose($handle);
},
200,
$headers
);
}