在锚 link 上下载 XLSX 文件点击 Laravel 5.2

Download XLSX file on anchor link click in Laravel 5.2

我正在尝试使用 Laravel Excel 导出数据。我已经集成了 Laravel excel,但在仅单击按钮而不是自动下载时发现问题。

这是我的观点:

<a href="{{Export::exportXLSX('users', $users)}}" class="btn btn-default btn-sm">
                                    <i class="fa fa-file-excel-o"></i> Export Users </a> 

// here $users is the array return from tbl_users through UsersController

我有一个下载文件的辅助方法,我的辅助方法如下所示:

class Export
{
    public static function exportXLSX($filename, $data){
        $filename = $filename.'-'.Carbon::now();
        Excel::create($filename, function($excel) use($data) {
            $excel->sheet('Sheetname', function($sheet) use($data) {
                $sheet->fromArray($data);
            });
        })->export('xlsx');
    }
}

我不想将文件存储到任何本地存储。我只想在单击 link 时才下载文件,而不是自动下载。有时我的数据会根据数据库中的 table 名称不断变化。

我有什么办法可以做到这一点?

谢谢!

根据 documentation 对于 Laravel Excel:

To download the created file, use ->export($ext) or ->download($ext).

您不需要使用 ->export->download 方法,除非您想开始下载过程。

首先你需要将它存储在服务器上:

To store the created file on the server, use ->store($ext, $path = false, $returnInfo = false) or ->save().

If you want to return storage information, set the third paramter to true or change the config setting inside export.php.

这是一个例子:

class Export
{
    public static function exportXLSX($filename, $data){
        $filename = $filename.'-'.Carbon::now();
        $storage_info = Excel::create($filename, function($excel) use($data) {
            $excel->sheet('Sheetname', function($sheet) use($data) {
                $sheet->fromArray($data);
            });
        })->store('xls', false, true);

        // Work with $storage_info->full parameter
        // ...
    }
}

如果您想使用自定义存储路径(例如,为每个客户端分隔文件),您可以将文件夹设置为第二个参数。

->store('xls', storage_path('excel/exports'));