DataTable Excel Data Export in CodeIgniter 4 Tutorial

Reading Time: 7 minutes
8,107 Views

Working & Download Reports in Web applications is very common when we are developing data related web applications. Exporting data into PDF, Excel, a Word Document, CSV is very common in applications.

Inside this article, we will see the concept of Exporting data into Excel report in codeigniter 4 using jQuery DataTable plugin. Installation and working methods for all you can find here in detailed steps.

Not only Excel, we can also export data into PDF, CSV etc.

Learn Excel Export Data Using PHPSpreadsheet Library in CodeIgniter 4, Click here.

Learn More –

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Create Database Table

Next, we need a table. That table will be responsible to store data.

Let’s create table with some columns.

CREATE TABLE students (
    id int(5) unsigned NOT NULL AUTO_INCREMENT,
    name varchar(100) NOT NULL,
    email varchar(100) NOT NULL,
    mobile varchar(20) DEFAULT NULL,
    branch varchar(50) DEFAULT NULL,
    created_at datetime DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Successfully, we have created a table.


Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = admin
database.default.password = admin
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
  

Now, database successfully connected with the application.


Create Route

Open Routes.php from /app/Config. Add this route.

//...

$routes->get("students", "StudentController::index");

//...

Create Model

To create a model file, run this spark command.

$ php spark make:model Student --suffix

It will create a file StudentModel.php at /app/Models folder.

Open StudentModel.php and write this following code into it.

<?php

namespace App\Models;

use CodeIgniter\Model;

class StudentModel extends Model
{
    protected $DBGroup = 'default';
    protected $table = 'students';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $insertID = 0;
    protected $returnType = 'array';
    protected $useSoftDelete = false;
    protected $protectFields = true;
    protected $allowedFields = [
        "name",
        "email",
        "mobile",
        "branch",
    ];

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat = 'datetime';
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';
    protected $deletedField = 'deleted_at';

    // Validation
    protected $validationRules = [];
    protected $validationMessages = [];
    protected $skipValidation = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert = [];
    protected $afterInsert = [];
    protected $beforeUpdate = [];
    protected $afterUpdate = [];
    protected $beforeFind = [];
    protected $afterFind = [];
    protected $beforeDelete = [];
    protected $afterDelete = [];
}

Create Data Seeder For dummy data

Next, we need dummy data set to demonstrate this article. If you have real time data, it will be good else continue with this Fake data.

To generate fake data – Need to create a seeder file and then will use Faker Library. By default Faker library is available in CodeIgniter 4.

To create seeder file, back to terminal and run this spark command.

$ php spark make:seeder Student --suffix

It will create a file StudentSeeder.php into /app/Database/Seeds folder.

Open StudentSeeder.php file and write this following code into it.

<?php

namespace App\Database\Seeds;

use App\Models\StudentModel;
use CodeIgniter\Database\Seeder;
use Faker\Factory;

class StudentSeeder extends Seeder
{
    public function run()
    {
        $data = [];

        for ($i = 0; $i < 50; $i++) {

            $data[] = $this->generateTestStudent();
        }

        $student_obj = new StudentModel();

        $student_obj->insertBatch($data);
    }

    public function generateTestStudent()
    {
        $faker = Factory::create();

        return [
            "name" => $faker->name(),
            "email" => $faker->email,
            "mobile" => $faker->phoneNumber,
            "branch" => $faker->randomElement([
                "Computer Science",
                "Mechancial",
                "Electrical",
                "Civil",
                "Robotics",
                "Medical",
            ]),
        ];
    }
}

Run Seeder File

To seed dummy data, we need to run the above created seeder file. Run this spark command to terminal.

$ php spark db:seed StudentSeeder

Create Controller

To create controller file, run this spark command into terminal.

$ php spark make:controller Student --suffix

It will create a file StudentController.php at /app/Controllers folder.

Open StudentController.php file and write this code.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\StudentModel;

class StudentController extends BaseController
{
	public function index()
	{
		$student_obj = new StudentModel();

		$students = $student_obj->findAll();

		return view("list-student", [
			"students" => $students,
		]);
	}
}

Create View File

Let’s create a view file list-student.php at /app/Views. Inside this view file, we are listing all data and also have a download button as Excel Report.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"/>
  <link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.6.5/css/buttons.dataTables.min.css"/>
</head>
<body>

<div class="container" style="margin-top:30px;">
  <h3 style="text-align: center;">Student Report - DataTable Export Buttons by Online Web Tutor</h3>

  <div class="panel panel-primary">
    <div class="panel-heading">
       Student Report
    </div>
    <div class="panel-body">
      <table class="table table-striped" id="tbl-student">
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Mobile</th>
            <th>Branch</th>
          </tr>
        </thead>
        <tbody>

          <?php
            if(count($students) > 0){

              $count = 1;

              foreach($students as $student){
                ?>
                  <tr>
                    <td><?= $count++ ?></td>
                    <td><?= $student['name'] ?></td>
                    <td><?= $student['email'] ?></td>
                    <td><?= $student['mobile'] ?></td>
                    <td><?= $student['branch'] ?></td>
                  </tr>
                <?php
              }
            }
          ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.5/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.5/js/buttons.html5.min.js"></script>

<script>
   $(function(){
     $("#tbl-student").DataTable({
        dom: 'Bfrtip',
        buttons: [
            'copyHtml5',
            'excelHtml5',
            'csvHtml5',
            'pdfHtml5',
            'pageLength'
        ]
    });
   })
</script>

</body>
</html>

Application Testing

Open project terminal and start development server via command:

php spark serve

URL: http://localhost:8080/students

We hope this article helped you to learn DataTable Excel Data Export in CodeIgniter 4 Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.