Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to Export or Convert Html to Excel or CSV in laravel 8 9

How to Export or Convert Html to Excel or CSV in laravel 8 / 9?

Aman Jain, May 6, 2022May 13, 2022

Excel or CSV are used to store large set of data to analyses and for reporting. In this article we will learn to export excel or CSV in laravel. This tutorial is best fit to you if you want to understand the basic of export of database table content with custom logic.

Laravel maatwebsite/excel uses phpspreadsheet to simplify the task of import and export. maatwebsite/excel package is wrapper around PhpSpreadsheet package. It gives much more flexibility and easy to use PhpSpreadsheet package through its Export object and encapsulates all logic.

In this example we will create a simple example to export database table in excel format. For this we will create a database, table, model, controller and simple view for html.

Let’s understand Import and export Excel or CSV in laravel 8 / 9 with simple example

Step 1 : Install the package

I assume the you have already installed the laravel and basic connection of it like database connection and composer.

Now install the package using composer in laravel root directory, open the terminal in laravel root directory and run below command to install maatwebsite/excel the package. This package has good stars on github and has lot of fan base of artisans

composer require maatwebsite/excel

Register Providers & Aliases

Add the following code the config/app.php file

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

Step 2 : Create a table, model and fill data

Now, for an example i am creating here a table using migration and then i am going to fill the data in it, so create model and migration

php artisan make:model Article -m

this will generate the model and migration file

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use HasFactory;
    
}

and migration file database/migrations/timestamp_create_articles_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
     public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();;
            $table->string('title');
            $table->string('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

and then migrate the migration

php artisan migrate

Now create seeder in database/seeders/DatabaseSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

// Import DB and Faker services
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create();

    	for ($i=0;$i<=100;$i++) {
            DB::table('articles')->insert([
                'title' => $faker->name,
                'body' => $faker->text,
                'email' => $faker->email,
                'updated_at' =>$faker->datetime,
                'created_at' => $faker->datetime              
            ]);
        }
        
    }
}

Run Seeder in command line

php artisan db:seed

Step 3 : Create Export Class

In new version of maatwebsite module it’s required to create a class for each export and we need to implement Export interface in class, then we can use this class in our controller to export or download

So create a class by following artisan command

php artisan make:export ArticlesExport --model=Article

This command will create the following file in path app/Exports/ArticlesExport.php.

<?php
namespace App\Exports;
use App\Models\Article;
use Maatwebsite\Excel\Concerns\FromCollection;
class ArticlesExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return Article::all();
    }
}

Step 3 : Create controller

Let’s create a controller and add a methods showArticle and exportArticles

php artisan make:controller ArticleController

and add the below code

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Article;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\ArticlesExport;

class ArticleController extends Controller {
    // Show products
    public function showArticle(Request $request){

     // added searching as well
      $articles = Article::when($request->has("title"),function($q)use($request){
            return $q->where("title","like","%".$request->get("title")."%");
        })->get();
     // or
     //  $articles = Article::all();

      
       return view('articles.article',['articles'=>$articles]);
    }

    function exportArticles(){
       
        $excel = Excel::download(new ArticlesExport, 'article-collection.xlsx');
        return $excel;
      
    }
      
}

here we added showArticle method to show the list of articles and exportArticle to export the article on the condition of request params.

Step 5 : Create the views

Create a view resource/articles/article.blade.php

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

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Readerstacks Export or Convert Html to Excel or CSV in laravel 8 / 9</title>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />

</head>

<body class="antialiased">
  <div class="container">
    <!-- main app container -->
    <div class="readersack">
      <div class="container">
        <div class="row">
          <div class="col-md-12 ">
            <h3>Export or Convert Html to Excel or CSV in laravel 8 / 9 - Readerstacks</h3>
           
            <a class='btn btn-info' href='{{url("article-export")}}'>Export Excel</a>
           
            <div id="search">

              <form id="searchform" name="searchform">
                <div class="form-group">
                  <label>Search by Title</label>
                  <input type="text" name="title" value="{{request()->get('title','')}}" class="form-control" />
                 

                </div>
                <div class="form-group">
                  <label>Search by body</label>
                  <input type="text" name="body" value="{{request()->get('body','')}}" class="form-control" />


                </div>
                <button class='btn btn-success' >Search</button>
              </form>


            </div>
            
            <div id="pagination_data">
              <table class="table table-striped table-dark table-bordered">
                <tr>
                  <th>Sr No.</th>
                  <th>Title</th>

                  <th>Body</th>

                  <th>Date</th>
                </tr>
                @foreach($articles as $article)
                <tr>
                  <td>{{$article->id}}</td>
                  <td>{{$article->title}}</td>

                  <td>{{substr($article->body,0,50)}}</td>
                  <td>{{$article->created_at}}</td>
                </tr>
                @endforeach
              </table>
              
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- credits -->
    <div class="text-center">
      <p>
        <a href="#" target="_top">Export or Convert Html to Excel or CSV in laravel 8 / 9</a>
      </p>
      <p>
        <a href="https://readerstacks.com" target="_top">readerstacks.com</a>
      </p>
    </div>
  </div>
  
</body>

</html>

Step 6 : Create Routes

Last step is to create the routes to show the form and submit the form

<?php

use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\ArticleController;


Route::get('/article-view',[ArticleController::class, 'showArticle']); 
Route::get('/article-export',[ArticleController::class, 'exportArticles']); 

ScreenShot

Screenshot 2022 05 06 at 8.09.16 AM
Screenshot 2022 05 06 at 8.09.22 AM
Database to Excel/csv

Related

Php Laravel Laravel 9 EXCELEXPORTHTMLlaravel

Post navigation

Previous post
Next post

Related Posts

Javascript Laravel Ajax Autocomplete Using Select2

Laravel Ajax Autocomplete Using Select2

July 17, 2022July 17, 2022

In this article we will learn to use Laravel Ajax Autocomplete Using Select2. Select2 is useful when we want live search of bulk data or to convert the existing select boz with multi features like search, multi select and options customizations. Autocomplete search is mostly work of javascript and when…

Read More
Php html string in blade in laravel

How to Render Html String in Blade in Laravel ?

March 8, 2022December 2, 2023

Blade is a template engine to write the syntax easily and powerfully. To render html string in blade in laravel we use {!! $htmlstring !!}. Using the blade template we can easily print a variable, can create loops and can create directives and components too. Laravel blade template uses filename.blade.php…

Read More
Laravel append URL query params to pagination laravel

How to Append URL Query Params to Pagination Laravel ?

November 17, 2023March 16, 2024

In this guide, we’ll focus on improving user experience by append URL query params to pagination laravel links. Pagination plays a vital role in web applications, enabling users to navigate through extensive datasets.This not only enhances usability but also ensures a smoother transition between pages. Append URL query params to…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version