Laravel 8 Import Export Excel & CSV File




Laravel Excel is designed at being a Laravel-flavoured PhpSpreadsheet. It’s a manageable and stylish wrapper round PhpSpreadsheet to simplify exports and imports. PhpSpreadsheet is a php based mostly library that allows you to learn and write completely different spreadsheet file codecs, like Excel and LibreOffice Calc. Laravel Excel has the next options:

  1. Simply export collections to Excel.
  2. Export queries with computerized chunking for higher efficiency.
  3. Queue exports for higher efficiency.
  4. Simply export Blade views to Excel.
  5. Simply import to collections.
  6. Learn the Excel file in chunks.
  7. Deal with the import inserts in batches.

If you wish to create straightforward import and export, excel file performance, this laravel maatwebsite/excel tutorial is finest for you.

On the finish of this tutorial, it is possible for you to to obtain or import excel & CSV information instantly from the database in laravel software.



Necessities

  1. PHP: ^7.2|^8.0
  2. Laravel: ^5.8
  3. PhpSpreadsheet: ^1.15
  4. PHP extension php_zip enabled
  5. PHP extension php_xml enabled
  6. PHP extension php_gd2 enabled
  7. PHP extension php_iconv enabled
  8. PHP extension php_simplexml enabled
  9. PHP extension php_xmlreader enabled
  10. PHP extension php_zlib enabled



Step 1: Set up Laravel Mission

First, open Terminal and run the next command to create a recent laravel undertaking:

composer create-project --prefer-dist laravel/laravel laravel-excel
Enter fullscreen mode

Exit fullscreen mode

or, when you’ve got put in the Laravel Installer as a world composer dependency:

laravel new laravel-excel
Enter fullscreen mode

Exit fullscreen mode



Step 2: Configure Database Particulars

After, Set up Go to the undertaking root listing, open .env file, and set database element as comply with:

DB_CONNECTION=mysql 
DB_HOST=127.0.0.1 
DB_PORT=3306 
DB_DATABASE=<DATABASE NAME>
DB_USERNAME=<DATABASE USERNAME>
DB_PASSWORD=<DATABASE PASSWORD>
Enter fullscreen mode

Exit fullscreen mode



Step 3: Set up maatwebsite/excel bundle

You possibly can set up Laravel Excel by way of composer. You’ve got to run this command for the set up.

composer require maatwebsite/excel
Enter fullscreen mode

Exit fullscreen mode



Register Plugin’s Service in Suppliers & Aliases

You possibly can have the next code positioned contained in the config/app.php file.

'suppliers' => [
  MaatwebsiteExcelExcelServiceProvider::class,
 ],  

'aliases' => [ 
  'Excel' => MaatwebsiteExcelFacadesExcel::class,
], 
Enter fullscreen mode

Exit fullscreen mode

Execute the seller, publish the command, and publish the config.

php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider" --tag=config
Enter fullscreen mode

Exit fullscreen mode



Step 4: Generate Faux Information and Migrate Desk

Within the First step, We migrate the consumer desk. After migration run efficiently We moved to the second step.

php artisan migrate
Enter fullscreen mode

Exit fullscreen mode

Within the Second Step, We generate the faux report. Right here We use tinker to generate the faux information. You need to use a unique technique as of your requirement.

php artisan tinker
Enter fullscreen mode

Exit fullscreen mode

After Opening the tinker, you’ll want to run this command to generate the faux information in our database.

Person::manufacturing facility()->depend(100)->create();
Enter fullscreen mode

Exit fullscreen mode



Step 5: Create a Routes

On this step, We are going to add a path to deal with requests for import and export information.

use AppHttpControllersUserController;

Route::get('/file-import',[UserController::class,'importView'])->title('import-view');
Route::publish('/import',[UserController::class,'import'])->title('import');
Route::get('/export-users',[UserController::class,'exportUsers'])->title('export-users');
Enter fullscreen mode

Exit fullscreen mode



Step 6: Create Import Class

Maatwebsite gives a technique to construct an import class and now we have to make use of it within the controller. So it will be an effective way to create a brand new Import class. So it’s a must to run the next command and alter the next code on that file:

