ILIAS  trunk Revision v12.0_alpha-1227-g7ff6d300864
class.ilExcel.php
Go to the documentation of this file.
1<?php
2
19use PhpOffice\PhpSpreadsheet\Spreadsheet;
20use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
21use PhpOffice\PhpSpreadsheet\IOFactory;
22use PhpOffice\PhpSpreadsheet\Shared\Date;
23use PhpOffice\PhpSpreadsheet\Cell\Cell;
24use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
25use PhpOffice\PhpSpreadsheet\Style\Fill;
26use PhpOffice\PhpSpreadsheet\Style\Border;
27use PhpOffice\PhpSpreadsheet\Cell\DataType;
29
30/*
31 * Wrapper for Microsoft Excel Import/Export (based on PHPSpreadsheet, formerPHPExcel which is deprecated)
32 * @author Jörg Lützenkirchen <luetzenkirchen@leifos.com>
33 */
35{
36 public const FORMAT_XML = 'Xlsx';
37 public const FORMAT_BIFF = 'Xls';
38 protected string $format;
39
40 private array $noncharacters = [
41 '\x{FFFE}-\x{FFFF}',
42 '\x{1FFFE}-\x{1FFFF}',
43 '\x{2FFFE}-\x{2FFFF}',
44 '\x{3FFFE}-\x{3FFFF}',
45 '\x{4FFFE}-\x{4FFFF}',
46 '\x{5FFFE}-\x{5FFFF}',
47 '\x{6FFFE}-\x{6FFFF}',
48 '\x{7FFFE}-\x{7FFFF}',
49 '\x{8FFFE}-\x{8FFFF}',
50 '\x{9FFFE}-\x{9FFFF}',
51 '\x{AFFFE}-\x{AFFFF}',
52 '\x{BFFFE}-\x{BFFFF}',
53 '\x{CFFFE}-\x{CFFFF}',
54 '\x{DFFFE}-\x{DFFFF}',
55 '\x{EFFFE}-\x{EFFFF}',
56 '\x{FFFFE}-\x{FFFFF}',
57 '\x{10FFFE}-\x{10FFFF}',
58 '\x{FDD0}-\x{FDEF}'
59 ];
60
61 protected ilLanguage $lng;
62 protected Spreadsheet $workbook;
63 protected string $type;
64
68 public function __construct()
69 {
70 global $DIC;
71
72 $this->lng = $DIC->language();
73 $this->setFormat(self::FORMAT_XML);
74 $this->workbook = new Spreadsheet();
75 $this->workbook->removeSheetByIndex(0);
76 }
77
78 //
79 // loading files
80 //
81
85 public function loadFromFile(string $filename): void
86 {
87 $this->workbook = IOFactory::load($filename);
88 }
89
90 //
91 // type/format
92 //
93
97 public function getValidFormats(): array
98 {
100 }
101
105 public function setFormat(string $a_format): void
106 {
107 if (in_array($a_format, $this->getValidFormats())) {
108 $this->format = $a_format;
109 }
110 }
111
112
113 //
114 // sheets
115 //
116
122 public function addSheet(
123 string $a_name,
124 bool $a_activate = true
125 ): int {
126 #20749
127 // see Worksheet::$_invalidCharacters;
128 $invalid = ['*', ':', '/', '\\', '?', '[', ']', '\'-', '\''];
129
130 $a_name = str_replace($invalid, '', $a_name);
131
132 // #19056 - phpExcel only allows 31 chars
133 // see https://github.com/PHPOffice/PHPExcel/issues/79
134 $a_name = ilStr::shortenTextExtended($a_name, 31);
135
136 $sheet = new Worksheet($this->workbook, $a_name);
137 $this->workbook->addSheet($sheet);
138 $new_index = $this->workbook->getSheetCount() - 1;
139
140 if ($a_activate) {
141 $this->setActiveSheet($new_index);
142 }
143
144 return $new_index;
145 }
146
150 public function setActiveSheet(int $a_index): void
151 {
152 $this->workbook->setActiveSheetIndex($a_index);
153 }
154
155
159 public function getSheetCount(): int
160 {
161 return $this->workbook->getSheetCount();
162 }
163
164
168 public function getSheetTitle(): string
169 {
170 return $this->workbook->getActiveSheet()->getTitle();
171 }
172
173
174 //
175 // cells
176 //
177
184 protected function prepareValue($value)
185 {
186 if (is_bool($value)) {
187 return $this->prepareBooleanValue($value);
188 }
189
190 if ($value instanceof ilDateTime) {
191 return $this->prepareDateValue($value);
192 }
193
194 if (is_string($value)) {
195 return $this->prepareString($value);
196 }
197
198 return $value;
199 }
200
205 protected function prepareDateValue(ilDateTime $a_value)
206 {
207 switch (true) {
208 case $a_value instanceof ilDate:
209 $a_value = Date::stringToExcel($a_value->get(IL_CAL_DATE));
210 break;
211
212 default:
213 $a_value = Date::stringToExcel($a_value->get(IL_CAL_DATETIME));
214 break;
215 }
216
217 return $a_value;
218 }
219
220 protected function prepareBooleanValue(bool $a_value): string
221 {
223
224 return $a_value ? $lng->txt('yes') : $lng->txt('no');
225 }
226
227 protected function prepareString(
228 string $value,
229 ): string {
230 if (!mb_check_encoding($value, 'UTF-8')) {
231 throw new InvalidArgumentException('Invalid UTF-8 passed.');
232 }
233
234 return $this->cleanupNonCharachters(strip_tags($value));
235 }
236
243 protected function setDateFormat(Cell $a_cell, $a_value): void
244 {
245 if ($a_value instanceof ilDate) {
246 $a_cell->getStyle()->getNumberFormat()->setFormatCode('dd.mm.yyyy');
247 } elseif ($a_value instanceof ilDateTime) {
248 $a_cell->getStyle()->getNumberFormat()->setFormatCode('dd.mm.yyyy hh:mm:ss');
249 }
250 }
251
257 public function setCellByCoordinates($a_coords, $a_value): void
258 {
259 if ($a_value instanceof ilDateTime) {
260 $wb = $this->workbook->getActiveSheet()->setCellValue(
261 $a_coords,
262 $this->prepareValue($a_value)
263 );
264 $cell = $wb->getCell($a_coords);
265 $this->setDateFormat($cell, $a_value);
266 } elseif (is_numeric($a_value)) {
267 $this->workbook->getActiveSheet()->setCellValueExplicit(
268 $a_coords,
269 $this->prepareValue($a_value),
270 DataType::TYPE_NUMERIC
271 );
272 } else {
273 $this->workbook->getActiveSheet()->setCellValueExplicit(
274 $a_coords,
275 $this->prepareValue($a_value),
276 DataType::TYPE_STRING
277 );
278 }
279 }
280
288 public function setCell(
289 int $a_row,
290 int $col,
291 $value,
292 ?string $datatype = null
293 ): void {
294 $coordinate = $this->getCoordByColumnAndRow($col, $a_row);
295
296 if ($datatype === DataType::TYPE_STRING) {
297 $this->workbook->getActiveSheet()->setCellValueExplicit(
298 $coordinate,
299 $this->prepareString($value),
300 $datatype
301 );
302 } elseif ($datatype !== null) {
303 $this->workbook->getActiveSheet()->setCellValueExplicit(
304 $coordinate,
305 $this->prepareValue($value),
306 $datatype
307 );
308 } elseif ($value instanceof ilDateTime) {
309 $wb = $this->workbook->getActiveSheet()->setCellValue(
310 $coordinate,
311 $this->prepareValue($value)
312 );
313 $this->setDateFormat($wb->getCell($coordinate), $value);
314 } elseif (is_numeric($value)) {
315 $this->workbook->getActiveSheet()->setCellValueExplicit(
316 $coordinate,
317 $this->prepareValue($value),
318 DataType::TYPE_NUMERIC
319 );
320 } else {
321 $this->workbook->getActiveSheet()->setCellValueExplicit(
322 $coordinate,
323 $this->prepareValue($value),
324 DataType::TYPE_STRING
325 );
326 }
327 }
328
336 public function setCellArray(
337 array $a_values,
338 string $a_top_left = 'A1',
339 $a_null_value = null
340 ): void {
341 foreach ($a_values as $row_idx => $cols) {
342 if (is_array($cols)) {
343 foreach ($cols as $col_idx => $col_value) {
344 $a_values[$row_idx][$col_idx] = $this->prepareValue($col_value);
345 }
346 } else {
347 $a_values[$row_idx] = $this->prepareValue($cols);
348 }
349 }
350
351 $this->workbook->getActiveSheet()->fromArray($a_values, $a_null_value, $a_top_left);
352 }
353
354
359 public function getCell(
360 int $a_row,
361 int $a_col
362 ) {
363 $coordinate = $this->getCoordByColumnAndRow($a_col, $a_row);
364 return $this->workbook->getActiveSheet()->getCell($coordinate)->getValue();
365 }
366
370 public function getSheetAsArray(): array
371 {
372 return $this->workbook->getActiveSheet()->toArray();
373 }
374
378 public function getColumnCount(): int
379 {
380 return Coordinate::columnIndexFromString($this->workbook->getActiveSheet()->getHighestDataColumn());
381 }
382
386 public function getColumnCoord(int $a_col): string
387 {
388 $col = $this->columnIndexAdjustment($a_col);
389 return Coordinate::stringFromColumnIndex($col);
390 }
391
395 protected function setGlobalAutoSize(): void
396 {
397 // this may change the active sheet
398 foreach ($this->workbook->getWorksheetIterator() as $worksheet) {
399 $this->workbook->setActiveSheetIndex($this->workbook->getIndex($worksheet));
400 $sheet = $this->workbook->getActiveSheet();
401 $cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
402 $cellIterator->setIterateOnlyExistingCells(true);
403 foreach ($cellIterator as $cell) {
404 $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
405 }
406 }
407 }
408
409 //
410 // deliver/save
411 //
412
416 protected function prepareStorage(string $a_file_name): string
417 {
418 $this->setGlobalAutoSize();
419 $this->workbook->setActiveSheetIndex(0);
420
421 switch ($this->format) {
422 case self::FORMAT_BIFF:
423 if (stripos($a_file_name, '.xls') === false) {
424 $a_file_name .= '.xls';
425 }
426 break;
427
428 case self::FORMAT_XML:
429 if (stripos($a_file_name, '.xlsx') === false) {
430 $a_file_name .= '.xlsx';
431 }
432 break;
433 }
434
435 return $a_file_name;
436 }
437
442 public function sendToClient(string $a_file_name): void
443 {
444 $a_file_name = $this->prepareStorage($a_file_name);
445 switch ($this->format) {
446 case self::FORMAT_BIFF:
447 $a_mime_type = MimeType::APPLICATION__VND_MS_EXCEL;
448 break;
449
450 case self::FORMAT_XML:
451 $a_mime_type = MimeType::APPLICATION__VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET;
452 break;
453 default:
454 $a_mime_type = MimeType::APPLICATION__OCTET_STREAM;
455 break;
456 }
457 $tmp_name = ilFileUtils::ilTempnam();
458
459 $writer = IOFactory::createWriter($this->workbook, $this->format);
460 $writer->save($tmp_name);
461
462 ilFileDelivery::deliverFileAttached($tmp_name, $a_file_name, $a_mime_type, true);
463 }
464
470 public function writeToFile(string $a_file): void
471 {
472 $a_file = $this->prepareStorage($a_file);
473
474 $writer = IOFactory::createWriter($this->workbook, $this->format);
475 $writer->save($a_file);
476 }
477
481 public function writeToTmpFile(): string
482 {
483 $writer = IOFactory::createWriter($this->workbook, $this->format);
485 $writer->save($filename);
486
487 return $filename;
488 }
489
493 public function setBold(string $a_coords): void
494 {
495 $this->workbook->getActiveSheet()->getStyle($a_coords)->getFont()->setBold(true);
496 }
497
501 public function setColors(
502 string $a_coords,
503 string $a_background,
504 ?string $a_font = null
505 ): void {
506 $opts = [
507 'fill' => [
508 'fillType' => Fill::FILL_SOLID,
509 'color' => ['rgb' => $a_background]
510 ]
511 ];
512
513 if ($a_font) {
514 $opts['font'] = [
515 'color' => ['rgb' => $a_font]
516 ];
517 }
518
519 $this->workbook->getActiveSheet()->getStyle($a_coords)->applyFromArray($opts);
520 }
521
525 public function setBorders(
526 string $a_coords,
527 bool $a_top,
528 bool $a_right = false,
529 bool $a_bottom = false,
530 bool $a_left = false
531 ): void {
532 $style = $this->workbook->getActiveSheet()->getStyle($a_coords);
533
534 // :TODO: border styles?
535 if ($a_top) {
536 $style->getBorders()->getTop()->setBorderStyle(Border::BORDER_THIN);
537 }
538 if ($a_right) {
539 $style->getBorders()->getRight()->setBorderStyle(Border::BORDER_THIN);
540 }
541 if ($a_bottom) {
542 $style->getBorders()->getBottom()->setBorderStyle(Border::BORDER_THIN);
543 }
544 if ($a_left) {
545 $style->getBorders()->getLeft()->setBorderStyle(Border::BORDER_THIN);
546 }
547 }
548
552 public function getCoordByColumnAndRow(
553 int $pColumn = 1,
554 int $pRow = 1
555 ): string {
556 $col = $this->columnIndexAdjustment($pColumn);
557 $columnLetter = Coordinate::stringFromColumnIndex($col);
558
559 return $columnLetter . $pRow;
560 }
561
565 public function addLink(
566 int $a_row,
567 int $a_column,
568 string $a_path
569 ): void {
570 $coordinate = $this->getCoordByColumnAndRow($a_column, $a_row);
571 $this->workbook->getActiveSheet()->getCell($coordinate)->getHyperlink()->setUrl($a_path);
572 }
573
578 public function columnIndexAdjustment(int $column): int
579 {
580 return ++$column;
581 }
582
587 public function mergeCells(string $coordinatesRange): void
588 {
589 $this->workbook->getActiveSheet()->mergeCells($coordinatesRange);
590 }
591
592 private function cleanupNonCharachters(string $string): string
593 {
594 return mb_ereg_replace('[' . implode('', $this->noncharacters) . ']', '', $string);
595 }
596}
$filename
Definition: buildRTE.php:78
Mime type determination.
Definition: MimeType.php:30
const IL_CAL_DATE
const IL_CAL_DATETIME
@classDescription Date and time handling
get(int $a_format, string $a_format_str='', string $a_tz='')
get formatted date
Class for single dates.
prepareValue($value)
Prepare value for cell.
Spreadsheet $workbook
setBold(string $a_coords)
Set cell(s) to bold.
getCell(int $a_row, int $a_col)
Returns the value of a cell.
prepareStorage(string $a_file_name)
Prepare workbook for storage/delivery.
array $noncharacters
getSheetAsArray()
Returns the active sheet as an array.
getSheetCount()
Returns number of sheets.
getColumnCoord(int $a_col)
Get column "name" from number.
addSheet(string $a_name, bool $a_activate=true)
Add sheet.
loadFromFile(string $filename)
Loads a spreadsheet from file.
setGlobalAutoSize()
Set all existing columns on all sheets to autosize.
setBorders(string $a_coords, bool $a_top, bool $a_right=false, bool $a_bottom=false, bool $a_left=false)
Toggle cell(s) borders.
getCoordByColumnAndRow(int $pColumn=1, int $pRow=1)
Get cell coordinate (e.g.
writeToFile(string $a_file)
Save workbook to file.
columnIndexAdjustment(int $column)
Adjustment needed because of migration PHPExcel to PhpSpreadsheet.
sendToClient(string $a_file_name)
Send workbook to client.
ilLanguage $lng
setDateFormat(Cell $a_cell, $a_value)
Set date format of cell.
setCellArray(array $a_values, string $a_top_left='A1', $a_null_value=null)
Set cell values from array.
const FORMAT_BIFF
setCellByCoordinates($a_coords, $a_value)
Set cell value by coordinates.
setColors(string $a_coords, string $a_background, ?string $a_font=null)
Set cell(s) colors.
setActiveSheet(int $a_index)
mergeCells(string $coordinatesRange)
getColumnCount()
Returns the number of columns the sheet contains.
prepareString(string $value,)
string $type
prepareDateValue(ilDateTime $a_value)
getSheetTitle()
Return the current sheet title.
setFormat(string $a_format)
Set file format.
const FORMAT_XML
setCell(int $a_row, int $col, $value, ?string $datatype=null)
Set cell value.
string $format
getValidFormats()
prepareBooleanValue(bool $a_value)
addLink(int $a_row, int $a_column, string $a_path)
cleanupNonCharachters(string $string)
static deliverFileAttached(string $path_to_file, ?string $download_file_name=null, ?string $mime_type=null, bool $delete_file=false)
static ilTempnam(?string $a_temp_path=null)
Returns a unique and non existing Path for e temporary file or directory.
language handling
static shortenTextExtended(string $a_str, int $a_len, bool $a_dots=false, bool $a_next_blank=false, bool $a_keep_extension=false)
global $lng
Definition: privfeed.php:31
if(!file_exists('../ilias.ini.php'))
global $DIC
Definition: shib_login.php:26