Laravel 5 import export to excel and csv using maatwebsite

In this post, i will show you how to import excel or CSV to store in database and how to export or download excel or CSV file from database table by maatwebsite. maatwebsite packages through you can easily get data, also you can group by data, also create more than one sheet etc. so now I show you simple example of books table data, you can download in xls, xlsx and csv formate and also you import data in xls, xlsx and CSV format file. In following few step you can implement import and export both function in your project. 

Step 1: Installation



Open your composer.json file and add below line in required package.

Laravel 5

"maatwebsite/excel": "~2.1.0"

Laravel 4

"maatwebsite/excel": "~1.3"

Then, run command composer update

Now open config/app.php file and add service provider and aliases.

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

Config

If you are using Laravel 5 then fire following command:

php artisan vendor: publish
If you are using Laravel 4 then fire following command:

php artisan config:publish maatwebsite/excel
This command will create a config file for excel package.

Step 2: Create Table and Model



In this step, we have to create a migration for items table using Laravel 5 PHP artisan command, so first fire bellow command:

php artisan make:migration create_books_table

After this command, you will find one file in following path database/migrations and you have to put below code in your migration file for creating items table.

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBooksTable extends Migration
{
   public function up()
   {
       Schema::create('books', function (Blueprint $table) {
           $table->increments('id');
           $table->string('title');
           $table->text('description');
           $table->timestamps();
       });
   }
   public function down()
   {
       Schema::drop("books");
   }
}

After create "books" table you should craete book model for books, so first create file in this path app/Book.php and put bellow content in book.php file:

app/Book.php

namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
   public $fillable = ['title','description'];
}

Step 3: Create Route


In this is step we need to create route of import export file. so open your app/Http/routes.php file and add following route.

Route::get('importExport', 'MaatwebsiteDemoController@importExport');
Route::get('downloadExcel/{type}', 'MaatwebsiteDemoController@downloadExcel');
Route::post('importExcel', 'MaatwebsiteDemoController@importExcel');

Step 4: Create Controller


Ok, now we should create new controller as MaatwebsiteDemoController in this path app/Http/Controllers/MaatwebsiteDemoController.php. this controller will manage all impostExport, downloadExcel and importExcel request and return response, so put bellow content in controller file:

app/Http/Controllers/MaatwebsiteDemoController.php

use Input;
use App\Book;
use DB;
use Excel;
class MaatwebsiteDemoController extends Controller
{
                public function importExport()
                {
                                return view('importExport');
                }
                public function downloadExcel($type)
                {
                                $data = Book::get()->toArray();
                                return Excel::create('itsolutionstuff_example', function($excel) use ($data) {
                                                $excel->sheet('mySheet', function($sheet) use ($data)
                        {
                                                                $sheet->fromArray($data);
                        });
                                })->download($type);
                }
                public function importExcel()
                {
                                if(Input::hasFile('import_file')){
                                                $path = Input::file('import_file')->getRealPath();
                                                $data = Excel::load($path, function($reader) {
                                                })->get();
                                                if(!empty($data) && $data->count()){
                                                                foreach ($data as $key => $value) {
                                                                                $insert[] = ['title' => $value->title, 'description' => $value->description];
                                                                }
                                                                if(!empty($insert)){
                                                                                DB::table('books')->insert($insert);
                                                                                dd('Insert Record successfully.');
                                                                }
                                                }
                                }
                                return back();
                }
}

Step 5: Create View


let's create importExport.blade.php(resources/views/importExport.blade.php) for layout and we will write design code here and put following code :

importExport.blade.php

<html lang="en">
<head>
                <title>Import - Export Laravel 5</title>
                <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
</head>
<body>
                <nav class="navbar navbar-default">
                                <div class="container-fluid">
                                                <div class="navbar-header">
                                                                <a class="navbar-brand" href="#">Import - Export in Excel and CSV Laravel 5</a>
                                                </div>
                                </div>
                </nav>
                <div class="container">
                                <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">
                                                <input type="file" name="import_file" />
                                                <button class="btn btn-primary">Import File</button>
                                </form>
                </div>
</body>
</html>

Comments

Popular posts from this blog

Laravel 5 Chart example using Charts Package

Laravel Stats Tracker

PHPMyBackup - A PHP MySQL differential backup script