通过按钮单击保存PhpSpreadSheet

Fer*_*erd 15 php spreadsheet laravel

我正在尝试让我的Laravel应用程序下载带有phpSpreadSheet的excel文件,这是PhpExcel的延续.但到目前为止,我没有任何运气.我首先尝试通过onClick进行Axios调用,但由于不允许JS保存,因此无效.之后,我尝试将按钮附加到Laravel动作,这只是打开一个空页面.

我不知道这里是否有人能帮助我,但我会保持充满希望

Asu*_*sur 30

首先,您需要在路由中设置端点以使用ajax(在您的情况下为axios)来调用它:

Route::get('spreadsheet/download',[
   'as' => 'spreadsheet.download', 
   'uses' => 'SpreadsheetController@download'
]);
Run Code Online (Sandbox Code Playgroud)

在你的控制器中:

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;
}
Run Code Online (Sandbox Code Playgroud)

如果您没有该文件,可以将其保存到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");
}
Run Code Online (Sandbox Code Playgroud)

现在您只需要调用端点/spreadsheet/download即可开始下载,但正常情况<a href="/spreadsheet/download">Download</a>可以正常工作.

希望这对你有所帮助.