Laravel 5.6 Import Export to Excel and CSV example
In this post we will give you information about Laravel 5.6 Import Export to Excel and CSV example. Hear we will give you detail about Laravel 5.6 Import Export to Excel and CSV exampleAnd how to use it also give you demo for it if it is necessary.
In this tutorial, I would like to share with you step by step import excel or csv to store in database and how to export or download excel or csv file from database using maatwebsite package in laravel 5.6 application.
Maatwebsite packages through you can easily get data, also you can group by data, also create more then one sheet etc. so now i show you simple example of items table data, you can download in xls, xlsx and csv formate and also you import data in xls, xlsx and csv formate file.
In this example, you have to just follow few step to implement import and export both function in your project. First see your browser preview will become like this:
Preview:
Preview of Import File:
Step 1 : Install Laravel 5.6 Project
first of all, we will install Laravel 5.6 application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Install Maatwebsite Package
In this step we need to install Maatwebsite package via the Composer package manager, so one your terminal and fire bellow command:
composer require maatwebsite/excel
OR
composer require "maatwebsite/excel":"~2.1.0"
Now open config/app.php file and add service provider and aliase.
config/app.php
'providers' => [
....
MaatwebsiteExcelExcelServiceProvider::class,
],
'aliases' => [
....
'Excel' => MaatwebsiteExcelFacadesExcel::class,
],
Step 3: Create Item Table and Model
In this step we have to create migration for items table using Laravel 5.6 php artisan command, so first fire bellow command:
php artisan make:migration create_items_table
After this command you will find one file in following path “database/migrations” and you have to put bellow code in your migration file for create items table.
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
class CreateItemsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('items', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop("items");
}
}
After create “items” table you should create Item model for items, so first create file in this path “app/Item.php” and put bellow content in item.php file:
app/Item.php
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Item extends Model
{
public $fillable = ['title','description'];
}
Step 4: Add Routes
In this step, we need to create route of import export file. so open your “routes/web.php” file and add following route.
routes/web.php
Route::get('importExport', 'MaatwebsiteDemoController@importExport');
Route::get('downloadExcel/{type}', 'MaatwebsiteDemoController@downloadExcel');
Route::post('importExcel', 'MaatwebsiteDemoController@importExcel');
Step 5: Create MaatwebsiteDemoController Controller
In this step, 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
<?php
namespace AppHttpControllers;
use AppItem;
use DB;
use Excel;
use IlluminateHttpRequest;
class MaatwebsiteDemoController extends Controller
{
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function importExport()
{
return view('importExport');
}
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function downloadExcel($type)
{
$data = Item::get()->toArray();
return Excel::create('onlinecode_example', function($excel) use ($data) {
$excel->sheet('mySheet', function($sheet) use ($data)
{
$sheet->fromArray($data);
});
})->download($type);
}
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function importExcel(Request $request)
{
$request->validate([
'import_file' => 'required'
]);
$path = $request->file('import_file')->getRealPath();
$data = Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = ['title' => $value->title, 'description' => $value->description];
}
if(!empty($arr)){
Item::insert($arr);
}
}
return back()->with('success', 'Insert Record successfully.');
}
}
Step 6: Create Blade File
In Last step, let’s create importExport.blade.php(resources/views/importExport.blade.php) for layout and we will write design code here and put following code:
resources/views/importExport.blade.php
<html lang="en">
<head>
<title>Laravel 5.6 Import Export to Excel and csv Example - ItSolutionStuff.com</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
</head>
<body>
<div >
<div >
<div >
<h1>Laravel 5.6 Import Export to Excel and CSV Example - ItSolutionStuff.com</h1>
</div>
<div >
<a href="{{ url('downloadExcel/xls') }}"><button >Download Excel xls</button></a>
<a href="{{ url('downloadExcel/xlsx') }}"><button >Download Excel xlsx</button></a>
<a href="{{ url('downloadExcel/csv') }}"><button >Download CSV</button></a>
<form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 10px;" action="{{ url('importExcel') }}" method="post" enctype="multipart/form-data">
@csrf
@if ($errors->any())
<div >
<a href="#" data-dismiss="alert" aria-label="close">×</a>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@if (Session::has('success'))
<div >
<a href="#" data-dismiss="alert" aria-label="close">×</a>
<p>{{ Session::get('success') }}</p>
</div>
@endif
<input type="file" name="import_file" />
<button >Import File</button>
</form>
</div>
</div>
</div>
</body>
</html>
Now you can check on your laravel 5.6 application with demo file for testing.
Demo Excel File for Testing :Click Here.
I hope it can help you…
Hope this code and post will helped you for implement Laravel 5.6 Import Export to Excel and CSV example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs