Yii framework extends CGridView to add the CSV export function, yiicgridview
This article describes how to extend the CGridView function of the Yii framework to export CSV data. We will share this with you for your reference. The details are as follows:
The CGridView component provided by Yii does not have the built-in data export function, but we can add this function by extending this component.
The specific method is as follows:
1. First, a subclass is derived, and an action Member is added. In the init function of this view, the browsing action or data export action is determined. If the view is a browsing operator, the default action is maintained, otherwise, the csv file is output.
public function init(){ if($this->action == 'export') { parent::init(); $this->genCsv(); } else { parent::init(); }}
2. Process csv file output:
protected function genCsv(){ header("Content-Type: text/csv; charset=GB2312"); header('Content-Disposition: attachment; filename="'.$this->fileName.'"'); //add your content dump codes here flush();}
3. Add a csv export button on the table control interface.
OverwriterenderItems()The method is as follows:
public function renderItems(){ if(Yii::app()->user->checkAccess('administrator')) { echo '<div class="toolBar">'; echo '<form action="'.CHtml::normalizeUrl(array($this->action)).'&id='.$this->id.'" method="post">'; foreach($this->getController()->getActionParams() as $name => $value) { echo '<input type="hidden" name="'.addcslashes($name,'"').'" value="'.addcslashes($value,'"').'" />'; } echo '<input type="image" title="'.Yii::t('ifCMS','Export to CSV').'" src="'.Yii::app()->theme->BaseUrl.'/images/ico-csv.png" alt="Submit">'; echo '</form>'; echo '</div>'; } parent::renderItems();}
4. Click the CSV action, for exampleactionCsv()In a single render table view, the template is as follows
<?php $this->widget('application.extensions.grid.MyGridView', array( 'id'=>'grid', 'action'=>'export', 'dataProvider'=>$dp, 'columns'=>array( array( 'header'=>Yii::t('Statistics','Phone'), 'name'=>'phone', ), array( 'header'=>Yii::t('Statistics','Count'), 'name'=>'count', ), )));?>
Note that no output exists before the header setting statement in the above step 2nd csv output function, including the following functions:
print,echo,printf,trigger_error,vprintf,ob_flush,var_dump,readfile,passthru
Otherwise, the content will only be output in the browser, but the file will not be downloaded.