How to export data in Excel using Laravel

AuthorHariom Prajapati

Pubish Date02 Jul 2022

categoryLaravel

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 .

 

Step 1- Install Laravel Maatwebsite Excel

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,
],

 

Step 3- Run below command for publish the vendor file

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config

 

 

 

Step 4 – Create  'users' table in database

image

 

User table data

image

 


Step 5- Create model for User 

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

 

step 6 – Create route 

Route::get('users_export', 'UserController@export');    

 

Step 7 – create   controller  

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

 

Step 8 – run php artisan serve

image

Then, go to your browser and simply run the below url

http://127.0.0.1:8000/users_export

 

OUTPUT

image

 

Here users.xlsx file downloaded

image

 

Comments 0

Leave a comment