The Cgridview component provided by Yii does not have a built-in data export capability, but we can add that functionality by extending the component.
Here's how:
1, first derive a subclass, add an action member, in the view of the INIT function to determine whether the browse action or data export action, if the browser is the action to maintain the default behavior, otherwise output CSV file.
[PHP]View Plaincopy
- public function init ()
- {
- if ( $this->action == ' export ')
- {
- parent::init ();
- $this->gencsv ();
-     }
- ELSE  
-     {  
- Parent::init ();
-     }  
- }
2, processing the output of the CSV file:
[PHP]View Plaincopy
- 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. Then add a CSV export button to the Table control interface
Override its Renderitems () method as follows:
[PHP]View Plaincopy
- 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, then in the click on the CSV action processing such as ACTIONCSV () render a single table view, the template is as follows
[PHP]View Plaincopy
- <?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 there is no output before the header setting statement in the 2nd step of the CSV output function above, including the following function:
[Plain]View Plaincopy
- Print, Echo, printf, Trigger_error, vprintf, Ob_flush, Var_dump, ReadFile, PassThru
Otherwise the content will only be exported in the browser, but the file download will not occur.
by Iefreer
Reference:
http://stackoverflow.com/questions/8028957/headers-already-sent-by-php
YII: Extended cgridview Add export CSV function