I'm trying to get a report from my codeigniter project in excel, but I am at a complete loss on how to do it. It already works well, just would like the output in excel rather then a page.
Any tips/pointers/explanations?
thanks!
I'll refer you to this wiki article from the codeIgniter site, or to this tutorial
use PHPExcel Library
put the class folder in your codeigniter application library and call the PHPExcel class
this works fine with codeigniter
If you need something quick and dirty (and potentially working in FF only), I use this JS solution:
function exportExcel(html) {
window.open('data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(
'<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv=Content-Type content="text/html; charset=utf-8"><meta name=ProgId content=Excel.Sheet><style>body {font-family:Arial} .ean {mso-number-format:0000000000000;}</style></head><body><table>'+html.replace(/[♫^]/gi,'')+'</table></body></html>'));
}
And then following link in caption tag of the table
<a href="#" onclick="javascript:exportExcel($(this).parents(".table1").html());">Excel</a>
It will open as HTML Worksheet, which works for me. As you can see in JS funciton code, you can add styles to columns and/or replace some chars you don't need in the output.
Simplest way to integrate PHPExcel with codeigniter
First download the Php Excel from the website https://phpexcel.codeplex.com/.
Then extract the copy and put in the application/third_party folder of codeignitor.
Then go to the folder application/libraries and create a file and name it Excel.php. And place the below code:
require_once APPPATH."/third_party/PHPExcel.php"; //Change path if required.
class Excel extends PHPExcel { public function __construct() { parent::__construct(); } }
4.Now create a Controller like Export.php and in its action put the code:
$this->load->library('Excel');
$query = $this->db->get('users');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
$objPHPExcel->setActiveSheetIndex(0);
$col = 0;
foreach ($header as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
$objPHPExcel->getActiveSheet()->getStyle('A1:Z1')->getFont()->setBold(true);
$col++;
}
// Fetching the table data
$row = 2;
foreach($query as $data)
{
$col = 0;
foreach ($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data[$field]); //change if required.
$col++;
}
$row++;
}
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_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="'.'export_'.$table_name.'.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');