An eloquent way of importing and exporting Excel and CSV files inLaravel 5.* with the power of PHPOffice’s PHPExcel
Installation

Require this package in your composer.json and update composer. This will download the package and PHPExcel of PHPOffice.

"maatwebsite/excel": "~2.0"

After updating composer, add the ServiceProvider to the providers array in app/config/app.php

'Maatwebsite\Excel\ExcelServiceProvider',

You can use the facade for shorter code. Add this to your aliasses:

'Excel' => 'Maatwebsite\Excel\Facades\Excel',

The class is binded to the ioC as excel

$excel = App::make('excel');

To publish the config settings in Laravel 5 use:

php artisan vendor:publish

This will add an excel.php config file to your config folder.
Importing a file

To start importing a file, you can use ->load($filename). The callback is optional.

Excel::load('file.xls', function($reader) {

// reader methods

});

ExcelFile injections

Following the Laravel 5.0 philosophy with its new awesome FormRequest injections, we introduce you ExcelFile injections.
ExcelFile class

This class is a wrapper for a file on your server. Inside the getFile() method you return the filename and it’s location. Inside the getFilters() method you can enable filters, like the chunk filter.

class UserListImport extends \Maatwebsite\Excel\Files\ExcelFile {

public function getFile()
 {
 return storage_path('exports') . '/file.csv';
 }

public function getFilters()
 {
 return [
 'chunk'
 ];
 }

}

If you want to have the getFile() dynamic based on user’s input, you can easily do:

public function getFile()
 {
 // Import a user provided file
 $file = Input::file('report');
 $filename = $this->doSomethingLikeUpload($file);

// Return it's location
 return $filename;
 }
Advertisements