如何使用 Yii 1.1 框架下载带有 PHP 的过滤 CSV 文件

在你进一步阅读之前,如果我在这里重复,我想道歉。我已经四处寻找了很长一段时间,在如何处理以下情况方面没有任何运气。由于我是一名新手程序员,整个事情变得越来越糟。


情况


我从工作中的高级程序员那里得到了一个任务,即创建一个生成CSV文件的函数。我遇到了一些麻烦,但最终还是成功了。该函数(位于模型中)如下所示。


// The function below will return a CSV file.

  public function convert2CSV(){


    $data = $this->search()->rawData;


    $fileOpener = fopen('php://output', 'w');


    fputcsv($fileOpener, array(

       'some code...'

    ), ';');


    foreach ($data as $rows) {

      fputcsv($fileOpener, $rows ';');

    }

    fclose($fileOpener);

}

目前为止,一切都好。现在,我得到了创建一个过滤器的任务,该过滤器也将应用于CSV文件。我这么说是什么意思?好吧,我在网站上使用过滤器,然后导出CSV文件,它应该只下载过滤器的结果。到目前为止,无论我做什么,它都会下载所有可以下载到最大数量的所有内容。


我试图通过使用$ _GET以某种方式告诉上面的CSV函数仅下载过滤后的结果来完成它。我一直在尝试在控制器中,在调用模型的CSV函数的操作中这样做。


 public function actionExport2CSV() {

    $a = new A();

    $b = new B();


  // This part will output the headers so that the file is downloaded rather than displayed

        header('Content-type: text/csv');

        header('Content-Disposition: attachment; filename=TestFile.csv');


  // do not cache the file

        header('Pragma: no-cache');

        header('Expires: 0');



        $a->convert2CSV(); {

            if (isset($_GET['B'])) {

                $b->attributes = $_GET['B'];

            }

    }

  }

}

感谢您能给我的任何帮助和/或解释。我当然更愿意了解我做错了什么,以便将来学到更多,成为一名更好的程序员。


一只萌萌小番薯
浏览 109回答 2
2回答

慕哥9229398

我使用EExcelview扩展,非常有用。下载并提取代码/protected/extensions/将其添加到您的文件中,如下所示/protected/config/main.php  'import' => array(      'app.models.*',      'app.portlets.*',      'app.components.*',      'app.extensions.*',      ...      'ext.phpexcel.*', # here we are importing the extension    ),在要下载 CSV 文件的视图中添加并优化代码,如下所示: $this->widget('EExcelView', array(      'dataProvider' => $model->search(),      'creator'      => Yii::app()->name,      'grid_mode'    => 'grid',      'title'        => 'CSV File title',      'subject'      => 'CSV File Subject',      'description'  => 'CSV File Description',      'exportText'   => 'Download file ',      'filename'     => urlencode('My file to download'),      'exportType'   => 'CSV', # Available Options => Excel5, Excel2007, PDF, HTML, CSV      'template'     => "{exportbuttons}",      'columns'      => array(          'colA',          'colB'          ...      ),  ));

万千封印

不要介意每个人。我编辑了搜索功能,以便在创建CSV文件之前对其进行过滤。
打开App,查看更多内容
随时随地看视频慕课网APP