Saving a PhpSpreadSheet through button click Saving a PhpSpreadSheet through button click php php

Saving a PhpSpreadSheet through button click


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.