Advertisement
krot

YII2 ExcelGrid

May 16th, 2018
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.02 KB | None | 0 0
  1. <?php
  2. namespace frontend\components\ExcelGrid;
  3.  
  4. use Yii;
  5. use Closure;
  6. use yii\i18n\Formatter;
  7. use yii\base\InvalidConfigException;
  8. use yii\helpers\Url;
  9. use yii\helpers\Html;
  10. use yii\helpers\Json;
  11. use yii\helpers\ArrayHelper;
  12. use yii\widgets\BaseListView;
  13. use yii\base\Model;
  14. use \PHPExcel;
  15. use \PHPExcel_IOFactory;
  16. use \PHPExcel_Settings;
  17. use \PHPExcel_Style_Fill;
  18. use \PHPExcel_Writer_IWriter;
  19. use \PHPExcel_Worksheet;
  20.  
  21. class ExcelGrid extends \yii\grid\GridView
  22. {
  23.     public $columns_array;
  24.     public $properties;
  25.     public $filename='excel';
  26.     public $extension='xlsx';
  27.     private $_provider;
  28.     private $_visibleColumns;
  29.     private $_beginRow = 1;
  30.     private $_endRow;
  31.     private $_endCol;
  32.     private $_objPHPExcel;
  33.     private $_objPHPExcelSheet;
  34.     private $_objPHPExcelWriter;   
  35.     public function init(){
  36.         parent::init();
  37.     }
  38.     public function run(){
  39.         //$this->test();
  40.         $this->init_provider();
  41.         $this->init_excel_sheet();
  42.         $this->initPHPExcelWriter('Excel2007');
  43.         $this->generateHeader();
  44.         $row = $this->generateBody();
  45.         $writer = $this->_objPHPExcelWriter;
  46.         $this->setHttpHeaders();
  47.         $writer->save('php://output');
  48.         Yii::$app->end();
  49.         //$writer->save('test.xlsx');
  50.         parent::run();
  51.     }
  52.    
  53.     public function init_provider(){
  54.         $this->_provider = clone($this->dataProvider);
  55.     }
  56.     public function init_excel_sheet(){
  57.         $this->_objPHPExcel=new PHPExcel();
  58.  
  59.         $creator = '';
  60.         $title = '';
  61.         $subject = '';
  62.         $description = 'Excel Grid Generated';
  63.         $category = '';
  64.         $keywords = '';
  65.         $manager = '';
  66.         $company = 'CODE';
  67.         $created = date("Y-m-d H:i:s");
  68.         $lastModifiedBy = '';
  69.         @extract($this->properties);
  70.         $this->_objPHPExcel->getProperties()
  71.             ->setCreator($creator)
  72.             ->setTitle($title)
  73.             ->setSubject($subject)
  74.             ->setDescription($description)
  75.             ->setCategory($category)
  76.             ->setKeywords($keywords)
  77.             ->setManager($manager)
  78.             ->setCompany($company)
  79.             ->setCreated($created)
  80.             ->setLastModifiedBy($lastModifiedBy);
  81.         $this->_objPHPExcelSheet = $this->_objPHPExcel->getActiveSheet();
  82.     }
  83.     public function initPHPExcelWriter($writer)
  84.     {
  85.         $this->_objPHPExcelWriter = PHPExcel_IOFactory::createWriter(
  86.             $this->_objPHPExcel,
  87.             $writer
  88.         );
  89.     }
  90.     public function generateHeader(){
  91.         $this->setVisibleColumns();
  92.         $sheet = $this->_objPHPExcelSheet;
  93.         $colFirst = self::columnName(1);
  94.  
  95.         $this->_endCol = 0;
  96.         foreach ($this->_visibleColumns as $column) {
  97.             $this->_endCol++;
  98.             $head = ($column instanceof \yii\grid\DataColumn) ? $this->getColumnHeader($column) : $column->header;
  99.             $cell = $sheet->setCellValue(self::columnName($this->_endCol) . $this->_beginRow, $head, true);
  100.         }
  101.         $sheet->freezePane($colFirst . ($this->_beginRow + 1));
  102.     }
  103.    
  104.     public function generateBody()
  105.     {
  106.         $columns = $this->_visibleColumns;
  107.         $models = array_values($this->_provider->getModels());
  108.         if (count($columns) == 0) {
  109.             $cell = $this->_objPHPExcelSheet->setCellValue('A1', $this->emptyText, true);
  110.             $model = reset($models);
  111.             return 0;
  112.         }
  113.         $keys = $this->_provider->getKeys();
  114.         $this->_endRow = 0;
  115.         foreach ($models as $index => $model) {
  116.             $key = $keys[$index];
  117.             $this->generateRow($model, $key, $index);
  118.             $this->_endRow++;
  119.         }
  120.  
  121.         // Set autofilter on
  122.         $this->_objPHPExcelSheet->setAutoFilter(
  123.             self::columnName(1) .
  124.             $this->_beginRow .
  125.             ":" .
  126.             self::columnName($this->_endCol) .
  127.             $this->_endRow
  128.         );
  129.         return ($this->_endRow > 0) ? count($models) : 0;
  130.     }
  131.    
  132.     public function generateRow($model, $key, $index)
  133.     {
  134.         $cells = [];
  135.         /* @var $column Column */
  136.         $this->_endCol = 0;
  137.         foreach ($this->_visibleColumns as $column) {
  138.             if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
  139.                 continue;
  140.             } else {
  141.                 $format = $column->format;
  142.                 $value = ($column->content === null) ?
  143.                     $this->formatter->format($column->getDataCellValue($model, $key, $index), $format) :
  144.                     call_user_func($column->content, $model, $key, $index, $column);
  145.             }
  146.             if (empty($value) && !empty($column->attribute) && $column->attribute !== null) {
  147.                 $value =ArrayHelper::getValue($model, $column->attribute, '');
  148.             }
  149.             $this->_endCol++;
  150.             $cell = $this->_objPHPExcelSheet->setCellValue(self::columnName($this->_endCol) . ($index + $this->_beginRow + 1),
  151.                 strip_tags($value), true);
  152.         }
  153.     }
  154.    
  155.     protected function setVisibleColumns()
  156.     {
  157.         $cols = [];
  158.         foreach ($this->columns as $key => $column) {
  159.             if ($column instanceof \yii\grid\SerialColumn || $column instanceof \yii\grid\ActionColumn) {
  160.                 continue;
  161.             }
  162.             $cols[] = $column;
  163.         }
  164.         $this->_visibleColumns = $cols;
  165.     }
  166.    
  167.     public function getColumnHeader($col)
  168.     {
  169.         if(isset($this->columns_array[$col->attribute]))
  170.             return $this->columns_array[$col->attribute];
  171.         /* @var $model yii\base\Model */
  172.         if ($col->header !== null || ($col->label === null && $col->attribute === null)) {
  173.             return trim($col->header) !== '' ? $col->header : $col->grid->emptyCell;
  174.         }
  175.         $provider = $this->dataProvider;
  176.         if ($col->label === null) {
  177.             if ($provider instanceof ActiveDataProvider && $provider->query instanceof ActiveQueryInterface) {
  178.                 $model = new $provider->query->modelClass;
  179.                 $label = $model->getAttributeLabel($col->attribute);
  180.             } else {
  181.                 $models = $provider->getModels();
  182.                 if (($model = reset($models)) instanceof Model) {
  183.                     $label = $model->getAttributeLabel($col->attribute);
  184.                 } else {
  185.                     $label =$col->attribute;
  186.                 }
  187.             }
  188.         } else {
  189.             $label = $col->label;
  190.         }
  191.         return $label;
  192.     }
  193.     public static function columnName($index)
  194.     {
  195.         $i = $index - 1;
  196.         if ($i >= 0 && $i < 26) {
  197.             return chr(ord('A') + $i);
  198.         }
  199.         if ($i > 25) {
  200.             return (self::columnName($i / 26)) . (self::columnName($i % 26 + 1));
  201.         }
  202.         return 'A';
  203.     }
  204.    
  205.     protected function setHttpHeaders()
  206.     {
  207.         header("Cache-Control: no-cache");
  208.         header("Expires: 0");
  209.         header("Pragma: no-cache");
  210.         header("x-man: 1");
  211.         header("Content-Type: application/vnd.ms-excel");
  212.         header("Content-Disposition: attachment; filename={$this->filename}.{$this->extension}");  
  213.         Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
  214.     }
  215. }
  216. use:
  217. <?php
  218.     // \app\components\ExcelGrid::widget([ OR
  219.     \bsource\gridview\ExcelGrid::widget([
  220.         'dataProvider' => $dataProvider,
  221.         'filterModel' => $searchModel,
  222.         //'extension'=>'xlsx',
  223.         //'filename'=>'excel',
  224.         'properties' => [
  225.             //'creator' =>'',
  226.             //'title' => '',
  227.             //'subject' => '',
  228.             //'category' => '',
  229.             //'keywords' => '',
  230.             //'manager' => '',
  231.             //'description'=>'BSOURCECODE',
  232.             //'company' =>'BSOURCE',
  233.         ],
  234.         'columns' => [
  235.             ['class' => 'yii\grid\SerialColumn'],
  236.             'username',
  237.             'createdby',
  238.             'createdon',
  239.         ],
  240.     ]);
  241.  
  242.  
  243.     Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
  244.                     $this->renderPartial('stat',[
  245.                                         'pList'=>..
  246.                                         'exportType'=>'xlsx'
  247.                                         ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement