Export Data Into Excel Report In CodeIgniter 4 Tutorial

Reading Time: 9 minutes
10,023 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 –

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 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.


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

Open project terminal and start development server via command:

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.

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more

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

Comments are closed.