Passed
Push — master ( a5720c...1236ba )
by WILMER
02:23
created

Export::exportExcel()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 30
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 25
nc 6
nop 0
dl 0
loc 30
rs 9.2088
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * (c) CJT TERABYTE INC
5
 * For the full copyright and license information, please view the LICENSE.md
6
 * file that was distributed with this source code.
7
 *
8
 *        @link: https://github.com/cjtterabytesoft/alert
9
 *      @author: Wilmer Arámbula <[email protected]>
10
 *   @copyright: (c) CJT TERABYTE INC
11
 *     @widgets: [Export]
12
 *       @since: 1.0
13
 *         @yii: 3.0
14
 **/
15
16
namespace cjtterabytesoft\widgets;
17
18
use Dompdf\Dompdf;
19
use Dompdf\Options;
20
use PhpOffice\PhpSpreadsheet\Spreadsheet;
21
use PhpOffice\PhpSpreadsheet\Style\Alignment;
22
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
23
use PhpOffice\PhpWord\IOFactory;
24
use PhpOffice\PhpWord\PhpWord;
25
use yii\base\InvalidConfigException;
26
use yii\base\Widget;
27
28
/**
29
 * Export File diferents format Csv, Excel, Html, Pdf, Word.
30
 */
31
class Export extends Widget
32
{
33
	/**
34
	 * @var string Charset export csv.
35
	 */
36
	public $_csvCharset = 'UTF-8';
37
38
	/**
39
	 * @var \yii\data\DataProviderInterface the data provider for the view. This property is required.
40
	 */
41
	public $_dataProvider;
42
43
	/**
44
	 * @var \app\model\searchModel.
45
	 */
46
	public $_searchModel;
47
48
	/**
49
	 * @var string tableName.
50
	 */
51
	public $_tableName= '';
52
53
	/**
54
	 * @var string Title Export.
55
	 */
56
	public $_title = '';
57
58
	/**
59
	 * Initializes the view.
60
	 */
61
	public function init()
62
	{
63
		parent::init();
64
65
		if (empty($this->_dataProvider)) {
66
			throw new InvalidConfigException('The "dataProvider" property must be set.');
67
		}
68
69
		if (empty($this->_searchModel)) {
70
			throw new InvalidConfigException('The "dataProvider" property must be set.');
71
		}
72
73
		$this->_tableName = $this->_searchModel->tableName();
74
75
		if (empty($this->_title)) {
76
			$this->_title = $this->_tableName;
77
		}
78
	}
79
80
	/**
81
	 * @return file Csv Export.
82
	 */
83
	public function exportCsv()
84
	{
85
		$csvCharset = $this->_csvCharset;
86
		$fields = $this->getFieldsKeys($this->_searchModel->exportFields());
87
		header('Pragma: public');
88
		header('Expires: 0');
89
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
90
		header('Content-Description: File Transfer');
91
		header('Content-Type: text/csv');
92
		$filename = $this->_tableName . '.csv';
93
		header('Content-Disposition: attachment;filename=' . $filename);
94
		header('Content-Transfer-Encoding: binary');
95
		$fp = fopen('php://output', 'w');
96
		fwrite($fp, $bom = (chr(0xEF) . chr(0xBB) . chr(0xBF)));
97
		if ($fp) {
0 ignored issues
show
introduced by
$fp is of type resource|false, thus it always evaluated to false.
Loading history...
98
			$items = [];
99
			$i = 0;
100
			foreach ($fields as $one) {
101
				$items[$i] = $one;
102
				$i++;
103
			}
104
			fwrite($fp, implode($items, ',') . "\n");
105
			$items = [];
106
			$i = 0;
107
			foreach ($this->_dataProvider->getModels() as $model) {
108
				foreach ($this->_searchModel->exportFields() as $one) {
109
					$item = str_replace('"', '\"', is_string($one) ? $model[$one] : $one($model));
110
					$items[$i] = ($item) ? '"' . $item . '"' : $item;
111
					$i++;
112
				}
113
				fwrite($fp, implode($items, ',') . "\n");
114
				$items = [];
115
				$i = 0;
116
			}
117
		}
118
		fclose($fp);
119
	}
120
121
	/**
122
	 * @return file Excel Export.
123
	 */
124
	public function exportExcel()
125
	{
126
		$fields = $this->getFieldsKeys($this->_searchModel->exportFields());
127
		$objPHPExcel = new Spreadsheet();
128
		$objPHPExcel->setActiveSheetIndex(0);
129
		$objPHPExcel->getActiveSheet()->setTitle($this->_title);
130
		$letter = 65;
131
		foreach ($fields as $one) {
132
			$objPHPExcel->getActiveSheet()->getColumnDimension(chr($letter))->setAutoSize(true);
133
			$objPHPExcel->getActiveSheet()->setCellValue(chr($letter) . '1', $this->_searchModel->getAttributeLabel($one));
134
			$objPHPExcel->getActiveSheet()->getStyle(chr($letter) . '1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
135
			$letter++;
136
		}
137
		$row = 2;
138
		$letter = 65;
139
		foreach ($this->_dataProvider->getModels() as $model) {
140
			foreach ($this->_searchModel->exportFields() as $one) {
141
				$objPHPExcel->getActiveSheet()->setCellValue(chr($letter) . $row, (is_string($one)) ? $model[$one] : $one($model));
142
				$objPHPExcel->getActiveSheet()->getStyle(chr($letter) . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
143
				$letter++;
144
			}
145
			$letter = 65;
146
			$row++;
147
		}
148
		header('Content-Type: application/vnd.ms-excel');
149
		$filename = $this->_tableName . '.xlsx';
150
		header('Content-Disposition: attachment;filename=' . $filename);
151
		header('Cache-Control: max-age=0');
152
		$objWriter = new Xlsx($objPHPExcel);
153
		$objWriter->save('php://output');
154
	}
155
156
	/**
157
	 * @return file Htlm Export.
158
	 */
159
	public function exportHtml()
160
	{
161
		$fields = $this->getFieldsKeys($this->_searchModel->exportFields());
162
		$phpWord = new PhpWord();
163
		$section = $phpWord->addSection();
164
		$section->addTitle($this->_title);
165
		$table = $section->addTable(['name' => 'Tahoma', 'size' => 10, 'align' => 'center',]);
166
		$table->addRow(300, ['exactHeight' => true]);
167
		foreach ($fields as $one) {
168
			$table->addCell(1500, [
169
				'bgColor' => 'eeeeee',
170
				'valign' => 'center',
171
				'borderTopSize' => 5,
172
				'borderRightSize' => 5,
173
				'borderBottomSize' => 5,
174
				'borderLeftSize' => 5,
175
			])->addText($this->_searchModel->getAttributeLabel($one), ['bold' => true, 'size' => 10], ['align' => 'center']);
176
		}
177
		foreach ($this->_dataProvider->getModels() as $model) {
178
			$table->addRow(300, ['exactHeight' => true]);
179
			foreach ($this->_searchModel->exportFields() as $one) {
180
				$table->addCell(1500, [
181
					'valign' => 'center',
182
					'borderTopSize' => 1,
183
					'borderRightSize' => 1,
184
					'borderBottomSize' => 1,
185
					'borderLeftSize' => 1,
186
				])->addText('<p style="margin-left: 10px;">' . (is_string($one)) ? $model[$one] : $one($model) . '</p>', ['bold' => false, 'size' => 10], ['align' => 'right']);
187
			}
188
		}
189
		header('Content-Type: application/html');
190
		$filename = $this->_tableName . '.html';
191
		header('Content-Disposition: attachment;filename=' . $filename . ' ');
192
		header('Cache-Control: max-age=0');
193
		$objWriter = IOFactory::createWriter($phpWord, 'HTML');
194
		$objWriter->save('php://output');
195
	}
196
197
	/**
198
	 * @return file Pdf Export.
199
	 */
200
	public function exportPdf()
201
	{
202
		$fields = $this->getFieldsKeys($this->_searchModel->exportFields());
203
		$options = new Options();
204
		$options->set('defaultFont', 'times');
205
		$dompdf = new Dompdf($options);
206
		$html = '<html><body>';
207
		$html .= '<h1>' . '<center>' . $this->_title . '</center>' . '</h1>';
208
		$html .= '<table width="100%" cellspacing="0" cellpadding="0">';
209
		$html .= '<tr style="background-color: #ececec;">';
210
		foreach ($fields as $one) {
211
			$html .= '<td style="border: 2px solid #cccccc; text-align: center; font-weight: 500;">' . $this->_searchModel->getAttributeLabel($one) . '</td>';
212
		}
213
		$html .= '</tr>';
214
		foreach ($this->_dataProvider->getModels() as $model) {
215
			$html .= '<tr>';
216
			foreach ($this->_searchModel->exportFields() as $one) {
217
				switch (true) {
218
					case is_string($one):
219
						$html .= '<td style="border: 1px solid #cccccc; text-align: left; font-weight: 300; padding-left: 10px;">' . $model[$one] . '</td>';
220
						break;
221
					default:
222
						$html .= '<td style="border: 1px solid #cccccc; text-align: left; font-weight: 300; padding-left: 10px;">' . $one($model) . '</td>';
223
						break;
224
				}
225
			}
226
			$html .= '</tr>';
227
		}
228
		$html .= '</table>';
229
		$html .= '</body></html>';
230
		$dompdf->loadHtml($html);
231
		$dompdf->setPaper('letter', 'landscape');
232
		$dompdf->render();
233
		$dompdf->stream($this->_tableName . '_' . time());
234
	}
235
236
	/**
237
	 * @return file Word Export.
238
	 */
239
	public function exportWord()
240
	{
241
		$fields = $this->getFieldsKeys($this->_searchModel->exportFields());
242
		$phpWord = new PhpWord();
243
		$phpWord->getCompatibility()->setOoxmlVersion(15);
244
		$section = $phpWord->addSection();
245
		$sectionStyle = $section->getSettings();
246
		$sectionStyle->setLandscape();
247
		$sectionStyle->setBorderTopColor('C0C0C0');
248
		$sectionStyle->setMarginTop(300);
249
		$sectionStyle->setMarginRight(300);
250
		$sectionStyle->setMarginBottom(300);
251
		$sectionStyle->setMarginLeft(300);
252
		$phpWord->addTitleStyle(1, ['name' => 'HelveticaNeueLT Std Med', 'size' => 16], ['align' => 'center']); //h
253
		$section->addTitle($this->_title);
254
		$table = $section->addTable(
255
			[
256
				'name' => 'Tahoma',
257
				'align' => 'center',
258
				'cellMarginTop' => 30,
259
				'cellMarginRight' => 30,
260
				'cellMarginBottom' => 30,
261
				'cellMarginLeft' => 30,
262
			]
263
		);
264
		$table->addRow(300, ['exactHeight' => true]);
265
		foreach ($fields as $one) {
266
			$table->addCell(1500, [
267
				'bgColor' => 'eeeeee',
268
				'valign' => 'center',
269
				'borderTopSize' => 5,
270
				'borderRightSize' => 5,
271
				'borderBottomSize' => 5,
272
				'borderLeftSize' => 5,
273
			])->addText($this->_searchModel->getAttributeLabel($one), ['bold' => true, 'size' => 10], ['align' => 'center']);
274
		}
275
		foreach ($this->_dataProvider->getModels() as $model) {
276
			$table->addRow(300, ['exactHeight' => true]);
277
			foreach ($this->_searchModel->exportFields() as $one) {
278
				$table->addCell(1500, [
279
					'valign' => 'center',
280
					'borderTopSize' => 1,
281
					'borderRightSize' => 1,
282
					'borderBottomSize' => 1,
283
					'borderLeftSize' => 1,
284
				])->addText(is_string($one) ? $model[$one] : $one($model), ['bold' => false, 'size' => 10], ['align' => 'left']);
285
			}
286
		}
287
		header('Content-Type: application/vnd.ms-word');
288
		$filename = $this->_tableName . '.docx';
289
		header('Content-Disposition: attachment;filename=' . $filename . ' ');
290
		header('Cache-Control: max-age=0');
291
		$objWriter = IOFactory::createWriter($phpWord, 'Word2007');
292
		$objWriter->save('php://output');
293
	}
294
295
	/**
296
	 * @return array Fields List.
297
	 */
298
	private function getFieldsKeys($fieldsSended)
299
	{
300
		$fields = [];
301
		$i = 0;
302
303
		foreach ($fieldsSended as $key => $value) {
304
			switch (true) {
305
				case is_int($key):
306
					$fields[$i] = $value;
307
					break;
308
				default:
309
					$fields[$i] = $key;
310
					break;
311
			}
312
			$i++;
313
		}
314
315
		return $fields;
316
	}
317
}
318