You get a bonus - 1 coin for daily activity. Now you have 1 coin

Example of Export-Import to Laravel 5 in excel and csv using maatwebsite.

Lecture



In this post, I will show you how to import excel or csv for storage in a database and how to export or load an excel or csv file from the maatwebsite database table. maatwebsite packages, you can easily get data, and you can also group data, and also create more than one sheet, etc., so now I will show you a simple example of a data table of elements, you can download xls, xlsx and csv formate, and also import data to xls, xlsx and csv formate. In the next step, you can implement the import and export of both functions in your project. First of all, your browser view will be as follows:

preview:

  Example of Export-Import to Laravel 5 in excel and csv using maatwebsite.

Preivew of Import file:

  Example of Export-Import to Laravel 5 in excel and csv using maatwebsite.

Step 1: Installation

Open the file composer.json and add the line with the required package.

Laravel 5

"maatwebsite / excel": "~ 2.1.0"

Laravel 4

"maatwebsite / excel": "~ 1.3"

Then run com *** at composer update

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

 'providers' => [ 

....

'Maatwebsite \ Excel \ ExcelServiceProvider',

],

'aliases' => [

....

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

],

config

If you are using Laravel 5, then run the following com *** y:

 php artisan vendor: publish 

If you are using Laravel 4, then run the following com *** y:

 php artisan config: publish maatwebsite / excel 

This com *** will create a configuration file for the excel package.

Step 3: Creating the table and model

At this stage we have to create a migration for the table of elements using the *** com at Laravel 5 php artisan, so first execute the com *** at the fire fire:

 php artisan make: migration create_items_table 

After this command, you will find one file in the following database / migration paths, and you will need to add the following code to your migration file to create a table of elements.



 use Illuminate \ Database \ Schema \ Blueprint;
 use Illuminate \ Database \ Migrations \ Migration;
 class CreateItemsTable extends Migration
 {
 public function up ()
 {

 Schema :: create ('items', function (Blueprint $ table) {
 $ table-> increments ('id');
 $ table-> string ('title');
 $ table-> text ('description');
 $ table-> timestamps ();
 });

 }

 public function down ()

 {
 Schema :: drop ("items");
 }
 } 

After the “ Item ” craete table, you must create an Item model for the items, so first create a file in this app / Item.php path and add the following content to the item.php file:

app / Item.php

 

namespace App;

use Illuminate \ Database \ Eloquent \ Model;

class Item extends Model

{

public $ fillable = ['title', 'description'];

}

Step 3: Creating Routes

At this point, we need to create the route of the export export file. so open the app / Http / routes.php file and add the following route.

Route :: get ('importExport', 'MaatwebsiteDemoController @ importExport');

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

Route :: post ('importExcel', 'MaatwebsiteDemoController @ importExcel');

Step 4: Creating the controller

So now we have to create a new controller like MaatwebsiteDemoController in this app / Http / Controllers / MaatwebsiteDemoController.php MaatwebsiteDemoController.php . This controller will manage all the impostExport, downloadExcel and importExcel data and return a response, so add the contents to the controller file below:

app / Http / Controllers / MaatwebsiteDemoController.php



 use Input;
 use App \ Item;
 use DB;
 use Excel;
 class MaatwebsiteDemoController extends Controller

 {

 public function importExport ()

 {

 return view ('importExport');

 }

 public function downloadExcel ($ type)

 {

 $ data = Item :: get () -> toArray ();

 return Excel :: create ('its solutionstuff_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 ('items') -> insert ($ insert);

 dd ('Insert Record successfully.');

 }

 }

 }

 return back ();

 }

 } 

Step 5: Create a presentation

let's create importExport.blade.php (resources / views / importExport.blade.php) for the layout, and we will write the project code here and put the 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-liquid" >

<div class = "navbar-header" >

<a class = "navbar-brand" HREF = "#"> Import - Export to 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 = "ale 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>

So, now we are ready to run this script in the browser, so run the project and test it.

avatar
6.12.2019 12:23

Сайт поправь, админ! Как скопировать последний блок и другие (html)?! Только ссылка на сайт копируется, а как же выделенный текст?! Зачем горизонтальный скрол для комментариев, если есть перенос по словам?

avatar
6.12.2019 12:39

чтобы скопировать как обычно копируете и удаляете то что лишнее скопировалось


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Famworks

Terms: Famworks