很久没来更新了,看一下时间,上一篇还是2个月前,最近有点忙,翻了下Yii2的代码,有个项目用了kartik的gridview的导出功能,这里顺便开个话题吧。
kartik的gridview默认自带导出功能,通过设置其exportConfig属性来进行导出的配置:
$defaultExportConfig = [ GridView::CSV => [ 'label' => '导出为CSV', 'iconOptions' => ['class' => 'glyphicon glyphicon-save-file'], ], ]; echo GridView::widget([ ...//中间略 'export' => [ 'label' => '导出', ], 'exportConfig' => $defaultExportConfig, ]);
但是上述导出的,只能是当前表的所有数据,如果你在gridview里进行了筛选,筛选结果只有10条的话,导出仍然是所有的数据。这种情况下,默认的导出功能就变得鸡肋了,这时需要自定义按钮来实现。
'toolbar' => [ [ 'content' => Html::a('导出', ['exportfile', Yii::$app->request->getQueryParams()], [ 'class' => 'btn btn-info', 'title' => '导出当前订单', 'target' => '_blank', 'data-pjax' => 0, ]), 'options' => ['class' => 'btn-group'] ], ],
然后在控制器里建立actionExportfile方法:
public function actionExportfile() { $gets = Yii::$app->request->get(); if (isset($gets[1]) && null !== $gets[1]['OrdersSearch']) { $exportarray = $this->getwhere($gets[1]['OrdersSearch']); $exportfields = array('field1', 'field2', '...'); //导出第一行字段 $this->export2excel($exportarray, $exportfields); } } private function getwhere($arr) { $sql = 'select * from ...'; //要查询的sql $ret = Yii::$app->db->createCommand($sql)->queryAll(); return $ret; } private function export2excel($data, $header, $title = "export_proc", $filename = "export_file") { if (!is_array($data) || !is_array($header)) return false; $objPHPExcel = new \PHPExcel(); $objPHPExcel->getProperties()->setCreator("Xlplat"); $objPHPExcel->getProperties()->setLastModifiedBy("Xlplat"); $objPHPExcel->getProperties()->setTitle("export_orders"); $objPHPExcel->getProperties()->setSubject("export_orders"); $objPHPExcel->getProperties()->setDescription("export_orders"); //设置表头,也就是第一行数据 foreach ($header as $k => $v){ $column = \PHPExcel_Cell::stringFromColumnIndex($k); $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($column."1", $v); } //设置行数据,从第二行开始 foreach ($data as $key=>$item){ foreach ($item as $key2=>$val){ $column = \PHPExcel_Cell::stringFromColumnIndex($key2); //获得列位置 $objPHPExcel->setActiveSheetIndex(0)->setCellValue($column.($key+2), $val); } } // Rename sheet $objPHPExcel->getActiveSheet()->setTitle($title); // Redirect output to a client’s web browser (Excel5) header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="'.$filename.'.xls"'); header('Cache-Control: max-age=0'); // If you're serving to IE 9, then the following may be needed header('Cache-Control: max-age=1'); // If you're serving to IE over SSL, then the following may be needed header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header ('Pragma: public'); // HTTP/1.0 $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); }
这样点击gridview的导出按钮时,导出的数据源和筛选同步。
文章评分1次,平均分5.0:★★★★★
文章不错非常喜欢,支持