Skip to content

Export to Excel 2013

daffneele edited this page Jun 19, 2013 · 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 ‘’; foreach($h as $key) { $key = ucwords($key); echo ‘’; } echo ‘’; foreach($array→result_array() as $row){ echo ‘’; foreach($row as $val) $this→writeRow($val); } echo ‘’; echo ‘
’.$key.‘
’; } function writeRow($val) { echo ‘’.utf8_decode($val).‘’; }

}

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