Saving a PhpSpreadSheet through button click

左心房为你撑大大i 提交于 2020-01-12 06:46:45

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/45737485/saving-a-phpspreadsheet-through-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!