Export Data to Excel/CSV in Codeigniter Using PHPExcel

Export Data to Excel/CSV in Codeigniter Using PHPExcel

In this codeigniter excel,csv export tutorial, we will would love to share with you how to Export data into Excel or CSV in CodeIgniter. Excel is the best technique to Export data in a file and you can easily export data to Excel or CSV using Codeigniter excel library.

Codeigniter Export Excel,CSV


  • Download Codeigniter Latest
  • Basic Configurations
  • Download phpExcel Library
  • Create Library
  • Create Database With Table
  • Setup Database Credentials
  • Make New Controller
  • Create model
  • Create Views
  • Start Development server
  • Conclusion

Download Codeigniter Project

In this step we will download the latest version of Codeigniter, Go to this link Download Codeigniter download the fresh setup of codeigniter and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Basic Configurations

Next we will set the some basic configuration on config.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

$config['base_url'] = 'http://localhost/demo/';

Download phpExcel Library

Download this excel library here : click here

Next, we need to download phpExcel library from this link, and extract into application/third_party folder. After extract this library move to PHPExcel folder like application/third_party/PHPExcel and also move PHPExcel.php file to application/third_party/PHPExcel.php.

Create Library

Now we need to create Excel.php file into application/library, So go to application/library and create one file name Excel.php and put the below code here.

if (!defined('BASEPATH')) exit('No direct script access allowed');  
require_once APPPATH."/third_party/PHPExcel.php";
class Excel extends PHPExcel {
    public function __construct() {

Create Database With Table

In this step, we need to create database name demo, so let’s open your phpmyadmin and create the database with the name demo . After successfully create a database, you can use the below sql query for creating a table in your database.

    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    first_name varchar(100) NOT NULL COMMENT 'First Name',
    last_name varchar(100) NOT NULL COMMENT 'Last Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    dob varchar(20) NOT NULL COMMENT 'Date of Birth',
    contact_no varchar(50) NOT NULL COMMENT 'Contact No',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
  INSERT INTO import (id, first_name, last_name, email, dob, contact_no) VALUES
  (1, 'Team', 'test', '[email protected]', '21-02-2011', '9000000001'),
  (2, 'Admin', 'second', '[email protected]', '21-02-2011', '9000000002'),
  (3, 'User', 'third', '[email protected]', '21-02-2011', '9000000003'),
  (4, 'Editor', 'fouth', '[email protected]', '21-02-2011', '9000000004'),
  (5, 'Writer', 'fifth', '[email protected]', '21-02-2011', '9000000005'),
  (6, 'Contact', 'sixth', '[email protected]', '21-02-2011', '9000000006'),
  (7, 'Manager', 'seven', '[email protected]', '21-02-2011', '9000000007');

Setup Database Credentials

In this step, We need to connect our project to database. we need to go application/config/ and open database.php file in text editor. After open the file in text editor, We need to setup database credential in this file like below.

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'demo',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE

Create Controller

Now we need to create a controller name Export.php. In this controller we will create some method/function. We will build some of the methods like :

  • Index() – This is used to showing users list
  • generateXls() – This function is used to export excel or csv sheet

defined('BASEPATH') OR exit('No direct script access allowed');

class Export extends CI_Controller {
	// construct
    public function __construct() {
		// load model
        $this->load->model('Export_model', 'export');

    public function index() {
        $data['export_list'] = $this->export->exportList();
        $this->load->view('export', $data);
	// create xlsx
    public function generateXls() {
		// create file name
        $fileName = 'data-'.time().'.xlsx';  
		// load excel library
        $listInfo = $this->export->exportList();
        $objPHPExcel = new PHPExcel();
        // set Header
        $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'First Name');
        $objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Last Name');
        $objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Email');
        $objPHPExcel->getActiveSheet()->SetCellValue('D1', 'DOB');
        $objPHPExcel->getActiveSheet()->SetCellValue('E1', 'Contact_No');       
        // set Row
        $rowCount = 2;
        foreach ($listInfo as $list) {
            $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $list->first_name);
            $objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, $list->last_name);
            $objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, $list->email);
            $objPHPExcel->getActiveSheet()->SetCellValue('D' . $rowCount, $list->dob);
            $objPHPExcel->getActiveSheet()->SetCellValue('E' . $rowCount, $list->contact_no);
        $filename = "tutsmake". date("Y-m-d-H-i-s").".csv";
		header('Content-Type: application/vnd.ms-excel'); 
		header('Content-Disposition: attachment;filename="'.$filename.'"');
		header('Cache-Control: max-age=0'); 
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');  


Create model

Now go to application/models folder and create a one model name Export_model.php . After create this model put the below query in to model.

defined('BASEPATH') OR exit('No direct script access allowed');

	class Export_model extends CI_Model {

		public function __construct()
	    public function exportList() {
	        $this->db->select(array('id', 'first_name', 'last_name', 'email', 'dob', 'contact_no'));
	        $query = $this->db->get();
	        return $query->result();

Create Views

Now we need to create export.php, go to application/views/ folder and create export.php file. Here put the below html code for showing list of product.

<!DOCTYPE html>
  <title>Codeigniter Export Example</title>
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <div class="table-responsive">
    <table class="table table-hover tablesorter">
                <th class="header">First Name</th>
                <th class="header">Last Name</th>                           
                <th class="header">Email</th>                      
                <th class="header">DOB</th>
                <th class="header">Contact Name</th>
            if (isset($export_list) &amp;&amp; !empty($export_list)) {
                foreach ($export_list as $key => $list) {
                        <td><?php echo $list->first_name; ?></td>   
                        <td><?php echo $list->last_name; ?></td> 
                        <td><?php echo $list->email; ?></td>                       
                        <td><?php echo $list->dob; ?></td>
                        <td><?php echo $list->contact_no; ?></td>
            } else {
                    <td colspan="5">There is no employee.</td>    
            <?php } ?>

    <a class="pull-right btn btn-primary btn-xs" href="export/createxls"><i class="fa fa-file-excel-o"></i> Export Data</a>


Start Development server

For start development server, Go to the browser and hit below the url.



In this codeigniter excel csv tutorial, we have successfully create a list of users and successfully export data as csv format, If you want to change format like excel,xls, xlse, etc. So you can change easily and download.

You may like

  1. Import Data From Excel & CSV to mysql Using Codeigniter
  2. Adding Multiple Markers To Google Maps From Database PHP Codeigniter
  3. Integrate Razorpay with PHP Codeigniter
  4. Implement Google Column Chart With PHP Codeigniter
  5. Google Bar & Line Charts Days Wise MySQL PHP Codeigniter
  6. Codeigniter Pagination Library Example
  7. Morris Area & Line Chart With Codeigniter Example

If you have any questions or thoughts to share, use the comment form below to reach us.

One reply to Export Data to Excel/CSV in Codeigniter Using PHPExcel

  1. Thanks bro.It was very helpful for me.

Leave a Reply

Your email address will not be published. Required fields are marked *