We can use CSV helper for exporting data in excelsheet in cakephp.
For using CSV helper we have to follow simple steps.
Step 1:- Firstly we have to create a file naming CsvHelper.php and have to save it in our app/view/Helper directory.
Below is the code which CsvHelper.php file contain
<?php
class CsvHelper extends AppHelper
{
var $delimiter = ',';
var $enclosure = '"';
var $filename = 'Export.csv';
var $line = array();
var $buffer;
function CsvHelper()
{
$this->clear();
}
function clear()
{
$this->line = array();
$this->buffer = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
}
function addField($value)
{
$this->line[] = $value;
}
function endRow()
{
$this->addRow($this->line);
$this->line = array();
}
function addRow($row)
{
fputcsv($this->buffer, $row, $this->delimiter, $this->enclosure);
}
function renderHeaders()
{
header('Content-Type: text/csv');
header("Content-type:application/vnd.ms-excel");
header("Content-disposition:attachment;filename=".$this->filename);
}
function setFilename($filename)
{
$this->filename = $filename;
if (strtolower(substr($this->filename, -4)) != '.csv')
{
$this->filename .= '.csv';
}
}
function render($outputHeaders = true, $to_encoding = null, $from_encoding ="auto")
{
if ($outputHeaders)
{
if (is_string($outputHeaders))
{
$this->setFilename($outputHeaders);
}
$this->renderHeaders();
}
rewind($this->buffer);
$output = stream_get_contents($this->buffer);
if ($to_encoding)
{
$output = mb_convert_encoding($output, $to_encoding, $from_encoding);
}
return $this->output($output);
}
}
?>
Step 2:- Then we have add this CsvHelper in our controller by using below code .
var $helpers = array('Html', 'Form','Csv');
Step 3:- Then we have to create export method in our controller which contains below code.
function export()
{
$this->set('posts', $this->Post->find('all'));
$this->layout = null;
$this->autoLayout = false;
Configure::write('debug','0');
}
Step 4:- Then we have to create ctp file for export function i.e export.ctp which contain below code .
<?php
$line= $posts[0]['Post'];
$this->CSV->addRow(array_keys($line));
foreach ($posts as $post)
{
$line= $post['Post'];
$this->CSV->addRow($line);
}
$filename='posts';
echo $this->CSV->render($filename);
?>
Step 5:- Now we have to add link to our view file by using below code. On this link click we will see our data in excelsheet format.
<?php echo $this->Html->link('Export',array('controller'=>'posts','action'=>'export'), array('target'=>'_blank'));?>
0 Comment(s)