Excel export in laravel
Initially, We are going to create a fresh laravel project. It is totally optional, If you already have a project running in your system.
composer create-project laravel/laravel --prefer-dist excelexport
And then write the below command to get into the project,
cd excelexport
Install maatwebsite/excel
package which helps us to export the data’s in excel format.
composer require maatwebsite/excel
The below codes are needed to be updated in ‘config/app.php’ for package configuration purpose.
'providers' => [
/*
* Package Service Providers...
*/
Maatwebsite\Excel\ExcelServiceProvider::class,
]'aliases' => [
...
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]
And then run the below command to publish whatever you have configured till now,
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
Once If you run the command. A file ‘config/excel.php’ will be created. With that you can identify whether the configuration is properly published or not.
And then you can write a CRUD operation. So that you can create some data that needs to be export. Refer the below article to write a API CRUD along with the validation.
In the above CRUD tutorial, I have done a CRUD operations in products. And I am going to create an export file for the products using the below command.
php artisan make:export ProductsExport --model=Products
Now a file will be created on ‘app/Exports/ProductsExport’ in which you can configure the things that needed to be exported.
<?phpnamespace App\Exports;use App\Models\Products;
use Maatwebsite\Excel\Concerns\FromCollection;class ProductsExport implements FromCollection
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return Products::all();
}
}
And the ‘App\Exports\ProductsExport’ has been imported in a controller where we will be writing code to export the datas in the excel format or in the csv format.
- Excel format
use App\Exports\ProductsExport;
use Maatwebsite\Excel\Facades\Excel;public function export()
{
return Excel::download(new ProductsExport, 'products.xlsx');
}
2. CSV format
public function export()
{
return Excel::download(new ProductsExport, 'products.csv');
}
Now we are going to create a ‘route’ in ‘web.php’ that creates an url that can be typed in the browser’s address bar to get the excel or csv file downloaded.
use App\Http\Controllers\ProductsController;Route::get(‘exportexcel’, [ProductsController::class, ‘export’]);
Finally run the laravel application and type ‘127.0.0.1:8000/exportexcel’ to get the file downloaded.
Thank you for reading!!😀