How to download xlsx file in laravel?

535 Views Asked by At

I use the library as a means of generating Excel documents. Only I need to either save the file to the root/storage/app/public/export/file.xlsx directory, or immediately download the file in the browser. Everything is implemented in Laravel 9. How can I write the code correctly?

My code, now:

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
...
    $spreadsheet = new Spreadsheet();
    $activeWorksheet = $spreadsheet->getActiveSheet();
    $activeWorksheet->setCellValue('A1', 'Hello, World!');
    $writer = new Xlsx($spreadsheet);
    $writer->save("file.xlsx");

The file is saved to a folder 'public'.

2

There are 2 best solutions below

0
Khayam Khan On

If your file is saved in the public folder, you can download it easily.

return response()->download(public_path('file_path'));

A more similar question is already here. Please have a read.

0
Herrys Aghista Rachman On

If you want to add into storage, use the storage feature,

$originalName = $yourfilename;
$path = "/public/export/".$originalName;
Storage::disk('local')->put($path, file_get_contents($yourfile));

The storage::disk('local') setting is in config/filesystem.php, and you can customise the path you want. You can see that default path is going to storage/app.

Or if you want download it directly, you can use datatables of yajra at your view. You can export it as dpf, Excel, and xlsx.

$(document).ready(function() {
    $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    } );
} );

Here are the references: datatable export