I'm trying to get my Laravel app to download an excel file with phpSpreadSheet a continuation of PhpExcel. But so far I'm not having any luck with it. I first tried to make an Axios call through an onClick but that didn't work since JS is not allowed to save things. After that I tried to attach the button to a Laravel action this just opened an empty page.
I don't know if anyone here will be able to help me but I will remain hopeful
First you need to set an endpoint in your routes to call it using ajax (axios in your case):
Route::get('spreadsheet/download',[
'as' => 'spreadsheet.download',
'uses' => 'SpreadsheetController@download'
]);
In your controller:
public function download ()
{
$fileContents = Storage::disk('local')->get($pathToTheFile);
$response = Response::make($fileContents, 200);
$response->header('Content-Type', Storage::disk('local')->mimeType($pathToTheFile));
return $response;
}
In case you don't have the file you can save it to php://output:
public function download ()
{
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="file.xlsx"');
$writer->save("php://output");
}
Now you just need to call the endpoint /spreadsheet/download
to start the download, but a normal <a href="/spreadsheet/download">Download</a>
would work.
Hope this helps you.