Skip to content

Export to Excel 2013

Hassan Salih edited this page Nov 26, 2015 · 5 revisions

I found that some of the export to excel plugin’s here are outdated for Codeigniter newer versions (didn’t do a huge search so sorry if missed something that does work)
so I tweaked an older version of this code and simplified it to be the most basic as it gets.

in a library file export.php
if (!defined('BASEPATH')) exit('No direct script access allowed');

/*
* Excel library for Code Igniter applications
* Based on: Derek Allard, Dark Horse Consulting, www.darkhorse.to, April 2006
* Tweaked by: Moving.Paper June 2013
*/
class Export{
    
    function to_excel($array, $filename) {
        header('Content-type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename='.$filename.'.xls');

         //Filter all keys, they'll be table headers
        $h = array();
        foreach($array->result_array() as $row){
            foreach($row as $key=>$val){
                if(!in_array($key, $h)){
                 $h[] = $key;   
                }
                }
                }
                //echo the entire table headers
                echo '<table><tr>';
                foreach($h as $key) {
                    $key = ucwords($key);
                    echo '<th>'.$key.'</th>';
                }
                echo '</tr>';
                
                foreach($array->result_array() as $row){
                     echo '<tr>';
                    foreach($row as $val)
                         $this->writeRow($val);   
                }
                echo '</tr>';
                echo '</table>';
                
            
        }
    function writeRow($val) {
                echo '<td>'.utf8_decode($val).'</td>';              
    }

}

in the controller:

$this->load->library('export');
$this->load->model('mymodel');
$sql = $this->mymodel->myqueryfunction();
$this->export->to_excel($sql, 'nameForFile'); 

in the model you do what ever query you need.
that’s it!

Clone this wiki locally