⚠ In case you've missed it, we have migrated to our new website, with a brand new forum. For more details about the migration you can read our blog post for website migration. This is an archived forum. ⚠

  •     

profile picture

Using PHPExcel with GroceryCRUD



hulabula
  • profile picture
  • Member

Posted 18 December 2015 - 20:25 PM

This is probably for those beginner PHP coders such as myself, but I just wanted to share how I got PHPExcel working with GroceryCRUD:
 
Step 1) I installed PHPExcel files into: applications/third_party/
 
Step 2) I created a file called Excel.php and placed it here: application/libraries/Excel.php
 
Step 3: Code for application/libraries/Excel.php is this:
<?php 
if (!defined('BASEPATH')) exit('No direct script access allowed');  
 
require_once APPPATH."/third_party/PHPExcel.php";
 
class Excel extends PHPExcel {
    public function __construct() {
        parent::__construct();
    }
}

Step 4) In my controller I added $this->load->library('excel'); to the __construct function:

	public function __construct()
	{
		parent::__construct();

		$this->load->database();
		$this->load->helper('url');

		$this->load->library('grocery_CRUD');
		$this->load->library('excel');
	}

Step 5) Make sure that your render() [case:16] "export to excel" points to a function where you will be using PHPExcel.  Because I'm a newbie and I couldn't get my custom model to work, I created a new function to applications/libraries/Grocery_CRUD.php under the protected function _export_to_excel($data) and call that from protected function exportToExcel

	protected function _export_to_excel_phpexcel($data)
	{
		$objPHPExcel = new PHPExcel();
				
		$objPHPExcel->setActiveSheetIndex(0);
		$objPHPExcel->getActiveSheet()->setTitle('test worksheet');
		$objPHPExcel->getActiveSheet()->setCellValue('A1', 'This is just some text value');
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->mergeCells('A1:D1');
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$filename='just_some_random_name.xls'; //save our workbook as this file name
		header('Content-Type: application/vnd.ms-excel'); //mime type
		header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
		header('Cache-Control: max-age=0'); //no cache
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  
		$objWriter->save('php://output');

		die();
	}

And it works!

 

 


Amit Shah
  • profile picture
  • Member

Posted 19 December 2015 - 00:46 AM

nice work brother - even if you think it is small.. but contribution helps a lot of others who may need it.

 

Happy GCing :)