How to print out from cgridview to csv?

2019-09-02 19:48发布

Q : How to print out the filtered data from cgridview to csv?

Status : I followed instruction as here. But now I got the plane csv(excel) file. No header, no data.

This is view

<?php
echo CHtml::button('Export', array('id'=>'export-button','class'=>'span-3 button')); 
?>
    <?php $this->widget('zii.widgets.grid.CGridView', array(
        'id'=>'request-grid',
        'dataProvider'=>$model->creator(),
        'filter'=>$model,
        'columns'=>array(
            'request_no',
            array(
                  'name'=>'request_type_id',
                  'value'=>'$data->requesttypes->name',
            ),
            array(
                  'name'=>'request_category_id',
                  'value'=>'$data->requestcategories->name',
            ),
            array(
                  'name'=>'financial_type_id',
                  'value'=>'$data->requestfinanicaltypes->name',
            ),
            array(
                  'name'=>'urgency_id',
                  'value'=>'$data->requesturgent->name',
            ),
            'status',
            'eta_date',
            'completed_date',
            'created_date',

            array(
            'class'=>'CButtonColumn',
            'template'=>'{update}{view}{copy}',
            'buttons'=>array(
                    'delete'=>array(
                        'visible'=>'true',
                        'options'=>array('style'=>'align:left;'),
                    ),
                    'view'=>array(
                        'visible'=>'true',
                        'options'=>array('style'=>'align:left;'),
                    ),              
                    'update'=>array(
                        'visible'=>'$data->status == \'Pending\'',
                    ),
                    'copy'=>array(
                        'imageUrl'=>Yii::app()->request->baseUrl.'/images/assets/Copy2.png',      
                        'url'=>'Yii::app()->createUrl("creator/copy", array("id"=>$data->id))',
                        'options'=>array('style'=>'border:none;'),
                    ),
                ),
            'htmlOptions'=>array(
                                    'style'=>'text-align: right; padding-right:3px;'
                            ),
            ),
        ),
    )); ?>


    <?php
    Yii::app()->clientScript->registerScript('delete-item', "

    $('#export-button').on('click',function() {

        $.fn.yiiGridView.export();
    });
    $.fn.yiiGridView.export = function() {
        $.fn.yiiGridView.update('request-grid',{ 
            success: function() {
                $('#request-grid').removeClass('grid-view-loading');
                window.location = '". $this->createUrl('exportFile')  . "';
            },
            data: 'export=true'
        });
    }
    ");
    ?>

This is My controller

public function actionExport()
{
    $fp = fopen('php://temp', 'w');

    /* 
     * Write a header of csv file
     */
    $headers = array(
        'request_no',               
        'status',
        'eta_date',
        'completed_date',
        'created_date',
    );
    $row = array();
    foreach($headers as $header) {
        $row[] = Request::model()->getAttributeLabel($header);
    }
    fputcsv($fp,$row);

    /*
     * Init dataProvider for first page
     */
    $model=new Request('Creator');
    $model->unsetAttributes();  // clear any default values
    if(isset($_GET['Request'])) {
        $model->attributes=$_GET['Request'];
    }
    $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 Request('Creator');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Request']))
            $model->attributes=$_GET['Request'];

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

    /*
     * save csv content to a Session
     */
    rewind($fp);
    Yii::app()->getRequest()->sendFile('aa.csv', stream_get_contents($fp), "text/csv", false);
    //Yii::app()->user->setState('export',stream_get_contents($fp));
    fclose($fp);
}

public function actionExportFile()
{
    Yii::app()->request->sendFile('export.csv',Yii::app()->user->getState('export'));
    Yii::app()->user->clearState('export');
}

Where did I wrong?

======================== updated

I moved to another extension here and followed by CalCS at here

Now I'm stacking to export the relationship data and some of the field are keep the data by csv and jason. I don't know to export those data at report. please help me.

this is my Model

public function creator()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id,true);
        $criteria->compare('request_no',$this->request_no,true);
        //$criteria->condition('creator',$this->creator);

        $criteria->condition = 'creator =' . Yii::app()->user->id;


        $criteria->compare('request_type_id',$this->request_type_id);
        $criteria->compare('request_category_id',$this->request_category_id);
        $criteria->compare('financial_type_id',$this->financial_type_id);
        $criteria->compare('urgency_id',$this->urgency_id);
        $criteria->compare('description',$this->description,true);
        $criteria->compare('eta_cost_usd',$this->eta_cost_usd,true);
        $criteria->compare('eta_cost_kyats',$this->eta_cost_kyats,true);
        $criteria->compare('final_cost_Ks',$this->final_cost_Ks,true);
        $criteria->compare('final_cost_USD',$this->final_cost_USD,true);
        $criteria->compare('exchange_rate_Ks',$this->exchange_rate_Ks);
        $criteria->compare('exchange_date',$this->exchange_date,true);
        $criteria->compare('status',$this->status);
        $criteria->compare('reviewers',$this->reviewers,true);
        $criteria->compare('approvers',$this->approvers,true);
        $criteria->compare('approved_date',$this->approved_date,true);
        $criteria->compare('force_approved',$this->force_approved);
        $criteria->compare('implementers',$this->implementers);
        $criteria->compare('eta_date',$this->eta_date,true);
        $criteria->compare('completed_date',$this->completed_date,true);
        //$criteria->compare('created_date',$this->created_date,true);

        $criteria->order = ' created_date DESC';
         $data = new CActiveDataProvider(get_class($this), array(
                        'pagination'=>array('pageSize'=> Yii::app()->user->getState('pageSize',
                                                                        Yii::app()->params['defaultPageSize']),),
                        'criteria'=>$criteria,
                ));
        $_SESSION['Lectivo-excel']=$data; // get all data and filtered data :)

        /*return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
        */
        return $data;
    }

