PHPExcel export mysql to excel in Codeigniter

Most of the time my clients need to download data from their database tables. Today, I decided to make a very small controller that is portable and efficient for exporting full MySQL tables to Excel using PHPExcel and CodeIgniter.

Download your mysql data in yo Excel Sheet.

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.

require_once APPPATH.'third_party/PHPExcel.php';
$this->excel = new PHPExcel(); 

PHPExcel Library in Controller.

$tamplate       = "demo.xlt";
$objReader      = PHPExcel_IOFactory::createReader('Excel5');
$exportdimond = $this->Userlist_Model->ExportDiamond();
$objPHPExcel    = $objReader->load("assets/file_template/".$tamplate);

$row = 2;
foreach ($exportdimond as $value)
{
    $objPHPExcel->getActiveSheet()->setCellValue('A'.$row, $value->id);
    $objPHPExcel->getActiveSheet()->setCellValue('B'.$row, $value->C_Shape);
    $objPHPExcel->getActiveSheet()->setCellValue('C'.$row, $value->C_Weight);
    $objPHPExcel->getActiveSheet()->setCellValue('D'.$row, $value->C_Color);
    $objPHPExcel->getActiveSheet()->setCellValue('E'.$row, $value->C_Clarity);
    $objPHPExcel->getActiveSheet()->setCellValue('F'.$row, $value->C_Cut);
    $objPHPExcel->getActiveSheet()->setCellValue('G'.$row, $value->C_Polish);
    $objPHPExcel->getActiveSheet()->setCellValue('H'.$row, $value->C_Symmetry);
    $objPHPExcel->getActiveSheet()->setCellValue('I'.$row, $value->C_Fluorescence);
    $row++;
}
$filename = "demo". date("Y-m-d-H-i-s").".csv";
header('Content-Type: application/vnd.ms-excel'); 
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0'); 
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');  
$objWriter->save('php://output');

Now model call to get data in table $this->Userlist_Model->ExportDiamond();

function ExportDiamond()
{
    $query = $this->db->get('diamond_master');
    return $query->result();
}

Leave a Reply

Your email address will not be published. Required fields are marked *