How to export data to excel file with laravel 5

Published Date: 25-Nov-2017 | Tags: Laravel 5.5  Import / Export  

This tutorial I want to show you an easy way to export data to excel by using laravel and maatwebsite/excel.

Step 1: Install maatwebsite/excel package.

To install it, please go to terminal or command prompt (for window users), navigate to your project directory, and run this command.

composer require maatwebsite/excel

 

Step 2: How to Export to Excel

Below is the code of exporting customer data to excel file.

$customers = Customer::orderBy('name')->get();
        Excel::create('Customer', function ($excel) use ($customers) {
            $excel->sheet('Sheet 1', function ($sheet) use ($customers) {
                $sheet->appendRow(['ID', 'Name', 'Gender', 'Email', 'Created_at', 'Updated_at']);
                foreach ($customers as $customer) {
                    $sheet->appendRow([
                        $customer->id,
                        $customer->name,
                        $customer->gender,
                        $customer->email,
                        $customer->created_at,
                        $customer->updated_at,
                    ]);
                }
            });
        })->export('xlsx');

Please check maatwebsite/excel website http://www.maatwebsite.nl/laravel-excel/docs for more info.

Hope you can do it.


Demo


Related Posts

© 2018 All Rights Reserved.