通过按钮单击保存PhpSpreadSheet

前端之家收集整理的这篇文章主要介绍了通过按钮单击保存PhpSpreadSheet前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试让我的Laravel应用程序下载一个带有 phpSpreadSheet延续PHPExcel的excel文件.但到目前为止,我没有任何运气.我首先尝试通过onClick进行Axios调用,但由于不允许JS保存,因此无效.之后我尝试将按钮附加到Laravel动作,这只是打开一个空页面.

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

首先,您需要在路由中设置端点以使用ajax(在您的情况下为axios)调用它:
Route::get('spreadsheet/download',[
   'as' => 'spreadsheet.download','uses' => 'SpreadsheetController@download'
]);

在你的控制器中:

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;
}

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

现在你只需要调用端点/电子表格/下载来开始下载,但是正常的< a href =“/ spreadsheet / download”>下载< / a>会工作.

希望这对你有所帮助.

猜你在找的PHP相关文章