通过单击按钮保存 PhpSpreadSheet

Saving a PhpSpreadSheet through button click

我正在尝试让我的 Laravel 应用程序下载 excel 文件,其中 phpSpreadSheet 是 PhpExcel 的延续。但到目前为止,我没有任何运气。我首先尝试通过 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");
}

现在您只需调用端点 /spreadsheet/download 即可开始下载,但正常的 <a href="/spreadsheet/download">Download</a> 也可以。

希望对您有所帮助。