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
Use composer to install PhpSpreadsheet into your project. Or also download the documentation and samples if you plan to use them. A good way to get started is to run some of the samples. Don't forget to download them via --prefer-source composer flag.
Read Excel File First, import the needed library and load the Reader of XLSX. Read the excel file using the load() function. Here test. xlsx is the file name.
You may use the following code: header('Content-Type: application/vnd. ms-excel'); header('Content-Disposition: attachment;filename="file. xlsx"'); header('Cache-Control: max-age=0'); $writer->save('php://output');
Write a newline character "\n" in a cell (ALT+"Enter") In Microsoft Office Excel you get a line break in a cell by hitting ALT+"Enter".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With