Tuesday, 28 October 2014

Exporting your MySQL table data with PHPExcel + 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()
    {
        parent::Controller();
 
        // 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);
 
        if(!$query)
            return false;
 
        // Starting the PHPExcel library
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory');
 
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
 
        $objPHPExcel->setActiveSheetIndex(0);
 
        // Field names in the first row
        $fields = $query->list_fields();
        $col = 0;
        foreach ($fields as $field)
        {
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
            $col++;
        }
 
        // Fetching the table data
        $row = 2;
        foreach($query->result() as $data)
        {
            $col = 0;
            foreach ($fields as $field)
            {
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
                $col++;
            }
 
            $row++;
        }
 
        $objPHPExcel->setActiveSheetIndex(0);
 
        $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');
 
        $objWriter->save('php://output');
    }
 
}

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.

Thank you for reading this tutorial I hope it has been useful. 

----------------------------------------------------------
Disediakan Oleh : Zainimar Binti Zulkifli
Sumber : http://dannyherran.com/2011/03/exporting-your-mysql-table-data-with-phpexcel-codeigniter/

0 comments:

Post a Comment