Yii2框架GridView自带导出功能最佳实践
1. 导出excel的实现方法
(1)使用phpexcel封装工具类导出excel
(2)使用爬虫爬取页面再处理封装工具类导出excel
(3)使用页面渲染后处理html添加头部信息生成excel文件的js导出
(4)使用GridView视图组件自带的导出功能
2.代码实现(使用GridView视图组件自带的导出功能)
<?= kartik\grid\GridView::widget([ 'tableOptions' => ['class' => 'table table-striped', 'style'=>'font-size:12px;'], 'layout' => "<div class=\"pull-left div_title\" >库存盘点清单</div><div class=\"pull-right\">{toolbar}</div><div class=\"clearfix\"></div>{items}", 'export'=>[ 'label'=>'导出', 'target'=>kartik\grid\GridView::TARGET_BLANK, ], 'exportConfig'=>[ \kartik\grid\GridView::EXCEL => [ 'label' => Yii::t('app', '导出Excel'), 'icon' =>'file-excel-o', 'iconOptions' => ['class' => 'text-success'], 'showHeader' => true, 'showPageSummary' => true, 'showFooter' => true, 'showCaption' => true, 'filename' => Yii::t('app', '库存盘点清单'), 'alertMsg' => Yii::t('app', '将生成并下载Excel文件'), 'options' => ['title' => Yii::t('app', 'Microsoft Excel 95+')], 'mime' => 'application/vnd.ms-excel', 'config' => [ 'worksheet' => Yii::t('app', '库存盘点清单'), 'cssFile' => '' ] ], ], 'striped'=>false, 'hover'=>true, 'showHeader'=>true, 'showFooter'=>false, 'showPageSummary' => false, 'showOnEmpty'=>true, 'emptyText'=>'当前没有数据!', 'emptyTextOptions'=>['style'=>'color:red;font-weight:bold;text-align:center;'], 'dataProvider' => $dataProvider, 'columns' => $columns, ]); ?>
优点:
(1)代码实现简单,只需在GridView中配置即可
(2)导出的Excel文件格式与GridView相同,包括对齐方式,自动实现统计导出
缺点:
(1)导出按钮的放置位置不方便调整,只能放置在紧贴GridView的位置
3.代码实战(复用searchModel进行数据查询,并使用phpexcel封装工具类导出excel)
(1)封装的Excel导出工具类代码如下:
<?php namespace core\components; use PHPExcel; use PHPExcel_IOFactory; use PHPExcel_Style_Alignment; use PHPExcel_Reader_Excel5; use PHPExcel_RichText; class MyExcelHelper extends \yii\base\Component{ /** * 将二维数组的数据转化为excel表格导出 * @param $data * @param $excel_name * @param $headers * @param $options */ public static function array2excel($data, $excel_name, $headers, $options, $style_options){ $objPHPExcel = new PHPExcel(); ob_start(); if (!isset($options['creator'])){ $objPHPExcel->getProperties()->setCreator('creator'); }else{ $objPHPExcel->getProperties()->setCreator($options['creator']); } if (isset($options['last_modified_by'])){ $objPHPExcel->getProperties()->setCreator('last_modified_by'); }else{ $objPHPExcel->getProperties()->setCreator($options['last_modified_by']); } if (isset($options['title'])){ $objPHPExcel->getProperties()->setCreator('title'); }else{ $objPHPExcel->getProperties()->setCreator($options['title']); } if (isset($options['subject'])){ $objPHPExcel->getProperties()->setCreator('subject'); }else{ $objPHPExcel->getProperties()->setCreator($options['subject']); } if (isset($options['description'])){ $objPHPExcel->getProperties()->setCreator('description'); }else{ $objPHPExcel->getProperties()->setCreator($options['description']); } if (isset($options['keywords'])){ $objPHPExcel->getProperties()->setCreator('keywords'); }else{ $objPHPExcel->getProperties()->setCreator($options['keywords']); } if (isset($options['category'])){ $objPHPExcel->getProperties()->setCreator('category'); }else{ $objPHPExcel->getProperties()->setCreator($options['category']); } $header_keys = array_keys($headers); foreach ($header_keys as $header_index => $header_key){ $index_ascii = $header_index + 65; $index_chr = chr($index_ascii); $header_value = $headers[$header_key]; $objPHPExcel->setActiveSheetIndex(0)->setCellValue($index_chr.'1', $header_value); $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension($index_chr)->setWidth(20); $objPHPExcel->setActiveSheetIndex(0)->getStyle($index_chr.'1')->applyFromArray([ 'font'=>[ 'bold' => true ], 'alignment'=>[ 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER ] ]); if (isset($style_options['h_align'][$header_key])){ if ($style_options['h_align'][$header_key] == 'left'){ $h_align = PHPExcel_Style_Alignment::HORIZONTAL_LEFT; }elseif ($style_options['h_align'][$header_key] == 'center'){ $h_align = PHPExcel_Style_Alignment::HORIZONTAL_CENTER; }elseif ($style_options['h_align'][$header_key] == 'right'){ $h_align = PHPExcel_Style_Alignment::HORIZONTAL_RIGHT; }else{ $h_align = PHPExcel_Style_Alignment::HORIZONTAL_CENTER; } $objPHPExcel->setActiveSheetIndex(0)->getStyle($index_chr)->applyFromArray([ 'alignment'=>[ 'horizontal' => $h_align ] ]); } } $data_row_index = 2; foreach ($data as $row_index => $row){ $data_keys = array_keys($row); foreach ($data_keys as $column_index => $data_key){ if ($column_index>=26){ throw new \yii\base\Exception('EXCEL表格超过26列'); } $index_ascii = $column_index + 65; $index_chr = chr($index_ascii); $value = $row[$data_key]; $objPHPExcel->setActiveSheetIndex(0)->setCellValue($index_chr . $data_row_index, $value); } $data_row_index++; } if (isset($options['summary'])){ $summary_keys = array_keys($options['summary']); foreach ($summary_keys as $summary_index => $summary_key){ $index_ascii = $summary_index + 65; $index_chr = chr($index_ascii); $summary_flag = $options['summary'][$summary_key]; if ($summary_flag){ $summary_value = \core\components\ArrayHelper::sumByColumn($data, $summary_key); $objPHPExcel->setActiveSheetIndex(0)->setCellValue($index_chr . $data_row_index, $summary_value); } } } $objPHPExcel->setActiveSheetIndex(0); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); ob_end_clean(); header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="' . $excel_name . '.xls"'); header('Cache-Control: max-age=0'); $objWriter->save('php://output'); exit; } /** * 将excel表格转化为二维数组的数据 * @param $excel_path * @param $data * @param $header */ public static function excel2array($excel_path, $header_keys){ if(!file_exists($excel_path)){ throw new \yii\base\Exception('该EXCEL不存在!'); } $PHPReader = new \PHPExcel_Reader_Excel2007(); if(!$PHPReader->canRead($excel_path)){ $PHPReader = new PHPExcel_Reader_Excel5(); if(!$PHPReader->canRead($excel_path)){ throw new \yii\base\Exception('该EXCEL不可读'); } } $PHPExcel = $PHPReader->load($excel_path); $currentSheet = $PHPExcel->getSheet(0); $max_column_index = $currentSheet->getHighestColumn(); $max_row_index = $currentSheet->getHighestRow(); $data = array(); for($row_index=2; $row_index<=$max_row_index; $row_index++ ){ for($column_chr='A'; $column_chr<=$max_column_index; $column_chr++){ $column_ord = ord($column_chr); $column_index = $column_ord - 65; $key = $column_chr.$row_index; $value = $currentSheet->getCell($key)->getValue(); if($value instanceof PHPExcel_RichText){ $value = $value->__toString(); } $data[$row_index-1][$header_keys[$column_index]] = $value; } } return $data; } }
(2)导出业务逻辑类:
<?php namespace backend\models; use Yii; class SheetExportAdapter{ //在适配器中引用数据查询模型 public $searchModel; //构造方法,传入数据查询模型,引用进行数据的查询 public function __construct($searchModel) { $this->searchModel = $searchModel; } /** * 导出业务逻辑接口 */ public function export(){} } class WmsPartiallyProductInSheetExport extends SheetExportAdapter { /** * 导出类的业务逻辑实现,先从搜索模型中获取参数,再调用搜索模型进行数据查询,最后调用导出工具类进行导出 */ public function export(){ $params = []; $params['WmsPartiallyProductInSheetSearch']['search_type'] = $this->searchModel->search_type; $params['WmsPartiallyProductInSheetSearch']['common_producer_info_id'] = $this->searchModel->common_producer_info_id; $params['WmsPartiallyProductInSheetSearch']['common_producer_herb_info_id_product'] = $this->searchModel->common_producer_herb_info_id_product; $params['WmsPartiallyProductInSheetSearch']['begin_at'] = $this->searchModel->begin_at; $params['WmsPartiallyProductInSheetSearch']['end_at'] = $this->searchModel->end_at; $dataProvider = $this->searchModel->search($params, true); $data = []; foreach ($dataProvider->getModels() as $model){ $wms_partially_product_in_sheet_number = $model->wms_partially_product_in_sheet_number; if ($model->is_del == 1) { $wms_partially_product_in_sheet_number .= '('.$model->stock_origin_type.')(已作废)'; }else{ $wms_partially_product_in_sheet_number .= '('.$model->stock_origin_type.')'; } $common_producer_herb_info_name_product = $model->common_producer_herb_info_name_product; $common_producer_herb_grade_name_product = $model->common_producer_herb_grade_name_product; $common_producer_herb_place_info_name = $model->common_producer_herb_place_info_name; if (\core\models\WmsManager::PIECE_TYPE_STANDARD == $model->piece_type){ $piece_type_name = '标准件'; }elseif(\core\models\WmsManager::PIECE_TYPE_OFF_STANDARD == $model->piece_type){ $piece_type_name = '非标准件'; }else{ $piece_type_name = '未设置'; } if (!\core\models\WmsManager::getIsShowWeightPerPackage($model->piece_type)){ $wms_partially_product_in_sheet_weight_per_package = '无'; }else{ $wms_partially_product_in_sheet_weight_per_package = \common\models\Base::weightBcdiv($model->wms_partially_product_in_sheet_weight_per_package); } if (empty($model->wms_partially_product_in_sheet_package_number)){ $wms_partially_product_in_sheet_package_number = '未设置'; }else{ $wms_partially_product_in_sheet_package_number = \core\models\WmsManager::showTotalPackageNumber($model->wms_partially_product_in_sheet_package_number, $model->standard_package_number, $model->off_standard_package_number, $model->piece_type); } $wms_partially_product_in_sheet_in_weight = \common\models\Base::weightBcdiv($model->wms_partially_product_in_sheet_in_weight); $modelDetail = \core\models\WmsStockDetailInfo::findNotDel()->where([ 'wms_stock_detail_info_relation_good_in_sheet_number' => $model->wms_partially_product_in_sheet_number, 'common_producer_material_type_info_id' => \core\models\WmsStockDetailInfo::wmsMaterialType()['partiallyProductType']])->one(); $surplus_weight = $modelDetail&&$modelDetail->wms_stock_detail_info_weight?\common\models\Base::weightBcdiv($modelDetail->wms_stock_detail_info_weight):0; if (empty($model->wms_partially_product_in_sheet_product_in_date)){ $wms_partially_product_in_sheet_product_in_date = '未知'; }else{ $wms_partially_product_in_sheet_product_in_date = date('Y-m-d', $model->wms_partially_product_in_sheet_product_in_date); } $wms_partially_product_in_sheet_status_name = (!$model->wms_partially_product_in_sheet_status||$model->wms_partially_product_in_sheet_status==0)?'未确认入库':"已入库"; $wmsPartiallyProductInSheetQualityCheckNumber = $model->getWmsPartiallyProductInSheetQualityCheckNumber(); if ('<span style="color: red;">未质检</span>' == $wmsPartiallyProductInSheetQualityCheckNumber){ $wmsPartiallyProductInSheetQualityCheckNumber = '未质检'; } $data[] = [ 'wms_partially_product_in_sheet_number'=>$wms_partially_product_in_sheet_number, 'common_producer_herb_info_name_product'=>$common_producer_herb_info_name_product, 'common_producer_herb_grade_name_product'=>$common_producer_herb_grade_name_product, 'common_producer_herb_place_info_name'=>$common_producer_herb_place_info_name, 'piece_type_name'=>$piece_type_name, 'wms_partially_product_in_sheet_weight_per_package'=>$wms_partially_product_in_sheet_weight_per_package, 'wms_partially_product_in_sheet_package_number'=>$wms_partially_product_in_sheet_package_number, 'wms_partially_product_in_sheet_in_weight'=>$wms_partially_product_in_sheet_in_weight, 'surplus_weight'=>$surplus_weight, 'wms_partially_product_in_sheet_product_in_date'=>$wms_partially_product_in_sheet_product_in_date, 'wms_partially_product_in_sheet_status_name'=>$wms_partially_product_in_sheet_status_name, 'wmsPartiallyProductInSheetQualityCheckNumber'=>$wmsPartiallyProductInSheetQualityCheckNumber, ]; } $excel_name = '半成品入库单'; $headers = [ 'wms_partially_product_in_sheet_number'=>'入库单号', 'common_producer_herb_info_name_product'=>'半成品名称', 'common_producer_herb_grade_name_product'=>'半成品等级', 'common_producer_herb_place_info_name'=>'半成品产地', 'piece_type_name'=>'计件类型', 'wms_partially_product_in_sheet_weight_per_package'=>'包装规格', 'wms_partially_product_in_sheet_package_number'=>'入库件数', 'wms_partially_product_in_sheet_in_weight'=>'入库重量(公斤)', 'surplus_weight'=>'剩余重量(公斤)', 'wms_partially_product_in_sheet_product_in_date'=>'入库日期', 'wms_partially_product_in_sheet_status_name'=>'入库状态', 'wmsPartiallyProductInSheetQualityCheckNumber'=>'质检号', ]; $options = [ 'creator'=>'中国汉广集团IT信息中心', 'last_modified_by'=>'中国汉广集团IT信息中心', 'title'=>$excel_name, 'subject'=>$excel_name, 'description'=>'半成品入库单', 'keywords'=>'半成品入库单', 'category'=>'半成品入库单', 'summary'=>[ 'wms_partially_product_in_sheet_number'=>false, 'common_producer_herb_info_name_product'=>false, 'common_producer_herb_grade_name_product'=>false, 'common_producer_herb_place_info_name'=>false, 'piece_type_name'=>false, 'wms_partially_product_in_sheet_weight_per_package'=>false, 'wms_partially_product_in_sheet_package_number'=>true, 'wms_partially_product_in_sheet_in_weight'=>true, 'surplus_weight'=>true, 'wms_partially_product_in_sheet_product_in_date'=>false, 'wms_partially_product_in_sheet_status_name'=>false, 'wmsPartiallyProductInSheetQualityCheckNumber'=>false, ] ]; $style_options = [ 'h_align'=>[ 'wms_partially_product_in_sheet_number'=>'left', 'common_producer_herb_info_name_product'=>'center', 'common_producer_herb_grade_name_product'=>'center', 'common_producer_herb_place_info_name'=>'center', 'piece_type_name'=>'center', 'wms_partially_product_in_sheet_weight_per_package'=>'right', 'wms_partially_product_in_sheet_package_number'=>'right', 'wms_partially_product_in_sheet_in_weight'=>'right', 'surplus_weight'=>'right', 'wms_partially_product_in_sheet_product_in_date'=>'center', 'wms_partially_product_in_sheet_status_name'=>'center', 'wmsPartiallyProductInSheetQualityCheckNumber'=>'center', ] ]; //调用导出工具类进行导出 \core\components\MyExcelHelper::array2excel($data, $excel_name, $headers, $options, $style_options); } }
(3)控制器行为:
public function actionExport($serialized_model){ $wmsPartiallyProductInSheetSearch = unserialize($serialized_model); $wmsPartiallyProductInSheetExport = new \backend\models\WmsPartiallyProductInSheetExport($wmsPartiallyProductInSheetSearch); $wmsPartiallyProductInSheetExport->export(); }
优点:
(1)自己实现导出工具类,容易掌控代码,实现了封装的思想
(2)使用导出适配器,进一步封装了导出逻辑
Yii2框架GridView自带导出功能最佳实践的更多相关文章
- java 导出 excel 最佳实践,java 大文件 excel 避免OOM(内存溢出) excel 工具框架
产品需求 产品经理需要导出一个页面的所有的信息到 EXCEL 文件. 需求分析 对于 excel 导出,是一个很常见的需求. 最常见的解决方案就是使用 poi 直接同步导出一个 excel 文件. 客 ...
- laravel框架excel 的导入导出功能
1.简介 Laravel Excel 在 Laravel 5 中集成 PHPOffice 套件中的 PHPExcel,从而方便我们以优雅的.富有表现力的代码实现Excel/CSV文件的导入和导出. ...
- yii2下拉框带搜索功能
简单的小功能,但是用起来还是蛮爽的.分享出来让更多的人有更快的开发效率,开开心心快乐编程.作者:白狼 出处:http://www.manks.top/yii2_dropdown_search.html ...
- YII2框架下使用PHPExcel导出柱状图
导出结果: 首先,到官网下载PHPExcel插件包,下载后文件夹如下: 将Classes文件夹放入到项目公共方法内. 新建控制器(访问导出的方法):EntryandexitController < ...
- python3开发进阶-Django框架的自带认证功能auth模块和User对象的基本操作
阅读目录 auth模块 User对象 认证进阶 一.auth模块 from django.contrib import auth django.contrib.auth中提供了许多方法,这里主要介绍其 ...
- JavaScript Web 应用最佳实践分析
[编者按]本文作者为 Mathias Schäfer,旨在回顾在客户端大量使用JavaScript 的最佳 Web应用实践.文章系国内 ITOM 管理平台 OneAPM 编译呈现. 对笔者来说,Jav ...
- GridView使用自带分页功能时分页方式及样式PagerStyle
// 转向地址:http://www.bubuko.com/infodetail-412562.html GridView分页,使用自带分页功能,类似下面样式: 在aspx页面中,GridView上的 ...
- atitit. 统计功能框架的最佳实践(1)---- on hibernate criteria
atitit. 统计功能框架的最佳实践(1)---- on hibernate criteria 1. 关键字 1 2. 统计功能框架普通有有些条件选项...一个日期选项..一个日期类型(日,周,月份 ...
- SSI框架下,用jxl实现导出功能
SSI框架下,用jxl实现导出功能 先说明一下,这个是SSI框架下,前端用ExtJs,应用在一个企业级的系统中的导出功能,因为是摸索着做的,所以里面有一些代码想整理一下,如果有人看到了,请视自己的架构 ...
随机推荐
- P1577 切绳子(二分)
思路:先来分析一下数据范围,是1e4个数据,但是,是double类型,结果不超过0.01那么在绳子最大的情况下,单纯的找正确答案暴力的话就是1e7的时间复杂度,再乘上1e4的数据,这样肯定不行.那么很 ...
- pytorch例子学习-DATA LOADING AND PROCESSING TUTORIAL
参考:https://pytorch.org/tutorials/beginner/data_loading_tutorial.html DATA LOADING AND PROCESSING TUT ...
- 简单使用普通用户启动tomcat
新建用户tomcat,该用户不能登录 useradd tomcat -s '/sbin/nologin' 将/usr/local/tomcat/bin/startup.sh更名 mv /usr/loc ...
- 异步操作之 Promise 和 Async await 用法进阶
ES6 提供的 Promise 方法和 ES7 提供的 Async/Await 语法糖都可以更好解决多层回调问题, 详细用法可参考:https://www.cnblogs.com/cckui/p/99 ...
- HBase篇(5)- BloomFilter
[每日五分钟搞定大数据]系列,HBase第五篇.上一篇我们落下了Bloom Filter,这次我们来聊聊这个东西. Bloom Filter 是什么? 先简单的介绍下Bloom Filter(布隆过滤 ...
- [WPF]如何使用代码创建DataTemplate(或者ControlTemplate)
1. 前言 上一篇文章([UWP]如何使用代码创建DataTemplate(或者ControlTemplate))介绍了在UWP上的情况,这篇文章再稍微介绍在WPF上如何实现. 2. 使用Framew ...
- H5 25-CSS三大特性之层叠性
25-CSS三大特性之层叠性 我是段落 <!DOCTYPE html> <html lang="en"> <head> <meta cha ...
- c++入门之运算符重载
c++函数重载:可以将一个函数名用于不同功能的函数.从而处理不同的对象.对于运算符,同样也有这样的用途,即对同一个标志符的运算符,可以运用到不同的功能中去. 首先引入:运算符重载,在C语言中甚至都有运 ...
- DOM节点左右移动
闲来没事写了个小demo,原本是回答别人博问的,有人比我更快的给出了链接,想想半途而废也不好,就写完了,写个博文记录一下(效果是按照我自己来的,可能和最早别人问的不太一样,反正无关紧要啦) 直接上co ...
- 使用队列queue实现一个简单的生产者消费者模型
一.生产者消费者模型 我们去超市商店等地购买商品时,我们大部分人都会说自己是消费者,而超市的各大供货商.工厂等,自然而然地也就成了我们的生产者.如此一来,生产者有了,消费者也有了,那么将二者联系起来的 ...