Loading Posts...

How To Export Data In Excel and CSV In Laravel 6 | maatwebsite/excel 3.1

How To Export Data In Excel and CSV In Laravel 6 | maatwebsite:excel 3.1

In this tutorial, we will see How To Export Data In Excel and CSV In Laravel 6 | maatwebsite/excel 3.1. If you want to up and running with basic laravel functionality, then go to my other article on this web blog called Laravel 6 Crud Example From ScratchIf you want to Generate PDF In Laravel, then check out Laravel 6 Generate PDF From View Example. For this example, we use the package called maatwebsite/excel version 3.1. So, our Laravel 6 and maatwebsite/excel 3.1.

Export Data In Excel and CSV in Laravel 6

When using the package in your application, it’s good to understand how the package functions behind the scenes. Following the behind-the-scenes will make you feel more comfortable and confident using the maximum potential of the tool.

Laravel Excel 3.1

Laravel Excel is intended at being Laravel-flavoured PhpSpreadsheet: a simple, but an elegant wrapper around PhpSpreadsheet to simplify the exports and imports.

 PhpSpreadsheet is the library written in pure PHP and providing the set of classes that allow us to read from and to write to different type of spreadsheet file formats, like Excel and LibreOffice Calc.

Laravel Excel Features

  1. We can easily export collections to Excel.
  2. We can export queries with automatic chunking for better performance.
  3. We can queue exports for better performance.
  4. We can easily export Blade views to Excel.
  5. We can easily import to collections.
  6. We can read the Excel file in chunks.
  7. We can handle the import inserts in batches.

Requirements

  1. PHP: ^7.0
  2. Laravel: ^5.5
  3. PhpSpreadsheet: ^1.6
  4. PHP extension php_zip enabled
  5. PHP extension php_xml enabled
  6. PHP extension php_gd2 enabled

Step 1: Installation

Require the following package in the composer.json of your Laravel 6 project. The following command will download the package and PhpSpreadsheet.

composer require maatwebsite/excel
➜  laravel6 git:(master) ✗ composer require maatwebsite/excel
Using version ^3.1 for maatwebsite/excel
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
  - Installing markbaker/matrix (1.1.4): Downloading (100%)
  - Installing markbaker/complex (1.4.7): Downloading (100%)
  - Installing phpoffice/phpspreadsheet (1.9.0): Downloading (100%)
  - Installing maatwebsite/excel (3.1.17): Downloading (100%)
phpoffice/phpspreadsheet suggests installing mpdf/mpdf (Option for rendering PDF with PDF Writer)
phpoffice/phpspreadsheet suggests installing tecnickcom/tcpdf (Option for rendering PDF with PDF Writer)
phpoffice/phpspreadsheet suggests installing jpgraph/jpgraph (Option for rendering charts, or including charts with PDF or HTML Writers)
Writing lock file
Generating optimized autoload files
> IlluminateFoundationComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: barryvdh/laravel-dompdf
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: laravel/ui
Discovered Package: maatwebsite/excel
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.
➜  laravel6 git:(master) ✗

Step 2: Configure package

The MaatwebsiteExcelExcelServiceProvider is auto-discovered and registered by default.

If you want to register by yourself, then add the ServiceProvider in config/app.php:

'providers' => [
    /*
     * Package Service Providers...
     */
    MaatwebsiteExcelExcelServiceProvider::class,
]

Excel facade is auto-discovered.

If you want to add it manually, add a Facade in config/app.php:

'aliases' => [
    ...
    'Excel' => MaatwebsiteExcelFacadesExcel::class,
]

If you want to publish a config, run the vendor publish command:

php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider"
➜  laravel6 git:(master) ✗ php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider"
Copied File [/vendor/maatwebsite/excel/config/excel.php] To [/config/excel.php]
Publishing complete.
➜  laravel6 git:(master) ✗

This will create the new config file named config/excel.php.

Step 3: Create model and migration files

Type the following command.

php artisan make:model Disneyplus -m

Now, go to the [timestamp].create_disneypluses_table.php file and add the columns.

public function up()
{
        Schema::create('disneypluses', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('show_name');
            $table->string('series');
            $table->string('lead_actor');
            $table->timestamps();
        });
}

Now, migrate the database using the following command.

php artisan migrate

Step 4: Create a controller and routes

Next step is to create a DisneyplusController.php file.

php artisan make:controller DisneyplusController

Now, add the two routes inside the routes >> web.php file.

// web.php