php artisan make:import ImportUser --model=Person
Enter fullscreen mode

Exit fullscreen mode

app/Imports/ImportUser.php

<?php

namespace AppImports;

use AppModelsUser;
use MaatwebsiteExcelConcernsToModel;

class ImportUser implements ToModel
{
    /**
    * @param array $row
    *
    * @return IlluminateDatabaseEloquentModel|null
    */
    public operate mannequin(array $row)
    {
        return new Person([
            'name' => $row[0],
            'e-mail' => $row[1],
            'password' => bcrypt($row[2]),
        ]);
    }
}
Enter fullscreen mode

Exit fullscreen mode

Right here you possibly can see map CSV or excel column worth to our Eloquent Mannequin. It’s good to format that CSV or excel column as you map in your import class.



Step 7: Create Export Class

Maatwebsite gives a technique to construct an export class and now we have to make use of it within the controller. So it will be an effective way to create a brand new export class. So it’s a must to run the next command and alter the next code on that file:

php artisan make:export ExportUser --model=Person
Enter fullscreen mode

Exit fullscreen mode

app/Exports/ExportUser.php

<?php

namespace AppExports;

use AppModelsUser;
use MaatwebsiteExcelConcernsFromCollection;

class ExportUser implements FromCollection
{
    /**
    * @return IlluminateSupportCollection
    */
    public operate assortment()
    {
        return Person::choose('title','e-mail')->get();
    }
}
Enter fullscreen mode

Exit fullscreen mode



Step 8: Create Controller

Subsequent, We’ve to create a controller to show a type to add CSV or excel file information. Let’s Create a controller named UserController utilizing the command given beneath:

php artisan make:controller UserController
Enter fullscreen mode

Exit fullscreen mode

As soon as the above command executed, it’ll create a controller file UserController.php in app/Http/Controllers listing. Open UserController.php file and put this code into that file.

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use MaatwebsiteExcelFacadesExcel;
use AppImportsImportUser;
use AppExportsExportUser;
use AppModelsUser;

class UserController extends Controller
{
    public operate importView(Request $request){
        return view('importFile');
    }

    public operate import(Request $request){
        Excel::import(new ImportUser, $request->file('file')->retailer('information'));
        return redirect()->again();
    }

    public operate exportUsers(Request $request){
        return Excel::obtain(new ExportUser, 'customers.xlsx');
    }
}
Enter fullscreen mode

Exit fullscreen mode



Step 9: Create Blade / View Information

We’ve reached the final step. On the whole, right here we have to formulate the view for dealing with importing and exporting via the frontend. Create a sources/views/importFile.blade.php file to arrange the view. Place the next code contained in the blade view file:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta title="viewport" content material="width=device-width, initial-scale=1">
    <title>Laravel 8 Import Export Excel & CSV File - TechvBlogs</title>
    <hyperlink rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>

<physique>
    <div class="container mt-5 text-center">
        <h2 class="mb-4">
            Laravel 8 Import Export Excel & CSV File - <a href="https://techvblogs.com/weblog/laravel-import-export-excel-csv-file?ref=repo" goal="_blank">TechvBlogs</a>
        </h2>
        <type motion="{{ route('import') }}" technique="POST" enctype="multipart/form-data">
            @csrf
            <div class="form-group mb-4">
                <div class="custom-file text-left">
                    <enter kind="file" title="file" class="custom-file-input" id="customFile">
                    <label class="custom-file-label" for="customFile">Select file</label>
                </div>
            </div>
            <button class="btn btn-primary">Import Customers</button>
            <a category="btn btn-success" href="{{ route('export-users') }}">Export Customers</a>
        </type>
    </div>
</physique>

</html>
Enter fullscreen mode

Exit fullscreen mode



Run Laravel Utility

Lastly, now we have to run the Laravel software, for this, now we have to go to the command immediate, and write the next command:

php artisan serve
Enter fullscreen mode

Exit fullscreen mode

After executing this command, Open http://localhost:8000/file-import in your browser.

Thanks for studying this weblog.



Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#Laravel #Import #Export #Excel #CSV #File