Export Data Into Excel Report In CodeIgniter 4 Tutorial

Share this Article
Reading Time: 9 minutes
1,638 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. Installation and working methods for all you can find here in detailed steps.

Learn Excel Export Using DataTable in CodeIgniter 4, Click here.

Learn More –

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Turn Development Mode On

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

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.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Create Database & Table in Application

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

CREATE DATABASE codeigniter4_app;

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 database and a table. Let’s connect with the application.


Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 
#--------------------------------------------------------------------
# DATABASE
#-------------------------------------------------------------------- 
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Now, database successfully connected with application.


Download PhpSpreadsheet Library into Application

To use excel report features, we need to download a library phpoffice/phpspreadsheet via composer.

Open project into terminal and run this command.

$ composer require phpoffice/phpspreadsheet

It will download excel spreadsheet package into /vendor folder of project root.


Create Routes

Open Routes.php from /app/Config.

Let’s add few routes into it. One route is to list all data and other is to download excel report.

//...

$routes->group("student", function ($routes) {

    $routes->get("/", "StudentController::index");
    $routes->get("download-report", "StudentController::downloadExcelReport");
});

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;

// Import Excel Package
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

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

		$students = $student_obj->findAll();

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

	public function downloadExcelReport()
	{
		$student_obj = new StudentModel();

		$students = $student_obj->findAll();

		$fileName = 'students.xlsx'; // File is to create

		$spreadsheet = new Spreadsheet();

		$sheet = $spreadsheet->getActiveSheet();
		$sheet->setCellValue('A1', 'Id');
		$sheet->setCellValue('B1', 'Name');
		$sheet->setCellValue('C1', 'Email');
		$sheet->setCellValue('D1', 'Mobile');
		$sheet->setCellValue('E1', 'Branch');
		$rows = 2;

		foreach ($students as $val) {
			$sheet->setCellValue('A' . $rows, $val['id']);
			$sheet->setCellValue('B' . $rows, $val['name']);
			$sheet->setCellValue('C' . $rows, $val['email']);
			$sheet->setCellValue('D' . $rows, $val['mobile']);
			$sheet->setCellValue('E' . $rows, $val['branch']);
			$rows++;
		}

		$writer = new Xlsx($spreadsheet);

		// file inside /public folder
		$filepath = $fileName;

		$writer->save($filepath);

		header("Content-Type: application/vnd.ms-excel");
		header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');

		header('Expires: 0');
		header('Cache-Control: must-revalidate');
		header('Pragma: public');
		header('Content-Length: ' . filesize($filepath));
		flush(); // Flush system output buffer
		readfile($filepath);

		exit;
	}
}

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">
  <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>
</head>
<body>

<div class="container" style="margin-top:30px;">
  <h2 style="text-align: center;">Student Report</h2>
  <h3  style="text-align: center;">Online Web Tutor - Export Excel in CodeIgniter 4 Tutorial</h3>

  <div class="panel panel-primary">
    <div class="panel-heading">
       Student Report
       <a href="<?= base_url('student/download-report') ?>" class="btn btn-info pull-right" style="margin-top: -7px;">Download Excel Report</a>
    </div>
    <div class="panel-body">
      <table class="table table-striped">
        <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>
</body>
</html>

Application Testing

Start development server:

$ php spark serve

URL: http://localhost:8080/student

We hope this article helped you to Export Data Into Excel Report In CodeIgniter 4 Tutorial in a very detailed way.

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.

Find More on CodeIgniter 4 here

2 thoughts on “Export Data Into Excel Report In CodeIgniter 4 Tutorial”

Leave a Comment