Exporting your MySQL table data with PHPExcel + CodeIgniter

Posted by Danny Herran on Mar 8, 2011 in Backend | 29 comments

PHPExcel + CodeIgniter Most of the time my clients need to download data from their database tables. Exporting to CSV is a pain in the rear for users and it leads to confusion (you know the colon and semicolon stuff). Today, I decided to make a very small controller that is portable and efficient for exporting full MySQL tables to Excel 2003 using PHPExcel and CodeIgniter.

First of all, you need PHPExcel which should be installed as a CodeIgniter library. In order to do this, you should follow the steps posted here.

Once you have PHPExcel installed and configured, make a controller exactly like this one:

class Table_export extends Controller {

	function __construct()

		// Here you should add some sort of user validation
		// to prevent strangers from pulling your table data

	function index($table_name)
		$query = $this->db->get($table_name);

			return false;

		// Starting the PHPExcel library

		$objPHPExcel = new PHPExcel();


		// Field names in the first row
		$fields = $query->list_fields();
		$col = 0;
		foreach ($fields as $field)
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);

		// Fetching the table data
		$row = 2;
		foreach($query->result() as $data)
			$col = 0;
			foreach ($fields as $field)
				$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);



		$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');

		// Sending headers to force the user to download the file
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="Products_'.date('dMy').'.xls"');
		header('Cache-Control: max-age=0');



Whenever you need to export data from a MySQL table, you just need to call this controller and pass the table name as a parameter, sort of like http://www.yoursite.com/table_export/products. Obviously, you should always add some sort of security measure in order to prevent strangers from pulling all your table information. Just add some session protection to your constructor and you’re set.

  • Denis Francis

    Muito bom!

    Só tenho uma dúvida: tentei transformar esse controller em uma lib, passando a query como parâmetro, porém não funcionou.
    Preciso passar a query como parâmetro devido a necessidade de usar vários joins aintes de exportar.


    • Hi, please post some code and I’d be glad to help. It should totally work with a custom query. In fact, most of the time I use custom queries to export data. You just need to modify the controller.

  • Brad Morse

    This does about the same, but your code is geared more toward to ease of use, this gives you more power, but you need to supply the query: http://codeigniter.com/wiki/Excel_Plugin/

    • Thanks for sharing the link! Yes, indeed, they both do almost the same, the only difference is the use of PHPExcel in my code.

  • Carlos

    Hi friend how can’t use this? I’ don’t understand? I need export some data from sql table to excel, I’m using PHPExcel (codeplex) I need help. this is my code:


    $objPHPexcel = PHPExcel_IOFactory::load(‘reporteencts.xlsx’);

    $conexion = mysql_connect(“localhost”, “root”, “”);
    $sql=”SELECT * FROM testtable”;


    die(” MySQL Error”);

    while($fila = mysql_fetch_array($rst))
    $objPHPExcel->getActiveSheet()->setCellValue(“A”, $fila[saleman]);
    $objPHPExcel->getActiveSheet()->setCellValue(“B”, $fila[name_c]);
    $objPHPExcel->getActiveSheet()->setCellValue(“C”, $fila[company]);

    header(‘Content-Type: application/vnd.ms-excel’);
    header(‘Content-Disposition: attachment;filename=”Report.xls”‘);
    header(‘Cache-Control: max-age=0’);

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPexcel, ‘Excel5’);

  • Having trouble with the generated file.

    When I try to open it, Excel says “the file is corrupt and cannot be opened”. If I try to extract the data (as offered by Excel), it extracts the data and shows it, apparently, with no errors.

    Before, I was using ‘$this->dbutil->csv_from_result(…)’ to generate a CSV file, but it also gave me the same error.

    I’m using: Windows 7 Ultimate with MS Office 2007

  • Pingback: Exporting your MySQL table data with PHPExcel + CodeIgniter « Niroze's Weblog()

  • I have obtained:
    Cannot redeclare class PHPExcel_IOFactory
    Cannot redeclare class IOFactory … IOFactory.php on line 52

    please help me?

  • Thank you.
    how to upload not just one table with data as a single sheet,
    but all the tables from the database as the data sheets?

    help me please? :
    I need all the tables from the database as sheets with data

  • how to import a file from Excel to Mysql ?

  • hi,

    I came up with an error msg trying to work out with your code using PHPExcel

    Fatal error: Cannot redeclare class IOFactory in C:\xampp\htdocs\codeigniter\application\libraries\PHPExcel\IOFactory.php on line bla.. bla.. bla..

    what’s the main reason of this?
    Any answer would be highly appreciated.. Thanks!

  • Firman

    This really helped me.
    Thank you…^_^

  • Razibul Hasan

    Dear Friend. This code is very helpful for me. Thanks You……………………

  • ~~~~~~~~~~~~~Controller~~~~~~~~~~~~~
    function get_report()
    // get the object
    $report = $this->usermodel->index();
    //pass it to db utility function
    $new_report = $this->dbutil->csv_from_result($report);
    //Now use it to write file. write_file helper function will do it
    $data = file_get_contents(“useruploads/break_report.csv”); // Read the file’s contents
    $name = ‘break_report.csv’;
    force_download($name, $data);

    function index()
    return $query = $this->db->get(‘wg_user_break’);

    <a href="”>Excel Report

    That’s it no big deal…. your excel file is ready to download…….

  • Swapnil

    Thanks for the code Danny!!.. I had question if we could save the excel file on sever when this function is called rather than downloading on the user browser?

  • Heng Sopheak

    Dear Friend,
    Do you have any tuttoail for below question

    How to use PHPExcel to import data from excel into database in codeignight?

  • Heng Sopheak

    How about import?

  • thanks @sachin your code works for me but need like to ask something.

    if i need to add custom column name and file title and little more design, then how and where to add.

  • mostafa hakimi

    thank you so much and very helpful. please post how to upload to mysql table form excel file in codeignter ? i am really in trouble with this issue. please help me with this

  • Bikash Bhandari

    is this ur manner of teaching ha?? i waste 1 hour of my time on this but not work….shit..

    • chanthol

      it work fine for me

  • divin kattipparambil

    i found error like “Unable to load the requested class: PHPExcel” please help

    • mukhila


  • ravi

    what will be model for this code

  • Ángel Rafael Mónaco Reif

    I need to do the same example in a view, but it doesn’t work. Anyone know why doesn’t work in a view?

  • Ju Oliveira

    Is it possible to pick the columns ($col) that we want to show in the Excel file?
    Like restraining the table only to 5 or 6 specific columns..

    And thank you so much!! Your code is very helpful! I’m working with both Codeigniter and PHPExcel and all the examples I could find didn’t have the CodeIgniter part, so thank you!! 🙂

  • Nico Viola

    Hi, a little improvement:
    You can fill the document using fromArray() method and forget about $col and $row vars.

    use this:

    $objPHPExcel = new PHPExcel();
    $fields = $query->list_fields();
    $objPHPExcel->getActiveSheet()->fromArray($fields, null, “A1”);
    $objPHPExcel->getActiveSheet()->fromArray($query->result_array(), null, “A2”);

    instead of this:
    $fields = $query->list_fields();
    $col = 0;
    foreach ($fields as $field)
    $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
    // Fetching the table data
    $row = 2;
    foreach($query->result() as $data)
    $col = 0;
    foreach ($fields as $field)
    $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);

  • Pradeep Kumar

    I Am Pradeep Kumar (pnp intech appr- 2017)

    Provide A best Link For databse backup in codingiter
    That is Link visit it fastly:


  • shekhar gohane

    here is an error which unable to handle by me can you give a solution
    Non-existent class: IOFactory