Route::get('disneyplus', '[email protected]')->name('disneyplus.create');
Route::post('disneyplus', '[email protected]')->name('disneyplus.store');

Now, create two methods inside the DisneyplusController.php file.

Step: 5 Create a form blade file for input the data

Now, inside the views folder, create one file called form.blade.php file. Add the following code.

@extends('layout')

@section('content')

Add Disneyplus Shows
@if ($errors->any())
    @foreach ($errors->all() as $error)
  • {{ $error }}
  • @endforeach

@endif
@csrf
@endsection

 

Step 6: Store data in the database

Now, we will write the two functions inside the DisneyplusController.php file.

validate([
            'show_name' => 'required|max:255',
            'series' => 'required|max:255',
            'lead_actor' => 'required|max:255',
        ]);
        Disneyplus::create($validatedData);
   
        return redirect('/disneyplus')->with('success', 'Disney Plus Show is successfully saved');
    }
}

So, in the above file, first, we have shown the form file, and then inside the store function, we check for validation and then store the data into the database.

Also, add the fillable fields inside the Disneyplus.php model file.

Now, go to this route: http://laravel6.test/disneyplus or http://localhost:8000/disneyplus

You will see one form. Try to save the data, and if everything in the code is right, then, you will see one entry in the database.

Step: 7 Create a view file for display the data.

Before we create a view file, we need to add one route inside the web.php.

// web.php

Route::get('disneyplus/list', '[email protected]')->name('disneyplus.index');

Now, create a view file called list.blade.php file. Add the following code.

@extends('layout')
@section('content')

    @foreach($shows as $show)
    
    @endforeach
  
ID Show Name Series Lead Actor Action
{{$show->id}} {{$show->show_name}} {{$show->series}} {{$show->lead_actor}}
@endsection

Now, add the code inside the index() function of DisneyplusController.php file.

public function index()
{
        $shows = Disneyplus::all();

        return view('list', compact('shows'));
}

Now, go to the http://laravel6.test/disneyplus/list or http://localhost:8000/disneyplus/list

You will see the listing of the shows.

Step 8: Create Exports class

You may do this by using the make:export command.

php artisan make:export DisneyplusExport --model=Disneyplus

The file can be found in app/Exports directory.

The file DisneyplusExport.php is following.

If you prefer to create a export manually, you can build the following in app/Exports.

Step 9: Write the export function

Inside the DisneyplusController.php file, add the following code.

// DisneyplusController.php

use AppDisneyplus;
use AppExportsDisneyplusExport;
use MaatwebsiteExcelFacadesExcel;

public function export() 
{
        return Excel::download(new DisneyplusExport, 'disney.xlsx');
}

So, our final file looks like below.

validate([
            'show_name' => 'required|max:255',
            'series' => 'required|max:255',
            'lead_actor' => 'required|max:255',
        ]);
        Disneyplus::create($validatedData);
   
        return redirect('/disneyplus')->with('success', 'Disney Plus Show is successfully saved');
    }

    public function index()
    {
        $shows = Disneyplus::all();

        return view('list', compact('shows'));
    }

    public function export() 
    {
        return Excel::download(new DisneyplusExport, 'disney.xlsx');
    }
}

Finally, add the route to be able to access the export:

// web.php

Route::get('export', '[email protected]');

Also, add the link to the Export inside the list.blade.php file.

@foreach($shows as $show)
    
      {{$show->id}}
      {{$show->show_name}}
      {{$show->series}}
      {{$show->lead_actor}}
      Export
    
@endforeach

Okay, now finally go to the http://laravel6.test/disneyplus/list, and now you can see one link called Export.

Click on the Export link, and you will see the disney.xlsx file inside your Download folder.

Exporting collections in CSV in Laravel 6

By default, the export format is determined by the extension of the file.

public function export() 
{
        return Excel::download(new DisneyplusExport, 'disney.csv');
}

It will download the CSV file.

If you want to configure the export format explicitly, you can pass it through as 2nd parameter.

You can find more details about export in different formats on this link.

Finally, How To Export Data In Excel and CSV In Laravel 6 | maatwebsite/excel 3.1 is over.

The post How To Export Data In Excel and CSV In Laravel 6 | maatwebsite/excel 3.1 appeared first on AppDividend.

Get Free Email Updates!

Signup now and receive an email once I publish new content.

I agree to have my personal information transfered to MailChimp ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.

user

The author didnt add any Information to his profile yet

Loading Posts...