In this tutorial we will learn how to export dynamic data in excel file with heading using laravel.
If you do not know how to install laravel then click here to install laravel .
Open your CMD and just run this command to install this package.
composer require maatwebsite/excel
Step 2- Now, go to config\app.php
Link installed package in app.php file
'providers' => [
....
Maatwebsite\Excel\ExcelServiceProvider::class,
],
'aliases' => [
....
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
User table data
php artisan make:model User
Then, run this command in CMD to generate UserExport.php file
php artisan make:export UserExport --model=User
Now this file has been created in the app folder, Generated file path is app/export/UserExport.php.
This is our UserExport.php file
<?php
namespace App\Exports;
use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class UserExport implements FromCollection ,WithHeadings
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return User::select('name', 'email', 'age')->get();
}
public function headings(): array
{
return [
'Name', 'Email ID','Age'
];
}
}
Route::get('users_export', '[email protected]');
php artisan make:controller UserController
UserController.php
<?php
namespace App\Http\Controllers;
use App\Exports\UserExport;
class UserController extends Controller
{
Function export(){
return Excel::download(new UserExport(), 'users.xlsx');
}
}
Then, go to your browser and simply run the below url
http://127.0.0.1:8000/users_export
OUTPUT
Here users.xlsx file downloaded