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

Contents

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

<?php 
if (!defined('BASEPATH')) exit('No direct script access allowed');  
 
require_once APPPATH."/third_party/PHPExcel.php";
 
class Excel extends PHPExcel {
    public function __construct() {
        parent::__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.

CREATE TABLE import (
    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
<?php

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

class Export extends CI_Controller {
	// construct
    public function __construct() {
        parent::__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
        $this->load->library('excel');
        $listInfo = $this->export->exportList();
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        // 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);
            $rowCount++;
        }
        $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');  
		$objWriter->save('php://output'); 

    }
    
}
?>

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.

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

	class Export_model extends CI_Model {

		public function __construct()
		{
		    $this->load->database();
		}
	   
	    public function exportList() {
	        $this->db->select(array('id', 'first_name', 'last_name', 'email', 'dob', 'contact_no'));
	        $this->db->from('import');
	        $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>
<html>
<head>
  <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>
</head>
<body>
    
    <div class="table-responsive">
    <table class="table table-hover tablesorter">
        <thead>
            <tr>
                <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>
            </tr>
        </thead>
        <tbody>
            <?php
            if (isset($export_list) &amp;&amp; !empty($export_list)) {
                foreach ($export_list as $key => $list) {
                    ?>
                    <tr>
                        <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>
                    </tr>
                    <?php
                }
            } else {
                ?>
                <tr>
                    <td colspan="5">There is no employee.</td>    
                </tr>
            <?php } ?>

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

</body>
</html>

Start Development server

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

http://localhost/demo/excel

Conclusion

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.

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

Spread the love

Be First to Comment

Leave a Reply

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