如何从cgridview打印到csv? [英] How to print out from cgridview to csv?

查看:252
本文介绍了如何从cgridview打印到csv?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问:如何将过滤的数据从cgridview打印到csv?

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

状态:我按照此处。但现在我得到了飞机csv(excel)文件。没有标题,没有数据。

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

这是视图

<?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'
        });
    }
    ");
    ?>

这是我的控制器

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');
}

我错了什么?

========================
已更新

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

到另一个扩展此处,然后是CalCS,地址是这里

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

m堆叠导出关系数据,一些字段通过csv和jason保留数据。我不知道在报告中导出这些数据。请帮助我。

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.

这是我的模型

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;
    }

这是我的查看

<?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>

这是我的控制器

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
    }


推荐答案

p>这是模型(aaa.php)

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;
    }

这是控制器

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
    }

这是 phpexcel 我用的是什么。 (非完整的phpexcel lib从他们的网站。)

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

在views / aaa / index.php调用?r = aaa / excel,这将导出当前过滤的数据或第一页数据。

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

这篇关于如何从cgridview打印到csv?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