通过单击按钮保存PhpSpreadSheet [英] Saving a PhpSpreadSheet through button click

查看:145
本文介绍了通过单击按钮保存PhpSpreadSheet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让我的Laravel应用使用 phpSpreadSheet 延续PhpExcel来下载excel文件 .但是到目前为止,我还没有运气.我首先尝试通过onClick进行Axios调用,但这没有用,因为不允许JS保存内容.之后,我尝试将按钮附加到Laravel动作上,这只是打开了一个空白页面.

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

推荐答案

首先,您需要在路由中设置一个端点,以使用ajax(在您的情况下为axios)对其进行调用:

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'
]);

在您的控制器中:

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: //输出:

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

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

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.

希望这对您有所帮助.

这篇关于通过单击按钮保存PhpSpreadSheet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