繁体   English   中英

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

[英]How to download a filtered CSV file with PHP using Yii 1.1 framework

在您进一步阅读之前,如果我在这里复制,我想道歉。 我已经环顾了很长一段时间,但对如何处理以下情况没有任何运气。 由于我是一个新手程序员,整个事情变得更糟。

情况

我在工作时从我的高级程序员那里得到了一项任务,即创建一个可以生成 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'];
            }
    }
  }
}

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

非常感谢你们的帮助。

亲切的问候。

我用的是EExcelview扩展,非常有用。

  1. 下载并解压/protected/extensions/的代码
  2. 将它添加到您的/protected/config/main.php文件中,如下所示
  'import' => array(
      'app.models.*',
      'app.portlets.*',
      'app.components.*',
      'app.extensions.*',
      ...
      'ext.phpexcel.*', # here we are importing the extension
    ),
  1. 在要下载 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 文件之前对其进行过滤。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM