Excel file with Database by PHPExcel in Codeigniter

Excel file with Database by PHPExcel in Codeigniter

How to generate Excel file using PHPExcel in Codeigniter

Here we will discuss how to create excel file from database by PHPExcel in codeigniter. We’ll Export Data from Database to Excel file in Codeigniter Framework by using PHPExcel library.

Explanation :

Step 1 :- Click here to download PHPExcel.

Step 2 :- Extract the downloaded PHPExcel lib files and copy Class directory inside files to application/third-party directory(folder).

Step 3 :- Create Excel.php in application/library folder.

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

Step 4 :- Call Excel.php library in your controller.

Eg: $this->load->library(‘excel’);

Step 5 :- Controller Excel.php

if (!defined('BASEPATH')) exit('No direct script access allowed'); 
class Excel extends CI_Controller
   public function excel() 
      //load our new PHPExcel library 
      //activate worksheet number 1 
      //name the worksheet 
      $this->excel->getActiveSheet()->setTitle('Users list'); 
      // load database 
      // load model 
      // get all users in array formate 
      $users = $this->userModel->get_users(); 
      // read data to active sheet 
      //save our workbook as this file name 
      header('Content-Type: application/vnd.ms-excel'); 
      //mime type 
      header('Content-Disposition: attachment;filename="'.$filename.'"'); 
      //tell browser what's the file name 
      header('Cache-Control: max-age=0'); 
      //no cache 
      //save it to Excel5 format (excel 2003 .XLS file), change 
      this to 'Excel2007' (and adjust the filename extension, also the 
      header mime type) 
      //if you want to save it as.XLSX Excel 2007 format 
      $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5'); 
      //force user to download the Excel file without writing it to server's 

Step 6 :- To download Excel file provide a link                

Eg:- <a href="<?php echo base_url('Excel/excel'); ?>Download</a>

*** To make title cells use this :- $this->excel->getActiveSheet()->fromArray($header);

*** Other cells can be shown as $this->excel->getActiveSheet()->fromArray($users, null, 'A2');

*** To style title cells

//change the font size        


 //make the font become bold


Hope this easy method for creating Excel file using the library phpexcel in codeigniter will help you.

For other Codeigniter solutions please check this link : Codeigniter

Leave a Reply

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

Back To Top