forked from kartik-v/yii2-export
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExportMenu.php
executable file
·1746 lines (1624 loc) · 63.7 KB
/
ExportMenu.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @package yii2-export
* @author Kartik Visweswaran <[email protected]>
* @copyright Copyright © Kartik Visweswaran, Krajee.com, 2015 - 2016
* @version 1.2.7
*/
namespace kartik\export;
use Closure;
use kartik\base\TranslationTrait;
use kartik\dynagrid\Dynagrid;
use kartik\grid\GridView;
use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Settings;
use PHPExcel_Style_Fill;
use PHPExcel_Worksheet;
use PHPExcel_Writer_Abstract;
use PHPExcel_Writer_CSV;
use Yii;
use yii\base\InvalidConfigException;
use yii\base\Model;
use yii\bootstrap\ButtonDropdown;
use yii\data\ActiveDataProvider;
use yii\data\BaseDataProvider;
use yii\db\ActiveQueryInterface;
use yii\grid\ActionColumn;
use yii\grid\Column;
use yii\grid\DataColumn;
use yii\grid\SerialColumn;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Inflector;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\JsExpression;
use yii\web\View;
use kartik\dialog\Dialog;
/**
* Export menu widget. Export tabular data to various formats using the PHPExcel library by reading data from a
* dataProvider - with configuration very similar to a GridView.
*
* @author Kartik Visweswaran <[email protected]>
* @since 1.0
*/
class ExportMenu extends GridView
{
use TranslationTrait;
/**
* Export formats
*/
const FORMAT_HTML = 'HTML';
const FORMAT_CSV = 'CSV';
const FORMAT_TEXT = 'TXT';
const FORMAT_PDF = 'PDF';
const FORMAT_EXCEL = 'Excel5';
const FORMAT_EXCEL_X = 'Excel2007';
/**
* Export form submission targets
*/
const TARGET_POPUP = '_popup';
const TARGET_SELF = '_self';
const TARGET_BLANK = '_blank';
/**
* Input parameters from export form
*/
const PARAM_EXPORT_TYPE = 'export_type';
const PARAM_EXPORT_COLS = 'export_columns';
const PARAM_COLSEL_FLAG = 'column_selector_enabled';
/**
* @var string the target for submitting the export form, which will trigger the download of the exported file.
* Must be one of the `TARGET_` constants. Defaults to `ExportMenu::TARGET_POPUP`. Note if you set `stream` and
* `streamAfterSave` to `false`, then this will be overridden to `_self`.
*/
public $target = self::TARGET_POPUP;
/**
* @var array configuration settings for the Krajee dialog widget that will be used to render alerts and
* confirmation dialog prompts
* @see http://demos.krajee.com/dialog
*/
public $krajeeDialogSettings = [];
/**
* @var bool whether to show a confirmation alert dialog before download. This confirmation dialog will notify user
* about the type of exported file for download and to disable popup blockers. Defaults to `true`.
*/
public $showConfirmAlert = true;
/**
* @var bool whether to enable the yii gridview formatter component. Defaults to `true`. If set to `false`, this
* will render content as `raw` format.
*/
public $enableFormatter = true;
/**
* @var bool whether to render the export menu as bootstrap button dropdown widget. Defaults to `true`. If set to
* `false`, this will generate a simple HTML list of links.
*/
public $asDropdown = true;
/**
* @var string the pjax container identifier inside which this menu is being rendered. If set the jQuery export
* menu plugin will get auto initialized on pjax request completion.
*/
public $pjaxContainerId;
/**
* @var array the HTML attributes for the export button menu. Applicable only if `asDropdown` is set to `true`. The
* following special options are available:
* - label: string, defaults to empty string
* - icon: string, defaults to `<i class="glyphicon glyphicon-export"></i>`
* - title: string, defaults to `Export data in selected format`.
* - menuOptions: array, the HTML attributes for the dropdown menu.
* - itemsBefore: array, any additional items that will be merged/prepended before with the export dropdown list.
* This should be similar to the `items` property as supported by `\yii\bootstrap\ButtonDropdown` widget. Note
* the page export items will be automatically generated based on settings in the `exportConfig` property.
* - itemsAfter: array, any additional items that will be merged/appended after with the export dropdown list. This
* should be similar to the `items` property as supported by `\yii\bootstrap\ButtonDropdown` widget. Note the
* page export items will be automatically generated based on settings in the `exportConfig` property.
*/
public $dropdownOptions = ['class' => 'btn btn-default'];
/**
* @var bool whether to clear all previous / parent buffers. Defaults to `false`.
*/
public $clearBuffers = false;
/**
* @var bool whether to initialize data provider and clear models before rendering. Defaults to `false`.
*/
public $initProvider = false;
/**
* @var bool whether to show a column selector to select columns for export. Defaults to `true`.
*/
public $showColumnSelector = true;
/**
* @var array the configuration of the column names in the column selector. Note: column names will be generated
* automatically by default. Any setting in this property will override the auto-generated column names. This
* list should be setup as `$key => $value` where:
* $key: int, is the zero based index of the column as set in `$columns`.
* $value: string, is the column name/label you wish to display in the column selector.
*/
public $columnSelector = [];
/**
* @var array the HTML attributes for the column selector dropdown button. The following special options are
* recognized:
* - label: string, defaults to empty string.
* - icon: string, defaults to `<i class="glyphicon glyphicon-list"></i>`
* - title: string, defaults to `Select columns for export`.
*/
public $columnSelectorOptions = [];
/**
* @var array the HTML attributes for the column selector menu list.
*/
public $columnSelectorMenuOptions = [];
/**
* @var array the settings for the toggle all checkbox to check / uncheck the columns as a batch. Should be setup as
* an associative array which can have the following keys:
* - `show`: bool, whether the batch toggle checkbox is to be shown. Defaults to `true`.
* - `label`: string, the label to be displayed for toggle all. Defaults to `Toggle All`.
* - `options`: array, the HTML attributes for the toggle label text. Defaults to `['class'=>'kv-toggle-all']`
*/
public $columnBatchToggleSettings = [];
/**
* @var array, HTML attributes for the container to wrap the widget. Defaults to ['class'=>'btn-group',
* 'role'=>'group']
*/
public $container = ['class' => 'btn-group', 'role' => 'group'];
/**
* @var string, the template for rendering the content in the container. This will be parsed only if `asDropdown`
* is `true`. The following tags will be replaced:
* - {columns}: will be replaced with the column selector dropdown
* - {menu}: will be replaced with export menu dropdown
*/
public $template = "{columns}\n{menu}";
/**
* @var int timeout for the export function (in seconds), if timeout is < 0, the default PHP timeout will be used.
*/
public $timeout = -1;
/**
* @var array the HTML attributes for the export form.
*/
public $exportFormOptions = [];
/**
* @var array the selected column indexes for export. If not set this will default to all columns.
*/
public $selectedColumns;
/**
* @var array the column indexes for export that will be disabled for selection in the column selector.
*/
public $disabledColumns = [];
/**
* @var array the column indexes for export that will be hidden for selection in the column selector, but will
* still be displayed in export output.
*/
public $hiddenColumns = [];
/**
* @var array the column indexes for export that will not be exported at all nor will they be shown in the column
* selector
*/
public $noExportColumns = [];
/**
* @var string the view file for rendering the export form
*/
public $exportFormView = '_form';
/**
* @var string the view file for rendering the columns selection
*/
public $exportColumnsView = '_columns';
/**
* @var boolean whether to use font awesome icons for rendering the icons as defined in `exportConfig`. If set to
* `true`, you must load the FontAwesome CSS separately in your application.
*/
public $fontAwesome = false;
/**
* @var array the export configuration. The array keys must be the one of the `format` constants (CSV, HTML, TEXT,
* EXCEL, PDF) and the array value is a configuration array consisting of these settings:
* - label: string, the label for the export format menu item displayed
* - icon: string, the glyphicon or font-awesome name suffix to be displayed before the export menu item label. If
* set to an empty string, this will not be displayed.
* - iconOptions: array, HTML attributes for export menu icon.
* - linkOptions: array, HTML attributes for each export item link.
* - filename: the base file name for the generated file. Defaults to 'grid-export'. This will be used to generate
* a default file name for downloading.
* - extension: the extension for the file name
* - alertMsg: string, the message prompt to show before saving. If this is empty or not set it will not be
* displayed.
* - mime: string, the mime type (for the file format) to be set before downloading.
* - writer: string, the PHP Excel writer type
* - options: array, HTML attributes for the export menu item.
*/
public $exportConfig = [];
/**
* @var string the request parameter ($_GET or $_POST) that will be submitted during export. If not set this will
* be auto generated. This should be unique for each export menu widget (for multiple export menu widgets on
* same page).
*/
public $exportRequestParam;
/**
* @var array the output style configuration options. It must be the style configuration array as required by
* PHPExcel.
*/
public $styleOptions = [];
/**
* @var array an array of rows to prepend in front of the grid used to create things like a title. Each array
* should be set with the following settings:
* - value: string, the value of the merged row
* - styleOptions: array, array of configuration options to set the style. See $styleOptions on how to configure.
*/
public $contentBefore = [];
/**
* @var array an array of rows to append after the footer row. Each array
* should be set with the following settings:
* - value: string, the value of the merged row
* - styleOptions: array, array of configuration options to set the style. See $styleOptions on how to configure.
*/
public $contentAfter = [];
/**
* @var bool whether to auto-size the excel output column widths. Defaults to `true`.
*/
public $autoWidth = true;
/**
* @var string encoding for the downloaded file header. Defaults to 'utf-8'.
*/
public $encoding = 'utf-8';
/**
* @var string the exported output file name. Defaults to 'grid-export';
*/
public $filename;
/**
* @var string the folder to save the exported file. Defaults to '@webroot/tmp/'. This property will be parsed only
* if `stream` is false. If the specified folder does not exist, files will be saved to `@webroot`.
*/
public $folder = '@webroot/tmp';
/**
* @var string the web accessible path for the saved file location. This property will be parsed only if `stream`
* is false. Note the `afterSaveView` property that will render the displayed file link.
*/
public $linkPath = '/tmp';
/**
* @var bool whether to stream output to the browser.
*/
public $stream = true;
/**
* @var bool whether to stream after saving file to `$folder` and when `$stream` is `false`. This property will be
* validated only when `$stream` is `false`.
*/
public $streamAfterSave = false;
/**
* @var bool whether to delete file after saving file to `$folder` and when `$stream` is `false`. This property
* will be validated only when `$stream` is `false`. This property is useful only if `streamAfterSave` is
* `true`.
*/
public $deleteAfterSave = false;
/**
* @var string|bool the view file to show details of exported file link. This property will be validated only when
* `$stream` is `false` and `streamAfterSave` is `false`. You can set this to `false` to not display any file
* link details for view. This defaults to the `_view` PHP file in the `views` folder of the extension.
*/
public $afterSaveView = '_view';
/**
* @var int fetch models from the dataprovider using batches of this size. Set this to `0` (the default) to
* disable. If `$dataProvider` does not have a pagination object, this parameter is ignored. Setting this
* property helps reduce memory overflow issues by allowing parsing of models in batches, rather than fetching
* all models in one go.
*/
public $batchSize = 0;
/**
* @var array, the configuration of various messages that will be displayed at runtime:
* - allowPopups: string, the message to be shown to disable browser popups for download. Defaults to `Disable any
* popup blockers in your browser to ensure proper download.`.
* - confirmDownload: string, the message to be shown for confirming to proceed with the download. Defaults to `Ok
* to proceed?`.
* - downloadProgress: string, the message to be shown in a popup dialog when download request is executed.
* Defaults to `Generating file. Please wait...`.
* - downloadComplete: string, the message to be shown in a popup dialog when download request is completed.
* Defaults to `All done! Click anywhere here to close this window, once you have downloaded the file.`.
*/
public $messages = [];
/**
* @var Closure the callback function on initializing the PHP Excel library. The anonymous function should have the
* following signature:
* ```php
* function ($excel, $grid)
* ```
* where:
* - `$excel`: the PHPExcel object instance
* - `$grid`: the GridView object
*/
public $onInitExcel = null;
/**
* @var Closure the callback function on initializing the writer. The anonymous function should have the following
* signature:
* ```php
* function ($writer, $grid)
* ```
* where:
* - `$writer`: PHPExcel_Writer_Abstract, the PHPExcel_Writer_Abstract object instance
* - `$grid`: GridView, the current GridView object
*/
public $onInitWriter = null;
/**
* @var Closure the callback function to be executed on initializing the active sheet. The anonymous function
* should have the following signature:
* ```php
* function ($sheet, $grid)
* ```
* where:
* - `$sheet`: PHPExcel_Worksheet, the PHPExcel_Worksheet object instance
* - `$grid`: GridView, the current GridView object
*/
public $onInitSheet = null;
/**
* @var Closure the callback function to be executed on rendering the header cell output content. The anonymous
* function should have the following signature:
* ```php
* function ($cell, $content, $grid)
* ```
* where:
* - `$cell`: PHPExcel_Cell, is the current PHPExcel cell being rendered
* - `$content`: string, is the header cell content being rendered
* - `$grid`: GridView, the current GridView object
*/
public $onRenderHeaderCell = null;
/**
* @var Closure the callback function to be executed on rendering each body data cell content. The anonymous
* function should have the following signature:
* ```php
* function ($cell, $content, $model, $key, $index, $grid)
* ```
* where:
* - `$cell`: PHPExcel_Cell, the current PHPExcel cell being rendered
* - `$content`: string, the data cell content being rendered
* - `$model`: Model, the data model to be rendered
* - `$key`: mixed, the key associated with the data model
* - `$index`: int, the zero-based index of the data model among the model array returned by [[dataProvider]].
* - `$grid`: GridView, the current GridView object
*/
public $onRenderDataCell = null;
/**
* @var Closure the callback function to be executed on rendering the footer cell output content. The anonymous
* function should have the following signature:
* ```php
* function ($cell, $content, $grid)
* ```
* where:
* - `$sheet`: PHPExcel_Worksheet, the PHPExcel_Worksheet object instance
* - `$content`: string, the footer cell content being rendered
* - `$grid`: GridView, the current GridView object
*/
public $onRenderFooterCell = null;
/**
* @var Closure the callback function to be executed on rendering the sheet. The anonymous function should have the
* following signature:
* ```php
* function ($sheet, $grid)
* ```
* where:
* - `$sheet`: PHPExcel_Worksheet, the PHPExcel_Worksheet object instance
* - `$grid`: GridView, the current GridView object
*/
public $onRenderSheet = null;
/**
* @var array the PHPExcel document properties
*/
public $docProperties = [];
/**
* @var string the library used to render the PDF. Defaults to `'mPDF'`. Must be one of:
* - `PHPExcel_Settings::PDF_RENDERER_TCPDF` or `'tcPDF'`
* - `PHPExcel_Settings::PDF_RENDERER_DOMPDF` or `'DomPDF'`
* - `PHPExcel_Settings::PDF_RENDERER_MPDF` or `'mPDF'`
*/
public $pdfLibrary = PHPExcel_Settings::PDF_RENDERER_MPDF;
/**
* @var string the alias for the pdf library path to export to PDF
*/
public $pdfLibraryPath = '@vendor/mpdf/mpdf';
/**
* @var array the internalization configuration for this widget
*/
public $i18n = [];
/**
* @var bool enable dynagrid for column selection. If set to `true` the inbuilt export menu column selector
* functionality will be disabled and not rendered.
*/
public $dynagrid = false;
/**
* @var array dynagrid widget options
*/
public $dynagridOptions = ['options' => ['id' => 'dyangrid-export-menu']];
/**
* @var array the default style configuration
*/
public $groupedRowStyle = [
'font' => [
'bold' => false,
'color' => [
'argb' => '000000',
],
],
'fill' => [
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => [
'argb' => 'C9C9C9',
],
],
];
/**
* @var string translation message file category name for i18n
*/
protected $_msgCat = 'kvexport';
/**
* @var BaseDataProvider the modified data provider for usage with export.
*/
protected $_provider;
/**
* @var string the data output format type. Defaults to `ExportMenu::FORMAT_EXCEL_X`.
*/
protected $_exportType = self::FORMAT_EXCEL_X;
/**
* @var array the default export configuration
*/
protected $_defaultExportConfig = [];
/**
* @var PHPExcel object instance
*/
protected $_objPHPExcel;
/**
* @var PHPExcel_Writer_Abstract object instance
*/
protected $_objPHPExcelWriter;
/**
* @var PHPExcel_Worksheet object instance
*/
protected $_objPHPExcelSheet;
/**
* @var int the header beginning row
*/
protected $_headerBeginRow = 1;
/**
* @var int the table beginning row
*/
protected $_beginRow = 1;
/**
* @var int the current table end row
*/
protected $_endRow = 1;
/**
* @var int the current table end column
*/
protected $_endCol = 1;
/**
* @var bool whether the column selector is enabled
*/
protected $_columnSelectorEnabled = true;
/**
* @var array the visble columns for export
*/
protected $_visibleColumns;
/**
* @var array the default style configuration
*/
protected $_defaultStyleOptions = [
self::FORMAT_EXCEL => [
'font' => [
'bold' => true,
'color' => [
'argb' => 'FFFFFFFF',
],
],
'fill' => [
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => [
'argb' => '00000000',
],
],
],
self::FORMAT_EXCEL_X => [
'font' => [
'bold' => true,
'color' => [
'argb' => 'FFFFFFFF',
],
],
'fill' => [
'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
'startcolor' => [
'argb' => 'FFA0A0A0',
],
'endcolor' => [
'argb' => 'FFFFFFFF',
],
],
],
];
/**
* @var array columns to be grouped
*/
protected $_groupedColumn = [];
/**
*
* @var array grouped row values
*/
protected $_groupedRow = null;
/**
* @var bool flag to identify if download is triggered
*/
protected $_triggerDownload = false;
/**
* @var bool flag to identify if no streaming of file is desired
*/
protected $_doNotStream = false;
/**
* @inheritdoc
*/
public function init()
{
if (empty($this->options['id'])) {
$this->options['id'] = $this->getId();
}
if (empty($this->exportRequestParam)) {
$this->exportRequestParam = 'exportFull_' . $this->options['id'];
}
$this->_columnSelectorEnabled = $this->showColumnSelector && $this->asDropdown;
$this->_triggerDownload = !empty($_POST) &&
!empty($_POST[$this->exportRequestParam]) &&
$_POST[$this->exportRequestParam];
$this->_doNotStream = (!$this->stream && !$this->streamAfterSave);
if ($this->_doNotStream) {
$this->target = self::TARGET_SELF;
}
if ($this->_triggerDownload) {
if (!$this->_doNotStream) {
Yii::$app->controller->layout = false;
}
$this->_exportType = $_POST[self::PARAM_EXPORT_TYPE];
$this->_columnSelectorEnabled = $_POST[self::PARAM_COLSEL_FLAG];
$this->initSelectedColumns();
}
if ($this->dynagrid) {
$this->_columnSelectorEnabled = false;
$options = $this->dynagridOptions;
$options['columns'] = $this->columns;
$options['storage'] = 'db';
$options['gridOptions']['dataProvider'] = $this->dataProvider;
$dynagrid = new DynaGrid($options);
$this->columns = $dynagrid->getColumns();
}
parent::init();
}
/**
* @inheritdoc
*/
public function run()
{
$this->initI18N(__DIR__);
$this->initColumnSelector();
$this->setVisibleColumns();
$this->initExport();
if (!$this->_triggerDownload) {
$this->registerAssets();
echo $this->renderExportMenu();
return;
}
if ($this->timeout >= 0) {
set_time_limit($this->timeout);
}
if (!$this->_doNotStream) {
$this->clearOutputBuffers();
}
$config = ArrayHelper::getValue($this->exportConfig, $this->_exportType, []);
if ($this->_exportType === self::FORMAT_PDF) {
$path = Yii::getAlias($this->pdfLibraryPath);
if (!PHPExcel_Settings::setPdfRenderer($this->pdfLibrary, $path)) {
throw new InvalidConfigException("The pdf rendering library '{$this->pdfLibrary}' was not found or installed at path '{$path}'.");
}
}
if (empty($config['writer'])) {
throw new InvalidConfigException("The 'writer' setting for PHPExcel must be setup in 'exportConfig'.");
}
$this->initPHPExcel();
$this->initPHPExcelWriter($config['writer']);
$this->initPHPExcelSheet();
$this->generateBeforeContent();
$this->generateHeader();
$this->generateBody();
$row = $this->generateFooter();
$this->generateAfterContent($row);
$writer = $this->_objPHPExcelWriter;
$sheet = $this->_objPHPExcelSheet;
if ($this->autoWidth) {
foreach ($this->getVisibleColumns() as $n => $column) {
$sheet->getColumnDimension(self::columnName($n + 1))->setAutoSize(true);
}
}
$this->raiseEvent('onRenderSheet', [$sheet, $this]);
if (!$this->stream) {
$this->folder = trim(Yii::getAlias($this->folder));
if (!file_exists($this->folder)) {
$this->folder = Yii::getAlias('@webroot');
}
$file = self::slash($this->folder) . $this->filename . '.' . $config['extension'];
$writer->save($file);
if ($this->streamAfterSave) {
$this->clearOutputBuffers();
$this->setHttpHeaders();
readfile($file);
if ($this->deleteAfterSave) {
@unlink($file);
}
$this->destroyPHPExcel();
exit();
} else {
$this->registerAssets();
echo $this->renderExportMenu();
if ($this->_triggerDownload && $this->_doNotStream && $this->afterSaveView !== false) {
$config = ArrayHelper::getValue($this->exportConfig, $this->_exportType, []);
if (!empty($config)) {
$file = $this->filename . '.' . $config['extension'];
echo $this->render($this->afterSaveView, [
'file' => $file,
'icon' => ($this->fontAwesome ? 'fa fa-' : 'glyphicon glyphicon-') . $config['icon'],
'href' => Url::to([self::slash($this->linkPath, '/') . $file]),
]);
}
}
}
if ($this->deleteAfterSave) {
@unlink($file);
}
} else {
$this->clearOutputBuffers();
$this->setHttpHeaders();
$writer->save('php://output');
$this->destroyPHPExcel();
exit();
}
}
/**
* Initialize columns selected for export
*
* @return void
*/
protected function initSelectedColumns()
{
if (!$this->_columnSelectorEnabled) {
return;
}
$this->selectedColumns = array_keys($this->columnSelector);
if (!isset($_POST[self::PARAM_EXPORT_COLS]) or !strlen($_POST[self::PARAM_EXPORT_COLS])) {
return;
}
$this->selectedColumns = Json::decode($_POST[self::PARAM_EXPORT_COLS]);
}
/**
* Appends slash to path if it does not exist
*
* @param string $path
* @param string $s the path separator
*
* @return string
*/
public static function slash($path, $s = DIRECTORY_SEPARATOR)
{
$path = trim($path);
if (substr($path, -1) !== $s) {
$path .= $s;
}
return $path;
}
/**
* Clear output buffers
*
* @return void
*/
protected function clearOutputBuffers()
{
if ($this->clearBuffers) {
while (ob_get_level() > 0) {
ob_end_clean();
}
} else {
ob_end_clean();
}
}
/**
* Initialize column selector list
*
* @return void
*/
protected function initColumnSelector()
{
if (!$this->_columnSelectorEnabled) {
return;
}
$selector = [];
Html::addCssClass($this->columnSelectorOptions, 'btn btn-default dropdown-toggle');
$header = ArrayHelper::getValue($this->columnSelectorOptions, 'header', Yii::t('kvexport', 'Select Columns'));
$this->columnSelectorOptions['header'] = (empty($header) || $header === false) ? '' :
'<li class="dropdown-header">' . $header . '</li><li class="kv-divider"></li>';
$id = $this->options['id'] . '-cols';
Html::addCssClass($this->columnSelectorMenuOptions, 'dropdown-menu kv-checkbox-list');
$this->columnSelectorMenuOptions = array_replace_recursive([
'id' => $id . '-list',
'role' => 'menu',
'aria-labelledby' => $id,
], $this->columnSelectorMenuOptions);
$this->columnSelectorOptions = array_replace_recursive([
'id' => $id,
'icon' => '<i class="glyphicon glyphicon-list"></i>',
'title' => Yii::t('kvexport', 'Select columns to export'),
'type' => 'button',
'data-toggle' => 'dropdown',
'aria-haspopup' => 'true',
'aria-expanded' => 'false',
], $this->columnSelectorOptions);
foreach ($this->columns as $key => $column) {
$selector[$key] = $this->getColumnLabel($key, $column);
}
$this->columnSelector = array_replace($selector, $this->columnSelector);
if (!isset($this->selectedColumns)) {
$keys = array_keys($this->columnSelector);
$this->selectedColumns = array_combine($keys, $keys);
}
}
/**
* Fetches the column label
*
* @param int $key
* @param Column $column
*
* @return string
*/
protected function getColumnLabel($key, $column)
{
$label = Yii::t('kvexport', 'Column') . ' ' . ($key + 1);
if (!empty($column->label)) {
$label = $column->label;
} elseif (!empty($column->header)) {
$label = $column->header;
} elseif (!empty($column->attribute)) {
$label = $this->getAttributeLabel($column->attribute);
} elseif (!$column instanceof DataColumn) {
$class = explode("\\", $column::classname());
$label = Inflector::camel2words(end($class));
}
return trim(strip_tags(str_replace(['<br>', '<br/>'], ' ', $label)));
}
/**
* Generates the attribute label
*
* @param string $attribute
*
* @return string
*/
protected function getAttributeLabel($attribute)
{
/**
* @var Model $model
*/
$provider = $this->dataProvider;
if ($provider instanceof ActiveDataProvider && $provider->query instanceof ActiveQueryInterface) {
$model = new $provider->query->modelClass;
return $model->getAttributeLabel($attribute);
} else {
$models = $provider->getModels();
if (($model = reset($models)) instanceof Model) {
return $model->getAttributeLabel($attribute);
} else {
return Inflector::camel2words($attribute);
}
}
}
/**
* Initializes export settings
*
* @return void
*/
public function initExport()
{
$this->_provider = clone($this->dataProvider);
if ($this->batchSize && $this->_provider->pagination) {
$this->_provider->pagination = clone($this->dataProvider->pagination);
$this->_provider->pagination->pageSize = $this->batchSize;
} else {
$this->_provider->pagination = false;
}
if ($this->initProvider) {
$this->_provider->prepare(true);
}
$this->styleOptions = ArrayHelper::merge($this->_defaultStyleOptions, $this->styleOptions);
$this->filterModel = null;
$this->setDefaultExportConfig();
$this->exportConfig = ArrayHelper::merge($this->_defaultExportConfig, $this->exportConfig);
if (empty($this->filename)) {
$this->filename = Yii::t('kvexport', 'grid-export');
}
$target = $this->target == self::TARGET_POPUP ? 'kvExportFullDialog' : $this->target;
$id = ArrayHelper::getValue($this->exportFormOptions, 'id', $this->options['id'] . '-form');
Html::addCssClass($this->exportFormOptions, 'kv-export-full-form');
$this->exportFormOptions += [
'id' => $id,
'target' => $target,
];
}
/**
* Sets the default export configuration
*
* @return void
*/
protected function setDefaultExportConfig()
{
$isFa = $this->fontAwesome;
$this->_defaultExportConfig = [
self::FORMAT_HTML => [
'label' => Yii::t('kvexport', 'HTML'),
'icon' => $isFa ? 'file-text' : 'floppy-saved',
'iconOptions' => ['class' => 'text-info'],
'linkOptions' => [],
'options' => ['title' => Yii::t('kvexport', 'Hyper Text Markup Language')],
'alertMsg' => Yii::t('kvexport', 'The HTML export file will be generated for download.'),
'mime' => 'text/html',
'extension' => 'html',
'writer' => 'HTML',
],
self::FORMAT_CSV => [
'label' => Yii::t('kvexport', 'CSV'),
'icon' => $isFa ? 'file-code-o' : 'floppy-open',
'iconOptions' => ['class' => 'text-primary'],
'linkOptions' => [],
'options' => ['title' => Yii::t('kvexport', 'Comma Separated Values')],
'alertMsg' => Yii::t('kvexport', 'The CSV export file will be generated for download.'),
'mime' => 'application/csv',
'extension' => 'csv',
'writer' => 'CSV',
],
self::FORMAT_TEXT => [
'label' => Yii::t('kvexport', 'Text'),
'icon' => $isFa ? 'file-text-o' : 'floppy-save',
'iconOptions' => ['class' => 'text-muted'],
'linkOptions' => [],
'options' => ['title' => Yii::t('kvexport', 'Tab Delimited Text')],
'alertMsg' => Yii::t('kvexport', 'The TEXT export file will be generated for download.'),
'mime' => 'text/plain',
'extension' => 'txt',
'writer' => 'CSV',
],
self::FORMAT_PDF => [
'label' => Yii::t('kvexport', 'PDF'),
'icon' => $isFa ? 'file-pdf-o' : 'floppy-disk',
'iconOptions' => ['class' => 'text-danger'],
'linkOptions' => [],
'options' => ['title' => Yii::t('kvexport', 'Portable Document Format')],
'alertMsg' => Yii::t('kvexport', 'The PDF export file will be generated for download.'),
'mime' => 'application/pdf',
'extension' => 'pdf',
'writer' => 'PDF',
],
self::FORMAT_EXCEL => [
'label' => Yii::t('kvexport', 'Excel 95 +'),
'icon' => $isFa ? 'file-excel-o' : 'floppy-remove',
'iconOptions' => ['class' => 'text-success'],
'linkOptions' => [],
'options' => ['title' => Yii::t('kvexport', 'Microsoft Excel 95+ (xls)')],
'alertMsg' => Yii::t('kvexport', 'The EXCEL 95+ (xls) export file will be generated for download.'),
'mime' => 'application/vnd.ms-excel',
'extension' => 'xls',
'writer' => 'Excel5',
],
self::FORMAT_EXCEL_X => [
'label' => Yii::t('kvexport', 'Excel 2007+'),
'icon' => $isFa ? 'file-excel-o' : 'floppy-remove',
'iconOptions' => ['class' => 'text-success'],
'linkOptions' => [],
'options' => ['title' => Yii::t('kvexport', 'Microsoft Excel 2007+ (xlsx)')],
'alertMsg' => Yii::t('kvexport', 'The EXCEL 2007+ (xlsx) export file will be generated for download.'),