php 通过单击按钮保存 PhpSpreadSheet
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45737485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving a PhpSpreadSheet through button click
提问by Ferdi van der Woerd
I'm trying to get my Laravel app to download an excel file with phpSpreadSheeta 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.
我正在尝试让我的 Laravel 应用程序使用phpSpreadSheet下载一个 excel 文件,这是PhpExcel的延续。但到目前为止,我没有任何运气。我首先尝试通过 onClick 进行 Axios 调用,但由于 JS 不允许保存内容,因此无效。之后,我尝试将按钮附加到 Laravel 操作,这只是打开了一个空页面。
I don't know if anyone here will be able to help me but I will remain hopeful
我不知道这里是否有人能够帮助我,但我仍然充满希望
回答by Asur
First you need to set an endpoint in your routes to call it using ajax (axios in your case):
首先,您需要在路由中设置一个端点以使用 ajax(在您的情况下为 axios)来调用它:
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:
如果您没有该文件,您可以将其保存到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.
现在您只需要调用端点/spreadsheet/download
即可开始下载,但正常<a href="/spreadsheet/download">Download</a>
工作即可。
Hope this helps you.
希望这对你有帮助。