How to Export data to Excel file with different format/extension in Laravel 10

By Ved Prakash N | Jan 20, 2024 | Laravel
Share : Whatsapp

https://www.fundaofwebit.com/post/how-to-export-data-to-excel-file-with-different-format-in-laravel-10

How to Export data to Excel file in Laravel 10


In this post, you will learn how to export data from a database table to Excel file with different format / extension in Laravel 10. 

We will create a Form, we will select the Export Format / Extension (.xlsx , .xls, csv, etc.), and download the Excel file.

We will specify / declare the Headings (Column Headings) like Name, Email, Phone, etc.. in the Excel file to be exported.

Let's get started.


Step 1: Install Laravel Excel Package via composer as follows: 

composer require maatwebsite/excel


Step 2: Configure the Package

The Maatwebsite\Excel\ExcelServiceProvider is auto-discovered and registered by default.

If you want to register it yourself, add the ServiceProvider in "config/app.php": ( providers & aliases )

'providers' => [
    // ...
    Maatwebsite\Excel\ExcelServiceProvider::class,
],

'aliases' => [
    // ...
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],


Step 3: To publish the config, run the vendor publish command

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


Note: We will follow with the example of "Customer Detail" to be exported in an Excel file. So I have used Model as a Customer ( app/ Models/ Customer.php )


Step 4: Create a Controller named CustomerController using the below artisan command:

php artisan make:controller CustomerController

After successfully creating the CustomerController, paste the below code in it.

In this controller, write the logic of export excel with different export format / file extensions as follows:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Exports\CustomersExport;
use Maatwebsite\Excel\Facades\Excel;

class CustomerController extends Controller
{
    public function exportDataInExcel(Request $request)
    {
        if($request->type == 'xlsx'){

            $fileExt = 'xlsx';
            $exportFormat = \Maatwebsite\Excel\Excel::XLSX;
        }
        elseif($request->type == 'csv'){

            $fileExt = 'csv';
            $exportFormat = \Maatwebsite\Excel\Excel::CSV;
        }
        elseif($request->type == 'xls'){

            $fileExt = 'xls';
            $exportFormat = \Maatwebsite\Excel\Excel::XLS;
        }
        else{

            $fileExt = 'xlsx';
            $exportFormat = \Maatwebsite\Excel\Excel::XLSX;
        }


        $filename = "customers-".date('d-m-Y').".".$fileExt;
        return Excel::download(new CustomersExport, $filename, $exportFormat);
    }
}


Step 5: Create a Excel Export Class named CustomerExport with the following command:

php artisan make:export CustomerExport

After successfully creating the Import Class, paste the below code in the following path : app/ Exports/ CustomerExport.php

There are different ways to Export data to excel file like:

1. Export Data in Excel Sheet with Headings (Column Names)

<?php

namespace App\Exports;

use App\Models\Customer;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class CustomersExport implements FromCollection, WithHeadings
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return Customer::select('name','email','phone')->get();
    }

    public function headings(): array
    {
        return [
            'Name',
            'Email',
            'Phone',
        ];
    }
}


2. Export Data in Excel Sheet without Headings

<?php

namespace App\Exports;

use App\Models\Customer;
use Maatwebsite\Excel\Concerns\FromCollection;

class CustomersExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return Customer::all();
    }
}


3. Export Data to Excel Sheet from a "Blade View" using "FormView" concern 

<?php

namespace App\Exports;

use App\Models\Customer;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;

class CustomersExport implements FromView
{
    public function view(): View
    {
        return view('customer.export', [
            'customers' => Customer::all()
        ]);
    }
}

Now, while export data to an excel file from a "Blade view" using a FormView concern, you have to create a Blade file in the following path: resources/ views/ customer/ export.blade.php and paste the below code:  

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
        </tr>
    </thead>
    <tbody>
        @foreach($customers as $customer)
            <tr>
                <td>{{ $customer->name }}</td>
                <td>{{ $customer->email }}</td>
                <td>{{ $customer->phone }}</td>
            </tr>
        @endforeach
    </tbody>
</table>


Step 6: Use this below in Form to export / download the excel file as per your requirement. 

<form action="{{ url('customer/export') }}" method="GET">
    <label>Export Customer Data in Excel File</label>
    <div class="input-group mt-2">
        <select name="type" class="form-control" required>
            <option value="">Select Excel Format</option>
            <option value="xlsx">XLSX</option>
            <option value="csv">CSV</option>
            <option value="xls">XLS</option>
        </select>
        <button type="submit" class="btn btn-success">Export</button>
    </div>
</form>


Step 7: Create a Route

Route::get('customer/export', [App\Http\Controllers\CustomerController::class, 'exportDataInExcel']);


That's it. Now, we are ready to export data to an Excel file at : http://localhost:8000/customer/export

I hope it helps you. Thanks for reading.