Excel and csv import export using maatwebsite in laravel example

We are share with you in this tutorials aboute excel/csv file export and import in laravel usign one of the best laravel package maatwebsite/excel. maatwebsite/excel is provide large functionality of excel or csv file import and exort in laravel.

When you are working on very larg ERP and e-commerce related product in laravel framwork then you are need to some time excel import and export functionality for reduce data entry in database and easyly any databe data export from database table to excel file and csv file for backup purpose.

So, how to implement excel import export functionality in your laravel application usinf maatwebsite/excel package. we are write here some basice step for implement and integrate excel import and export functionality in laravel.

In this demo example e are create one post table and we are export this table data into excel or csv file and also import excel file data into this posst table. our table look like this..


+----+-------+-------------+
| id | title | description |
+----+-------+-------------+
|    |       |             |
+----+-------+-------------+
|    |       |             |
+----+-------+-------------+        

Follow Bellow Few Step:
  • 1) Install Required Packages
  • 2) Configuration app.php file
  • 3) Create route
  • 4) Create controller
  • 5) Create view file
Step : 1 Install Required Packages

First we are need to install maatwebsite/excel package in your laravel application. here is to way for install package in laravel

First way :

Open your composer.json file and simply put into it package name and package version like that


"require": {
    "php": ">=5.6.4",
    "laravel/framework": "5.4.*",
    "laravel/tinker": "~1.0",
    "maatwebsite/excel": "~2.1.0"
},

After put package into composer.json file then after save it and run following command and your required package install in your laravel application.


composer update

Second way :

In second methos for install any package it very easy. open terminal and run following command then you can install your any required package.


composer require maatwebsite/excel

Step : 2 Configuration app.php file

After installing package we are need to configure php.php file. open your confige/app.php file and changes some following


'providers' => [
	....
	'Maatwebsite\Excel\ExcelServiceProvider',
],
'aliases' => [
	....
	'Excel' => 'Maatwebsite\Excel\Facades\Excel',
],

Done above configuration then run following command :


php artisan vendor:publish

Step : 3 Create route

now we are create following route


// Route for view/blade file.
Route::get('importExport', 'MaatwebsiteController@importExport');
// Route for export/download tabledata to .csv, .xls or .xlsx
Route::get('downloadExcel/{type}', 'MaatwebsiteController@downloadExcel');
// Route for import excel data to database.
Route::post('importExcel', 'MaatwebsiteController@importExcel');

Step : 4 Create controller

Now create MaatwebsiteController.php file in app/Http/Controllers folders look like.


<?php
namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Input;
use App\Post;
use DB;
use Session;
use Excel;

class MaatwebsiteController extends Controller
{
    public function importExport()
    {
        return view('importExport');
    }
    public function downloadExcel($type)
    {
        $data = Post::get()->toArray();
        return Excel::create('laravelcode', function($excel) use ($data) {
            $excel->sheet('mySheet', function($sheet) use ($data)
            {
                $sheet->fromArray($data);
            });
        })->download($type);
    }
    public function importExcel(Request $request)
    {
        if($request->hasFile('import_file')){
            Excel::load($request->file('import_file')->getRealPath(), function ($reader) {
                foreach ($reader->toArray() as $key => $row) {
                    $data['title'] = $row['title'];
                    $data['description'] = $row['description'];

                    if(!empty($data)) {
                        DB::table('post')->insert($data);
                    }
                }
            });
        }

        Session::put('success', 'Youe file successfully import in database!!!');

        return back();
    }
}

Step : 5 Create view/blade file

After done create above controlle then after we need to crerate one view file for layout. so create importExport.blade.php file in your laravel application's resources/views folders look like.


@extends('layouts.app')

@section('content')
<div class="container">
	@if($message = Session::get('success'))
		<div class="alert alert-info alert-dismissible fade in" role="alert">
	      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
	        <span aria-hidden="true">×</span>
	      </button>
	      <strong>Success!</strong> {{ $message }}
	    </div>
	@endif
	{!! Session::forget('success') !!}
	<br />
	<a href="{{ URL::to('downloadExcel/xls') }}"><button class="btn btn-success">Download Excel xls</button></a>
	<a href="{{ URL::to('downloadExcel/xlsx') }}"><button class="btn btn-success">Download Excel xlsx</button></a>
	<a href="{{ URL::to('downloadExcel/csv') }}"><button class="btn btn-success">Download CSV</button></a>
	<form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 10px;" action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
		{{ csrf_field() }}
		<input type="file" name="import_file" />
		<button class="btn btn-primary">Import File</button>
	</form>
</div>
@endsection

Now we are ready to run our example so run bellow command ro quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/importExport

We are hope it can help you...

 Prev post

Next post