Exporting CGridView results to CSV file

You are viewing revision #1 of this wiki article.
This is the latest version of this article.

How to create a simple CSV exporting for CGridView search results

A few days ago, i worked for CGridView exporting functional for my client. He asked me to create a simple exporting to a CSV file a CGridView search results.

That's very easy. Let's start...

Create an export button in your template.

I just created an Export Button above my grid.

<?php echo CHtml::button('Export', array('id'=>'export-button','class'=>'span-3 button')); ?>
Extending CGridView javascript code.

This javascript code does:

  1. bind an .export() execution by clicking an export button, defined above.
  2. extinds an yiiGridView javascript class for function update.
    [javascript]
    $('#export-button').on('click',function() {
    $.fn.yiiGridView.export();
    });
    $.fn.yiiGridView.export = function() {
    $.fn.yiiGridView.update('dates-grid',{ 
    	success: function() {
    		$('#dates-grid').removeClass('grid-view-loading');
    		window.location = '". $this->createUrl('exportFile')  . "';
    	},
    	data: $('.search-form form').serialize() + '&export=true'
    });
    }
    
Add actions to your controller

Because CGridView always uses for update the same action as initial render CGridView we need to use this action for our purpose in a next way: Add next peace of code at the top of action your CGridView render.

if(Yii::app()->request->getParam('export')) {
	$this->actionExport();
	Yii::app()->end();
}

It will run our actionExport if GET['export'] set.

Action Export (will use CGridView dataprovider defined in a model()->search())
public function actionExport()
{
	$fp = fopen('php://temp', 'w');

	/* 
	 * Write a header of csv file
	 */
	$headers = array(
		'd_date',
		'client.clientFirstName',
		'client.clientLastName',
		'd_time',
	);
	$row = array();
	foreach($headers as $header) {
		$row[] = MODEL::model()->getAttributeLabel($header);
	}
	fputcsv($fp,$row);

	/*
	 * Init dataProvider for first page
	 */
	$model=new MODEL('search');
	$model->unsetAttributes();  // clear any default values
	if(isset($_GET['MODEL'])) {
		$model->attributes=$_GET['MODEL'];
	}
	$dp = $model->search();

	/*
	 * Get models, write to a file, then change page and re-init DataProvider
	 * with next page and repeat writing again
	 */
	while($models = $dp->getData()) {
		foreach($models as $model) {
			$row = array();
			foreach($headers as $head) {
				$row[] = CHtml::value($model,$head);
			}
			fputcsv($fp,$row);
		}

		unset($model,$dp,$pg);
		$model=new MODEL('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['MODEL']))
			$model->attributes=$_GET['MODEL'];

		$dp = $model->search();
		$nextPage = $dp->getPagination()->getCurrentPage()+1;
		$dp->getPagination()->setCurrentPage($nextPage);
	}

	/*
	 * save csv content to a Session
	 */
	rewind($fp);
	Yii::app()->user->setState('export',stream_get_contents($fp));
	fclose($fp);
}
Last action to download CSV file
public function actionGetExportFile()
{
	Yii::app()->request->sendFile('export.csv',Yii::app()->user->getState('export'));
	Yii::app()->user->clearState('export');
}
Hope everything is clear. Enjoy your Yii CGridView.
6 3
18 followers
Viewed: 70 046 times
Version: Unknown (update)
Category: Tutorials
Written by: RusAlex
Last updated by: RusAlex
Created on: Feb 20, 2012
Last updated: 12 years ago
Update Article

Revisions

View all history

Related Articles