Thursday 12 July 2012

A simple code to export data to excel using PHP and cake php

While generating a report in your project, you might have to download the data into excel file using PHP. In most scenario, you have to display the report in a page and create a link to download the report in the excel file. Well in that scenario, i think i can help you with a simplified code of PHP and cakephp.


Core Php

<?php
    $filename ="excelreport.xls";
    $contents = "Name\t Email \t Mobile \t \n";
$contents.= "Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n";
$contents.= "Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n";
$contents.= "Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n";
    header('Content-type: application/ms-excel'); /// you can set csv format
    header('Content-Disposition: attachment; filename='.$filename);
    echo $contents;
    ?>

Cake php Code 
Past this code on controller
controlpanel_controller.php

class ControlpanelController extends AppController {
var $name="Controlpanel";
var $layout=false;

function file_export()
{
              $this->autoRender=false;
ini_set('max_execution_time', 1600); //increase max_execution_time to 10 min if data set is very large
$results = $this->ModelName->find('all', array());// set the query function
 foreach($results as $result)
{
$header_row.= $result['Doctor']['fname']."\t". $result['Doctor']['lname'] ."\t ".$result['User']['email']." \t \n";

}
$filename = "export_".date("Y.m.d").".xls";
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename="'.$filename.'"');
echo($header_row);
}

}



No comments:

Post a Comment