Ad

Download XLSX File On Anchor Link Click In Laravel 5.2

- 1 answer

i am trying to export data using Laravel Excel. I have integrated the Laravel excel, but finding an issue in downloading of button click only, NOT AUTO DOWNLOAD.

Here is how my view looks like:

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" 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

I have a helper method to download the file and here is how my helper looks like:

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

I dont want to store the file to any local storage. I just want the file to be download only when i click on the link instead of auto download. There are certain times when my data keep changing as per the table name in my database.

Any way i can achieve this?

Thank you!

Ad

Answer

According to documentation for Laravel Excel:

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

You don't need to use neither ->export nor ->download methods unless you want to start a download process.

First you do need is to store it on the server:

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.

Here is an example:

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
        // ...
    }
}

If you want to use a custom storage path (e.g. to separate the files per client), you can set the folder as the second parameter.

->store('xls', storage_path('excel/exports'));
Ad
source: stackoverflow.com
Ad