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,应用在一个企业级的系统中的导出功能,因为是摸索着做的,所以里面有一些代码想整理一下,如果有人看到了,请视自己的架构 ...
随机推荐
- 微信小程序PHP 微信支付接口调用
小程序端 /** * 微信支付接口 */ wxPaymoney:function (out_trade_no, true_money){ //out_trade_no 后台统一下单接口需要用 var ...
- Python:Day19 正则表达式补充
贪婪匹配 贪婪匹配是指字符后面是*+?的时候,都是尽可能多的匹配,如果不想尽可能多的匹配,那么在这三个字符后面加?号即可,这样变成惰性匹配,按最少匹配. ret = re.findall('ab??' ...
- 008_Node中的require和import
一.js的对象的解构赋值 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuri ...
- nginx之十三:搭建 nginx 反向代理用做内网域名转发
user www www;worker_processes 1;error_log logs/error.log;pid logs/nginx.pid;worker_rlimit_nofile 6 ...
- java对象比较
public class InternDemo { public static void main(String[] args){ /* jdk7版本之后 字符串常量池从Perm Space移到Jav ...
- 20175330 实验二《Java面向对象程序设计》实验报告
一.前期准备:unit的安装与使用:打开idea,Preferences中点击Plugins,在market中搜索junit,如图点选JUnitGenerator V2.0进行安装,安装后会显示ins ...
- [USACO5.3]校园网Network of Schools
题目描述 一些学校连入一个电脑网络.那些学校已订立了协议:每个学校都会给其它的一些学校分发软件(称作“接受学校”).注意即使 B 在 A 学校的分发列表中, A 也不一定在 B 学校的列表中. 你要写 ...
- C#高性能二进制序列化
二进制序列化可以方便快捷的将对象进行持久化或者网络传输,并且体积小.性能高,应用面甚至还要高于json的序列化:开始之前,先来看看dotcore/dotne自带的二进制序列化:C#中对象序列化和反序列 ...
- odoo学习总结
odoo10总结 1.odoo中的向导应用. .py文件 # -*- coding: utf-8 -*-f ...
- Gym101237C The Palindrome Extraction Manacher、SAM、倍增
传送门 假设字符串\(B,D\)满足\(|B| \geq |D|\),那么一定会有\(B=rev(D)+T\),其中\(T\)是一个回文串. 考虑枚举回文串\(T\)的中心\(p\),找到以\(p\) ...