-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExportableGridview.php
309 lines (265 loc) · 8.79 KB
/
ExportableGridview.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
<?php
namespace eseperio\gridview;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Yii;
use yii\base\UserException;
use yii\grid\Column;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;
/**
* Class ExportableGridview
* @package eseperio\admintheme\widgets\grid
*/
class ExportableGridview extends \yii\grid\GridView
{
const DEFAULT_POINTER = 'A';
const WRITER_XLS = 'Xls';
const WRITER_XLSX = 'Xlsx';
const WRITER_ODS = 'Ods';
const WRITER_CSV = 'Csv';
const WRITER_HTML = 'Html';
const WRITER_TCPDF = 'Tcpdf';
const WRITER_DOMPDF = 'Dompdf';
const WRITER_MPDF = 'Mpdf';
/**
* @var string the layout that determines how different sections of the grid view should be organized.
* The following tokens will be replaced with the corresponding section contents:
*
* - `{summary}`: the summary section. See [[renderSummary()]].
* - `{errors}`: the filter model error summary. See [[renderErrors()]].
* - `{items}`: the list items. See [[renderItems()]].
* - `{sorter}`: the sorter. See [[renderSorter()]].
* - `{pager}`: the pager. See [[renderPager()]].
*/
public $layout = "{summary}\n{items}\n{export}\n{pager}";
/**
* @var string writer type (format type). If not set, it will be determined automatically.
* Supported values:
*
* - 'Xls'
* - 'Xlsx'
* - 'Ods'
* - 'Csv'
* - 'Html'
* - 'Tcpdf'
* - 'Dompdf'
* - 'Mpdf'
*
* @see IOFactory
*/
public $writerType;
/**
* @var string filename of the generated spreadsheet
*/
public $fileName = 'exported.xls';
/**
* @var array Additional options for sending the file
*/
public $exportFileOptions = [];
/**
* @var bool whether the gridview can be exported.
*/
public $exportable = true;
/**
* @var array options to use when rendering export link.
*/
public $exportLinkOptions = [
'class' => 'btn btn-default',
'target' => '_blank',
];
/**
* @var array columns to be exported. It empty gridview columns will be used.
*/
public $exportColumns = [];
/**
* @var string spreadsheet column index
*/
private $columnIndex = self::DEFAULT_POINTER;
/**
* @var int spreadsheet row index
*/
private $rowIndex = 1;
/**
* @var array multidimensional containing rows and columns.
* First level: Rows
* Second level: Cols
*/
private $data = [];
/**
* @var Spreadsheet generated
*/
private $_document;
/**
* Initialize the gridview;
* @throws \yii\base\InvalidConfigException
*/
public function init()
{
if (!isset($this->id)) {
$this->options['id'] = $this->getId();
}
if ($this->downloadRequested() && !empty($this->exportColumns)) {
$this->emptyCell = "";
$this->columns = $this->exportColumns;
}
if ($this->downloadRequested())
$this->dataProvider->pagination = false;
parent::init();
}
/**
* @return bool whether a download is allowed and requested.
*/
public function downloadRequested()
{
$request = Yii::$app->getRequest();
$grid = $request->get('export-grid');
$container = $request->get('export-container');
return $this->exportable && $grid && $container === $this->id;
}
/**
* @return string|void
* @throws UserException
* @throws \Exception
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws \yii\base\ExitException
*/
public function run()
{
if ($this->downloadRequested()) {
if ($this->dataProvider->getCount() <= 0 || empty($this->columns))
throw new UserException('Nothing to export');
$response = Yii::$app->getResponse();
$response->setStatusCode(200);
$this->prepareExportArray();
$document = $this->getDocument();
$document->getActiveSheet()->fromArray($this->data);
$this->prepareSend($this->exportFileOptions);
Yii::$app->response->send();
Yii::$app->end();
}
parent::run();
}
protected function prepareExportArray()
{
$this->renderExportHeaders();
$this->renderExportBody();
$this->renderExportFooter();
$this->cleanExportData();
}
public function renderExportHeaders()
{
$cells = [];
foreach ($this->columns as $column) {
/* @var $column Column */
$cells[$this->columnIndex++] = $column->renderHeaderCell();
}
$this->data[$this->rowIndex++] = $cells;
$this->columnIndex = self::DEFAULT_POINTER;
}
public function renderExportBody()
{
$models = array_values($this->dataProvider->getModels());
$keys = $this->dataProvider->getKeys();
$rows = [];
foreach ($models as $index => $model) {
$key = $keys[$index];
$rows[] = $this->renderExportRow($model, $key, $index);
}
}
public function renderExportRow($model, $key, $index)
{
$cells = [];
/* @var $column Column */
foreach ($this->columns as $column) {
$cells[$this->columnIndex++] = $column->renderDataCell($model, $key, $index);
}
$this->columnIndex = self::DEFAULT_POINTER;
$this->data[$this->rowIndex++] = $cells;
}
public function renderExportFooter()
{
$cells = [];
foreach ($this->columns as $column) {
/* @var $column Column */
$cells[$this->columnIndex++] = $column->renderFooterCell();
}
$this->data[$this->rowIndex++] = $cells;
$this->columnIndex = self::DEFAULT_POINTER;
}
/**
* Removes all tags and encodes each cell to export.
*/
private function cleanExportData()
{
foreach ($this->data as $rowKey => $row) {
foreach ($row as $colKey => $column) {
$cleanValue = Html::encode(strip_tags(trim(str_replace(' ', "", $column))));
$this->data[$rowKey][$colKey] = $cleanValue;
}
}
}
/**
* @return \PhpOffice\PhpSpreadsheet\Spreadsheet spreadsheet document representation instance.
*/
public function getDocument()
{
if (!is_object($this->_document)) {
$this->_document = new Spreadsheet();
}
return $this->_document;
}
/**
* Sends the rendered content as a file to the browser.
*
* Note that this method only prepares the response for file sending. The file is not sent
* until [[\yii\web\Response::send()]] is called explicitly or implicitly.
* The latter is done after you return from a controller action.
*
* @param array $options additional options for sending the file. The following options are supported:
*
* - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'.
* - `inline`: bool, whether the browser should open the file within the browser window. Defaults to false,
* meaning a download dialog will pop up.
*
* @return \yii\web\Response the response object.
*/
public function prepareSend($options = [])
{
$writerType = $this->writerType;
if ($writerType === null) {
$fileExtension = strtolower(pathinfo($this->fileName, PATHINFO_EXTENSION));
$writerType = ucfirst($fileExtension);
}
$tmpResource = tmpfile();
if ($tmpResource === false)
throw new \Exception('Temporary file could not be created');
$tmpResourceMetaData = stream_get_meta_data($tmpResource);
$tmpFileName = $tmpResourceMetaData['uri'];
$writer = IOFactory::createWriter($this->getDocument(), $writerType);
$writer->save($tmpFileName);
unset($writer);
return Yii::$app->getResponse()->sendStreamAsFile($tmpResource, $this->fileName, $options);
}
/**
* @inheritdoc
*/
public function renderSection($name)
{
if ($name === '{export}' && $this->exportable)
return $this->renderExportLink();
return parent::renderSection($name);
}
/**
* @return string the export link tag.
*/
public function renderExportLink()
{
$label = ArrayHelper::remove($this->exportLinkOptions, 'label', 'Export');
$encode = ArrayHelper::remove($this->exportLinkOptions, 'encode', true);
$url = Url::current(['export-grid' => 1, 'export-container' => $this->getId()]);
$this->exportLinkOptions['data-pjax'] = 0;
return Html::a($encode ? Html::encode($label) : $label, $url, $this->exportLinkOptions);
}
}