Skip to content

Instantly share code, notes, and snippets.

@nebiros
Created January 28, 2010 13:13
Show Gist options
  • Save nebiros/288725 to your computer and use it in GitHub Desktop.
Save nebiros/288725 to your computer and use it in GitHub Desktop.
Export data to excel on Zend Framework
<?php
class IndexController extends Zend_Controller_Action
{
public function exportXlsAction()
{
set_time_limit( 0 );
$model = new Default_Model_SomeModel();
$data = $model->getData();
$filename = APPLICATION_PATH . "/tmp/excel-" . date( "m-d-Y" ) . ".xls";
$realPath = realpath( $filename );
if ( false === $realPath )
{
touch( $filename );
chmod( $filename, 0777 );
}
$filename = realpath( $filename );
$handle = fopen( $filename, "w" );
$finalData = array();
foreach ( $data AS $row )
{
$finalData[] = array(
utf8_decode( $row["col1"] ), // For chars with accents.
utf8_decode( $row["col2"] ),
utf8_decode( $row["col3"] ),
);
}
foreach ( $finalData AS $finalRow )
{
fputcsv( $handle, $finalRow, "\t" );
}
fclose( $handle );
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$this->getResponse()->setRawHeader( "Content-Type: application/vnd.ms-excel; charset=UTF-8" )
->setRawHeader( "Content-Disposition: attachment; filename=excel.xls" )
->setRawHeader( "Content-Transfer-Encoding: binary" )
->setRawHeader( "Expires: 0" )
->setRawHeader( "Cache-Control: must-revalidate, post-check=0, pre-check=0" )
->setRawHeader( "Pragma: public" )
->setRawHeader( "Content-Length: " . filesize( $filename ) )
->sendResponse();
readfile( $filename ); exit();
}
}
@manish-wedigtech
Copy link

Its is giving me "Action Helper by name Layout not found" error? any solution?
I am new to Zend Framwork 1.2.

@jitendra2
Copy link

It generates excel file but when open directely it generates non english content like damage file.what i should do?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment