How to download an excel file in laravel?

by lindsey.homenick , in category: PHP Frameworks , 4 days ago

How to download an excel file in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 3 days ago

@lindsey.homenick 

To download an excel file in Laravel, you can follow these steps:

  1. First, make sure you have the Maatwebsite/Laravel-Excel package installed in your Laravel project. You can install it using Composer by running the following command:
1
composer require maatwebsite/excel


  1. Next, publish the configuration file by running the following command:
1
php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider"


  1. Create a new controller or use an existing one to handle the file download. In the controller method, you can create an Excel file using the MaatwebsiteExcelExcel facade and return it as a download response. Here is an example:
1
2
3
4
5
6
use MaatwebsiteExcelFacadesExcel;

public function downloadExcelFile()
{
    return Excel::download(new YourExportableClass, 'filename.xlsx');
}


  1. Create a class that implements the FromView or FromCollection interface provided by Laravel Excel. This class will define the data that will be exported to the Excel file. Here is an example using the FromCollection interface:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use MaatwebsiteExcelConcernsFromCollection;
use AppModelsUser;

class UsersExport implements FromCollection
{
    public function collection()
    {
        return User::all();
    }
}


  1. Finally, create a route that points to the controller method for downloading the Excel file. For example:
1
Route::get('/download-excel', [YourController::class, 'downloadExcelFile']);


Now, when you visit the specified route in your application, it will trigger the download of an Excel file containing the data returned by the FromCollection class.