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

i7uaboj4  于 2022-11-09  发布在  PHP
关注(0)|答案(2)|浏览(162)

在你进一步阅读之前,如果我在这里做了一个重复,我想道歉。我已经找了很长一段时间了,但没有运气知道如何处理下面的情况。整个事情变得更糟,因为我是一个新手程序员。
“现状"
我从我的高级程序员那里得到了一个任务,要创建一个函数来生成一个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文件以及。我的意思是什么?嗯,wenn我使用过滤器在网站上,然后导出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'];
            }
    }
  }
}

我很感激你能给予我的任何帮助和/或解释。我当然更愿意了解我做错了什么,以便学习更多,在未来成为一个更好的程序员。
非常感谢你们的帮助。
此致。

rnmwe5a2

rnmwe5a21#

我用的是EExcelview扩展,非常有用。
1.下载并解压缩/protected/extensions/中的代码
1.将其添加到/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'
          ...
      ),
  ));
e0bqpujr

e0bqpujr2#

别在意每个人。
我编辑了搜索功能,以便在创建CSV文件之前对其进行筛选。

相关问题