This is my View

<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'request-grid',
    'dataProvider'=>$model->creator(),
    'filter'=>$model,
    'columns'=>array(
        //'id',
        'request_no',
        //'creator',
        array(
              'name'=>'request_type_id',
              'value'=>'$data->requesttypes->name',
        ),
        array(
              'name'=>'request_category_id',
              'value'=>'$data->requestcategories->name',
        ),
        array(
              'name'=>'financial_type_id',
              'value'=>'$data->requestfinanicaltypes->name',
        ),
        array(
              'name'=>'urgency_id',
              'value'=>'$data->requesturgent->name',
        ),
        'status',
        'eta_date',
        'completed_date',
        'created_date',
        /*
        'description',
        'eta_cost_usd',
        'eta_cost_kyats',
        'final_cost_Ks',
        'final_cost_USD',
        'exchange_rate_Ks',
        'exchange_date',
        'status_id',
        'reviewers',
        'approvers',
        'approved_date',
        'force_approved',
        'implementer',
        'eta_date',
        'completed_date',
        'created_date',
        */
        array(
        'class'=>'CButtonColumn',
        'template'=>'{update}{view}{copy}',
        'buttons'=>array(
                'delete'=>array(
                    'visible'=>'true',
                    'options'=>array('style'=>'align:left;'),
                ),
                'view'=>array(
                    'visible'=>'true',
                    'options'=>array('style'=>'align:left;'),
                ),              
                'update'=>array(
                    'visible'=>'$data->status == \'Pending\'',
                ),
                'copy'=>array(
                    'imageUrl'=>Yii::app()->request->baseUrl.'/images/assets/Copy2.png',      
                    'url'=>'Yii::app()->createUrl("creator/copy", array("id"=>$data->id))',
                    'options'=>array('style'=>'border:none;'),
                ),
            ),
        'htmlOptions'=>array(
                                'style'=>'text-align: right; padding-right:3px;'
                        ),
        ),
    ),
)); ?>

</div>
<?php $this->endWidget(); ?>
</div>

<div id='menub'>
<?php   
$this->widget('zii.widgets.CMenu', array(
'encodeLabel'=>false,
'htmlOptions'=>array('class'=>'actions'),
'items'=>array(
               array(
                     'label'=>Yii::t('internationalization', 'Exportar'),
                    'url'=>array('CREATOR/Excel'),


))));
?></div></div>

This is My controller

public function actionExcel() {

        $d = $_SESSION['Lectivo-excel'];

        $data = array();

        $data[]=array_keys($d->data[0]->attributes);//headers: cols name

        foreach ($d->data as $item) {
            $data[] = $item->attributes;

        }

        Yii::import('application.extensions.phpexcel.JPhpExcel');
        $xls = new JPhpExcel('UTF-8', false, 'test');
        $xls->addArray($data);
        $xls->generateXML('filename'); //export into a .xls file
    }

1条回答
不美不萌又怎样
2楼-- · 2019-09-02 20:04

This is model (aaa.php)

public function creator()

    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id,true);

        ...........

        $criteria->order = ' created_date DESC';
         $data = new CActiveDataProvider(get_class($this), array(
                    'pagination'=>array('pageSize'=> Yii::app()->user->getState('pageSize',
                                                                    Yii::app()->params['defaultPageSize']),),
                    'criteria'=>$criteria,
            ));
        $_SESSION['excel-current']=$data; // get all data and filtered data :)

        return $data;
    }

This is controller

public function actionIndex()
    {
        $model=new Request('creator');
        $model->scenario = "CreatorIndex";
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Request']))
            $model->attributes=$_GET['Request'];

        $this->render('index',array(
            'model'=>$model,
        ));
    }
public function actionExcel() {

        $d = $_SESSION['excel-current'];

        $data = array();
        //$data[]=array_keys($d->data[0]->attributes);//headers: default cols name

        // default data add
        foreach ($d->data as $item) {
            $data[] = $item->attributes;

        }

        // Custome cols
        $data[0][0] = 'Request No';

        .............

        $data[0][20] = 'Created Date';
        $i=1;

                // custom add data
        foreach($d->data as $item)
        {

            $data[$i][0] = $item->request_no;

                        ............

            $data[$i][20] = $item->created_date;
            $i++;
        }

        Yii::import('application.extensions.phpexcel.JPhpExcel');
        $xls = new JPhpExcel('UTF-8', false, 'test');
        $xls->addArray($data);
        $xls->generateXML('filename'); //export into a .xls file
    }

This is phpexcel what I use. (not full phpexcel lib from their website.)

at views/aaa/index.php call the ?r=aaa/excel, this will be export your current filtered data or 1st page of data.

查看更多
登录 后发表回答