How to export data to excel in laravel?

Member

by charles , in category: PHP , 2 years ago

How to export data to excel in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by marina , a year ago

@charles  You can export data to excel in Laravel using the maatwebsite/excel package. This package helps you export data to an Excel or CSV file in a few simple steps.


Here is a controller as an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<?php

use Maatwebsite\Excel\Facades\Excel;

public function export() {

    $data = Item::get()->toArray();

    return Excel::create('items_list', function($excel) use ($data) {
        $excel->sheet('sheet_1', function($sheet) use ($data) {
            $sheet->fromArray($data);
        });
    })->download();
}


Add the Maatwebsite\Excel\ExcelServiceProvider::class, to the providers array in config/app.php like this:

1
2
3
4
5
6
'providers' => [
    /*
     * Package Service Providers...
     */
    Maatwebsite\Excel\ExcelServiceProvider::class,
]


Publish the vendor by running in the terminal:

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


You can install the package using composer, run the following command in the terminal:

1
composer require maatwebsite/excel

Member

by anibal , a year ago

@charles 

To export data to Excel in Laravel, you can use the Laravel Excel package. This package provides a simple way to export data to Excel and other spreadsheet formats.


Here are the steps to export data to Excel using Laravel Excel:

  1. Install Laravel Excel package using composer:
1
composer require maatwebsite/excel


  1. After installing the package, you can create a new export class to define the data to be exported. You can create the export class using the following artisan command:
1
php artisan make:export User***port --model=User


This command will create a new export class User***port in the app/Exports directory.

  1. Define the data to be exported in the query() method of the export class. For example, if you want to export all users, you can write:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use AppModelsUser;
use MaatwebsiteExcelConcernsFromQuery;

class User***port implements FromQuery
{
    public function query()
    {
        return User::query();
    }
}


  1. To export the data, you can use the download() method of the Excel facade. For example, you can create a new route to export users as follows:
1
2
3
4
5
6
use AppExportsUser***port;
use MaatwebsiteExcelFacade***cel;

Route::get('/export-users', function () {
    return Excel::download(new User***port, 'users.xlsx');
});


This will create a new Excel file named users.xlsx and download it to the user's browser.


Note: You can customize the export format, styling, and other options using the Laravel Excel package. Please refer to the package documentation for more details.