ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
Worksheet.php
Go to the documentation of this file.
1<?php
2
4
5use ArrayObject;
27
28class Worksheet implements IComparable
29{
30 // Break types
31 const BREAK_NONE = 0;
32 const BREAK_ROW = 1;
33 const BREAK_COLUMN = 2;
34
35 // Sheet state
36 const SHEETSTATE_VISIBLE = 'visible';
37 const SHEETSTATE_HIDDEN = 'hidden';
38 const SHEETSTATE_VERYHIDDEN = 'veryHidden';
39
46
52 private static $invalidCharacters = ['*', ':', '/', '\\', '?', '[', ']'];
53
59 private $parent;
60
66 private $cellCollection;
67
73 private $rowDimensions = [];
74
80 private $defaultRowDimension;
81
87 private $columnDimensions = [];
88
94 private $defaultColumnDimension;
95
101 private $drawingCollection;
102
108 private $chartCollection;
109
115 private $title;
116
122 private $sheetState;
123
129 private $pageSetup;
130
136 private $pageMargins;
137
143 private $headerFooter;
144
150 private $sheetView;
151
157 private $protection;
158
164 private $styles = [];
165
171 private $conditionalStylesCollection = [];
172
178 private $cellCollectionIsSorted = false;
179
185 private $breaks = [];
186
192 private $mergeCells = [];
193
199 private $protectedCells = [];
200
206 private $autoFilter;
207
213 private $freezePane;
214
220 private $topLeftCell;
221
227 private $showGridlines = true;
228
234 private $printGridlines = false;
235
241 private $showRowColHeaders = true;
242
248 private $showSummaryBelow = true;
249
255 private $showSummaryRight = true;
256
262 private $comments = [];
263
269 private $activeCell = 'A1';
270
276 private $selectedCells = 'A1';
277
283 private $cachedHighestColumn = 1;
284
290 private $cachedHighestRow = 1;
291
297 private $rightToLeft = false;
298
304 private $hyperlinkCollection = [];
305
311 private $dataValidationCollection = [];
312
318 private $tabColor;
319
325 private $dirty = true;
326
332 private $hash;
333
339 private $codeName;
340
347 public function __construct(?Spreadsheet $parent = null, $pTitle = 'Worksheet')
348 {
349 // Set parent and title
350 $this->parent = $parent;
351 $this->setTitle($pTitle, false);
352 // setTitle can change $pTitle
353 $this->setCodeName($this->getTitle());
354 $this->setSheetState(self::SHEETSTATE_VISIBLE);
355
356 $this->cellCollection = CellsFactory::getInstance($this);
357 // Set page setup
358 $this->pageSetup = new PageSetup();
359 // Set page margins
360 $this->pageMargins = new PageMargins();
361 // Set page header/footer
362 $this->headerFooter = new HeaderFooter();
363 // Set sheet view
364 $this->sheetView = new SheetView();
365 // Drawing collection
366 $this->drawingCollection = new ArrayObject();
367 // Chart collection
368 $this->chartCollection = new ArrayObject();
369 // Protection
370 $this->protection = new Protection();
371 // Default row dimension
372 $this->defaultRowDimension = new RowDimension(null);
373 // Default column dimension
374 $this->defaultColumnDimension = new ColumnDimension(null);
375 $this->autoFilter = new AutoFilter(null, $this);
376 }
377
382 public function disconnectCells(): void
383 {
384 if ($this->cellCollection !== null) {
385 $this->cellCollection->unsetWorksheetCells();
386 // @phpstan-ignore-next-line
387 $this->cellCollection = null;
388 }
389 // detach ourself from the workbook, so that it can then delete this worksheet successfully
390 // @phpstan-ignore-next-line
391 $this->parent = null;
392 }
393
397 public function __destruct()
398 {
399 Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title);
400
401 $this->disconnectCells();
402 $this->rowDimensions = [];
403 }
404
410 public function getCellCollection()
411 {
412 return $this->cellCollection;
413 }
414
420 public static function getInvalidCharacters()
421 {
422 return self::$invalidCharacters;
423 }
424
432 private static function checkSheetCodeName($pValue)
433 {
434 $CharCount = Shared\StringHelper::countCharacters($pValue);
435 if ($CharCount == 0) {
436 throw new Exception('Sheet code name cannot be empty.');
437 }
438 // Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'"
439 if (
440 (str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) ||
441 (Shared\StringHelper::substring($pValue, -1, 1) == '\'') ||
442 (Shared\StringHelper::substring($pValue, 0, 1) == '\'')
443 ) {
444 throw new Exception('Invalid character found in sheet code name');
445 }
446
447 // Enforce maximum characters allowed for sheet title
448 if ($CharCount > self::SHEET_TITLE_MAXIMUM_LENGTH) {
449 throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.');
450 }
451
452 return $pValue;
453 }
454
462 private static function checkSheetTitle($pValue)
463 {
464 // Some of the printable ASCII characters are invalid: * : / \ ? [ ]
465 if (str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) {
466 throw new Exception('Invalid character found in sheet title');
467 }
468
469 // Enforce maximum characters allowed for sheet title
470 if (Shared\StringHelper::countCharacters($pValue) > self::SHEET_TITLE_MAXIMUM_LENGTH) {
471 throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.');
472 }
473
474 return $pValue;
475 }
476
484 public function getCoordinates($sorted = true)
485 {
486 if ($this->cellCollection == null) {
487 return [];
488 }
489
490 if ($sorted) {
491 return $this->cellCollection->getSortedCoordinates();
492 }
493
494 return $this->cellCollection->getCoordinates();
495 }
496
502 public function getRowDimensions()
503 {
504 return $this->rowDimensions;
505 }
506
512 public function getDefaultRowDimension()
513 {
514 return $this->defaultRowDimension;
515 }
516
522 public function getColumnDimensions()
523 {
524 return $this->columnDimensions;
525 }
526
532 public function getDefaultColumnDimension()
533 {
534 return $this->defaultColumnDimension;
535 }
536
542 public function getDrawingCollection()
543 {
544 return $this->drawingCollection;
545 }
546
552 public function getChartCollection()
553 {
554 return $this->chartCollection;
555 }
556
564 public function addChart(Chart $pChart, $iChartIndex = null)
565 {
566 $pChart->setWorksheet($this);
567 if ($iChartIndex === null) {
568 $this->chartCollection[] = $pChart;
569 } else {
570 // Insert the chart at the requested index
571 array_splice($this->chartCollection, $iChartIndex, 0, [$pChart]);
572 }
573
574 return $pChart;
575 }
576
582 public function getChartCount()
583 {
584 return count($this->chartCollection);
585 }
586
594 public function getChartByIndex($index)
595 {
596 $chartCount = count($this->chartCollection);
597 if ($chartCount == 0) {
598 return false;
599 }
600 if ($index === null) {
601 $index = --$chartCount;
602 }
603 if (!isset($this->chartCollection[$index])) {
604 return false;
605 }
606
607 return $this->chartCollection[$index];
608 }
609
615 public function getChartNames()
616 {
617 $chartNames = [];
618 foreach ($this->chartCollection as $chart) {
619 $chartNames[] = $chart->getName();
620 }
621
622 return $chartNames;
623 }
624
632 public function getChartByName($chartName)
633 {
634 $chartCount = count($this->chartCollection);
635 if ($chartCount == 0) {
636 return false;
637 }
638 foreach ($this->chartCollection as $index => $chart) {
639 if ($chart->getName() == $chartName) {
640 return $this->chartCollection[$index];
641 }
642 }
643
644 return false;
645 }
646
652 public function refreshColumnDimensions()
653 {
654 $currentColumnDimensions = $this->getColumnDimensions();
655 $newColumnDimensions = [];
656
657 foreach ($currentColumnDimensions as $objColumnDimension) {
658 $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension;
659 }
660
661 $this->columnDimensions = $newColumnDimensions;
662
663 return $this;
664 }
665
671 public function refreshRowDimensions()
672 {
673 $currentRowDimensions = $this->getRowDimensions();
674 $newRowDimensions = [];
675
676 foreach ($currentRowDimensions as $objRowDimension) {
677 $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension;
678 }
679
680 $this->rowDimensions = $newRowDimensions;
681
682 return $this;
683 }
684
690 public function calculateWorksheetDimension()
691 {
692 // Return
693 return 'A1:' . $this->getHighestColumn() . $this->getHighestRow();
694 }
695
701 public function calculateWorksheetDataDimension()
702 {
703 // Return
704 return 'A1:' . $this->getHighestDataColumn() . $this->getHighestDataRow();
705 }
706
712 public function calculateColumnWidths()
713 {
714 // initialize $autoSizes array
715 $autoSizes = [];
716 foreach ($this->getColumnDimensions() as $colDimension) {
717 if ($colDimension->getAutoSize()) {
718 $autoSizes[$colDimension->getColumnIndex()] = -1;
719 }
720 }
721
722 // There is only something to do if there are some auto-size columns
723 if (!empty($autoSizes)) {
724 // build list of cells references that participate in a merge
725 $isMergeCell = [];
726 foreach ($this->getMergeCells() as $cells) {
727 foreach (Coordinate::extractAllCellReferencesInRange($cells) as $cellReference) {
728 $isMergeCell[$cellReference] = true;
729 }
730 }
731
732 // loop through all cells in the worksheet
733 foreach ($this->getCoordinates(false) as $coordinate) {
734 $cell = $this->getCellOrNull($coordinate);
735 if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) {
736 //Determine if cell is in merge range
737 $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]);
738
739 //By default merged cells should be ignored
740 $isMergedButProceed = false;
741
742 //The only exception is if it's a merge range value cell of a 'vertical' randge (1 column wide)
743 if ($isMerged && $cell->isMergeRangeValueCell()) {
744 $range = $cell->getMergeRange();
745 $rangeBoundaries = Coordinate::rangeDimension($range);
746 if ($rangeBoundaries[0] == 1) {
747 $isMergedButProceed = true;
748 }
749 }
750
751 // Determine width if cell does not participate in a merge or does and is a value cell of 1-column wide range
752 if (!$isMerged || $isMergedButProceed) {
753 // Calculated value
754 // To formatted string
756 $cell->getCalculatedValue(),
757 $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode()
758 );
759
760 $autoSizes[$this->cellCollection->getCurrentColumn()] = max(
761 (float) $autoSizes[$this->cellCollection->getCurrentColumn()],
762 (float) Shared\Font::calculateColumnWidth(
763 $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(),
764 $cellValue,
765 $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(),
766 $this->getParent()->getDefaultStyle()->getFont()
767 )
768 );
769 }
770 }
771 }
772
773 // adjust column widths
774 foreach ($autoSizes as $columnIndex => $width) {
775 if ($width == -1) {
776 $width = $this->getDefaultColumnDimension()->getWidth();
777 }
778 $this->getColumnDimension($columnIndex)->setWidth($width);
779 }
780 }
781
782 return $this;
783 }
784
790 public function getParent()
791 {
792 return $this->parent;
793 }
794
800 public function rebindParent(Spreadsheet $parent)
801 {
802 if ($this->parent !== null) {
803 $definedNames = $this->parent->getDefinedNames();
804 foreach ($definedNames as $definedName) {
805 $parent->addDefinedName($definedName);
806 }
807
808 $this->parent->removeSheetByIndex(
809 $this->parent->getIndex($this)
810 );
811 }
812 $this->parent = $parent;
813
814 return $this;
815 }
816
822 public function getTitle()
823 {
824 return $this->title;
825 }
826
841 public function setTitle($title, $updateFormulaCellReferences = true, $validate = true)
842 {
843 // Is this a 'rename' or not?
844 if ($this->getTitle() == $title) {
845 return $this;
846 }
847
848 // Old title
849 $oldTitle = $this->getTitle();
850
851 if ($validate) {
852 // Syntax check
853 self::checkSheetTitle($title);
854
855 if ($this->parent) {
856 // Is there already such sheet name?
857 if ($this->parent->sheetNameExists($title)) {
858 // Use name, but append with lowest possible integer
859
860 if (Shared\StringHelper::countCharacters($title) > 29) {
862 }
863 $i = 1;
864 while ($this->parent->sheetNameExists($title . ' ' . $i)) {
865 ++$i;
866 if ($i == 10) {
867 if (Shared\StringHelper::countCharacters($title) > 28) {
869 }
870 } elseif ($i == 100) {
871 if (Shared\StringHelper::countCharacters($title) > 27) {
873 }
874 }
875 }
876
877 $title .= " $i";
878 }
879 }
880 }
881
882 // Set title
883 $this->title = $title;
884 $this->dirty = true;
885
886 if ($this->parent && $this->parent->getCalculationEngine()) {
887 // New title
888 $newTitle = $this->getTitle();
889 $this->parent->getCalculationEngine()
890 ->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
891 if ($updateFormulaCellReferences) {
892 ReferenceHelper::getInstance()->updateNamedFormulas($this->parent, $oldTitle, $newTitle);
893 }
894 }
895
896 return $this;
897 }
898
904 public function getSheetState()
905 {
906 return $this->sheetState;
907 }
908
916 public function setSheetState($value)
917 {
918 $this->sheetState = $value;
919
920 return $this;
921 }
922
928 public function getPageSetup()
929 {
930 return $this->pageSetup;
931 }
932
938 public function setPageSetup(PageSetup $pValue)
939 {
940 $this->pageSetup = $pValue;
941
942 return $this;
943 }
944
950 public function getPageMargins()
951 {
952 return $this->pageMargins;
953 }
954
960 public function setPageMargins(PageMargins $pValue)
961 {
962 $this->pageMargins = $pValue;
963
964 return $this;
965 }
966
972 public function getHeaderFooter()
973 {
974 return $this->headerFooter;
975 }
976
982 public function setHeaderFooter(HeaderFooter $pValue)
983 {
984 $this->headerFooter = $pValue;
985
986 return $this;
987 }
988
994 public function getSheetView()
995 {
996 return $this->sheetView;
997 }
998
1004 public function setSheetView(SheetView $pValue)
1005 {
1006 $this->sheetView = $pValue;
1007
1008 return $this;
1009 }
1010
1016 public function getProtection()
1017 {
1018 return $this->protection;
1019 }
1020
1026 public function setProtection(Protection $pValue)
1027 {
1028 $this->protection = $pValue;
1029 $this->dirty = true;
1030
1031 return $this;
1032 }
1033
1042 public function getHighestColumn($row = null)
1043 {
1044 if ($row == null) {
1045 return Coordinate::stringFromColumnIndex($this->cachedHighestColumn);
1046 }
1047
1048 return $this->getHighestDataColumn($row);
1049 }
1050
1059 public function getHighestDataColumn($row = null)
1060 {
1061 return $this->cellCollection->getHighestColumn($row);
1062 }
1063
1072 public function getHighestRow($column = null)
1073 {
1074 if ($column == null) {
1075 return $this->cachedHighestRow;
1076 }
1077
1078 return $this->getHighestDataRow($column);
1079 }
1080
1089 public function getHighestDataRow($column = null)
1090 {
1091 return $this->cellCollection->getHighestRow($column);
1092 }
1093
1099 public function getHighestRowAndColumn()
1100 {
1101 return $this->cellCollection->getHighestRowAndColumn();
1102 }
1103
1112 public function setCellValue($pCoordinate, $pValue)
1113 {
1114 $this->getCell($pCoordinate)->setValue($pValue);
1115
1116 return $this;
1117 }
1118
1128 public function setCellValueByColumnAndRow($columnIndex, $row, $value)
1129 {
1130 $this->getCellByColumnAndRow($columnIndex, $row)->setValue($value);
1131
1132 return $this;
1133 }
1134
1144 public function setCellValueExplicit($pCoordinate, $pValue, $pDataType)
1145 {
1146 // Set value
1147 $this->getCell($pCoordinate)->setValueExplicit($pValue, $pDataType);
1148
1149 return $this;
1150 }
1151
1162 public function setCellValueExplicitByColumnAndRow($columnIndex, $row, $value, $dataType)
1163 {
1164 $this->getCellByColumnAndRow($columnIndex, $row)->setValueExplicit($value, $dataType);
1165
1166 return $this;
1167 }
1168
1176 public function getCell(string $coordinate): Cell
1177 {
1178 // Shortcut for increased performance for the vast majority of simple cases
1179 if ($this->cellCollection->has($coordinate)) {
1181 $cell = $this->cellCollection->get($coordinate);
1182
1183 return $cell;
1184 }
1185
1187 [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($coordinate);
1188 $cell = $sheet->cellCollection->get($finalCoordinate);
1189
1190 return $cell ?? $sheet->createNewCell($finalCoordinate);
1191 }
1192
1199 private function getWorksheetAndCoordinate(string $pCoordinate): array
1200 {
1201 $sheet = null;
1202 $finalCoordinate = null;
1203
1204 // Worksheet reference?
1205 if (strpos($pCoordinate, '!') !== false) {
1206 $worksheetReference = self::extractSheetTitle($pCoordinate, true);
1207
1208 $sheet = $this->parent->getSheetByName($worksheetReference[0]);
1209 $finalCoordinate = strtoupper($worksheetReference[1]);
1210
1211 if (!$sheet) {
1212 throw new Exception('Sheet not found for name: ' . $worksheetReference[0]);
1213 }
1214 } elseif (
1215 !preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate) &&
1216 preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/i', $pCoordinate)
1217 ) {
1218 // Named range?
1219 $namedRange = $this->validateNamedRange($pCoordinate, true);
1220 if ($namedRange !== null) {
1221 $sheet = $namedRange->getWorksheet();
1222 if (!$sheet) {
1223 throw new Exception('Sheet not found for named range: ' . $namedRange->getName());
1224 }
1225
1226 $cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!');
1227 $finalCoordinate = str_replace('$', '', $cellCoordinate);
1228 }
1229 }
1230
1231 if (!$sheet || !$finalCoordinate) {
1232 $sheet = $this;
1233 $finalCoordinate = strtoupper($pCoordinate);
1234 }
1235
1236 if (Coordinate::coordinateIsRange($finalCoordinate)) {
1237 throw new Exception('Cell coordinate string can not be a range of cells.');
1238 } elseif (strpos($finalCoordinate, '$') !== false) {
1239 throw new Exception('Cell coordinate must not be absolute.');
1240 }
1241
1242 return [$sheet, $finalCoordinate];
1243 }
1244
1252 private function getCellOrNull($coordinate): ?Cell
1253 {
1254 // Check cell collection
1255 if ($this->cellCollection->has($coordinate)) {
1256 return $this->cellCollection->get($coordinate);
1257 }
1258
1259 return null;
1260 }
1261
1270 public function getCellByColumnAndRow($columnIndex, $row): Cell
1271 {
1272 $columnLetter = Coordinate::stringFromColumnIndex($columnIndex);
1273 $coordinate = $columnLetter . $row;
1274
1275 if ($this->cellCollection->has($coordinate)) {
1277 $cell = $this->cellCollection->get($coordinate);
1278
1279 return $cell;
1280 }
1281
1282 // Create new cell object, if required
1283 return $this->createNewCell($coordinate);
1284 }
1285
1293 private function createNewCell($pCoordinate)
1294 {
1295 $cell = new Cell(null, DataType::TYPE_NULL, $this);
1296 $this->cellCollection->add($pCoordinate, $cell);
1297 $this->cellCollectionIsSorted = false;
1298
1299 // Coordinates
1300 [$column, $row] = Coordinate::coordinateFromString($pCoordinate);
1301 $aIndexes = Coordinate::indexesFromString($pCoordinate);
1302 if ($this->cachedHighestColumn < $aIndexes[0]) {
1303 $this->cachedHighestColumn = $aIndexes[0];
1304 }
1305 if ($aIndexes[1] > $this->cachedHighestRow) {
1306 $this->cachedHighestRow = $aIndexes[1];
1307 }
1308
1309 // Cell needs appropriate xfIndex from dimensions records
1310 // but don't create dimension records if they don't already exist
1311 $rowDimension = $this->rowDimensions[$row] ?? null;
1312 $columnDimension = $this->columnDimensions[$column] ?? null;
1313
1314 if ($rowDimension !== null && $rowDimension->getXfIndex() > 0) {
1315 // then there is a row dimension with explicit style, assign it to the cell
1316 $cell->setXfIndex($rowDimension->getXfIndex());
1317 } elseif ($columnDimension !== null && $columnDimension->getXfIndex() > 0) {
1318 // then there is a column dimension, assign it to the cell
1319 $cell->setXfIndex($columnDimension->getXfIndex());
1320 }
1321
1322 return $cell;
1323 }
1324
1332 public function cellExists($coordinate)
1333 {
1335 [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($coordinate);
1336
1337 return $sheet->cellCollection->has($finalCoordinate);
1338 }
1339
1348 public function cellExistsByColumnAndRow($columnIndex, $row)
1349 {
1350 return $this->cellExists(Coordinate::stringFromColumnIndex($columnIndex) . $row);
1351 }
1352
1358 public function getRowDimension(int $pRow): RowDimension
1359 {
1360 // Get row dimension
1361 if (!isset($this->rowDimensions[$pRow])) {
1362 $this->rowDimensions[$pRow] = new RowDimension($pRow);
1363
1364 $this->cachedHighestRow = max($this->cachedHighestRow, $pRow);
1365 }
1366
1367 return $this->rowDimensions[$pRow];
1368 }
1369
1375 public function getColumnDimension(string $pColumn): ColumnDimension
1376 {
1377 // Uppercase coordinate
1378 $pColumn = strtoupper($pColumn);
1379
1380 // Fetch dimensions
1381 if (!isset($this->columnDimensions[$pColumn])) {
1382 $this->columnDimensions[$pColumn] = new ColumnDimension($pColumn);
1383
1384 $columnIndex = Coordinate::columnIndexFromString($pColumn);
1385 if ($this->cachedHighestColumn < $columnIndex) {
1386 $this->cachedHighestColumn = $columnIndex;
1387 }
1388 }
1389
1390 return $this->columnDimensions[$pColumn];
1391 }
1392
1398 public function getColumnDimensionByColumn(int $columnIndex): ColumnDimension
1399 {
1400 return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex));
1401 }
1402
1408 public function getStyles()
1409 {
1410 return $this->styles;
1411 }
1412
1420 public function getStyle($pCellCoordinate)
1421 {
1422 // set this sheet as active
1423 $this->parent->setActiveSheetIndex($this->parent->getIndex($this));
1424
1425 // set cell coordinate as active
1426 $this->setSelectedCells($pCellCoordinate);
1427
1428 return $this->parent->getCellXfSupervisor();
1429 }
1430
1438 public function getConditionalStyles($pCoordinate)
1439 {
1440 $pCoordinate = strtoupper($pCoordinate);
1441 if (!isset($this->conditionalStylesCollection[$pCoordinate])) {
1442 $this->conditionalStylesCollection[$pCoordinate] = [];
1443 }
1444
1445 return $this->conditionalStylesCollection[$pCoordinate];
1446 }
1447
1455 public function conditionalStylesExists($pCoordinate)
1456 {
1457 return isset($this->conditionalStylesCollection[strtoupper($pCoordinate)]);
1458 }
1459
1467 public function removeConditionalStyles($pCoordinate)
1468 {
1469 unset($this->conditionalStylesCollection[strtoupper($pCoordinate)]);
1470
1471 return $this;
1472 }
1473
1479 public function getConditionalStylesCollection()
1480 {
1481 return $this->conditionalStylesCollection;
1482 }
1483
1492 public function setConditionalStyles($pCoordinate, $pValue)
1493 {
1494 $this->conditionalStylesCollection[strtoupper($pCoordinate)] = $pValue;
1495
1496 return $this;
1497 }
1498
1509 public function getStyleByColumnAndRow($columnIndex1, $row1, $columnIndex2 = null, $row2 = null)
1510 {
1511 if ($columnIndex2 !== null && $row2 !== null) {
1512 $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
1513
1514 return $this->getStyle($cellRange);
1515 }
1516
1517 return $this->getStyle(Coordinate::stringFromColumnIndex($columnIndex1) . $row1);
1518 }
1519
1530 public function duplicateStyle(Style $pCellStyle, $pRange)
1531 {
1532 // Add the style to the workbook if necessary
1533 $workbook = $this->parent;
1534 if ($existingStyle = $this->parent->getCellXfByHashCode($pCellStyle->getHashCode())) {
1535 // there is already such cell Xf in our collection
1536 $xfIndex = $existingStyle->getIndex();
1537 } else {
1538 // we don't have such a cell Xf, need to add
1539 $workbook->addCellXf($pCellStyle);
1540 $xfIndex = $pCellStyle->getIndex();
1541 }
1542
1543 // Calculate range outer borders
1544 [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($pRange . ':' . $pRange);
1545
1546 // Make sure we can loop upwards on rows and columns
1547 if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
1548 $tmp = $rangeStart;
1549 $rangeStart = $rangeEnd;
1550 $rangeEnd = $tmp;
1551 }
1552
1553 // Loop through cells and apply styles
1554 for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
1555 for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
1556 $this->getCell(Coordinate::stringFromColumnIndex($col) . $row)->setXfIndex($xfIndex);
1557 }
1558 }
1559
1560 return $this;
1561 }
1562
1573 public function duplicateConditionalStyle(array $pCellStyle, $pRange = '')
1574 {
1575 foreach ($pCellStyle as $cellStyle) {
1576 if (!($cellStyle instanceof Conditional)) {
1577 throw new Exception('Style is not a conditional style');
1578 }
1579 }
1580
1581 // Calculate range outer borders
1582 [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($pRange . ':' . $pRange);
1583
1584 // Make sure we can loop upwards on rows and columns
1585 if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
1586 $tmp = $rangeStart;
1587 $rangeStart = $rangeEnd;
1588 $rangeEnd = $tmp;
1589 }
1590
1591 // Loop through cells and apply styles
1592 for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
1593 for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
1594 $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $pCellStyle);
1595 }
1596 }
1597
1598 return $this;
1599 }
1600
1609 public function setBreak($pCoordinate, $pBreak)
1610 {
1611 // Uppercase coordinate
1612 $pCoordinate = strtoupper($pCoordinate);
1613
1614 if ($pCoordinate != '') {
1615 if ($pBreak == self::BREAK_NONE) {
1616 if (isset($this->breaks[$pCoordinate])) {
1617 unset($this->breaks[$pCoordinate]);
1618 }
1619 } else {
1620 $this->breaks[$pCoordinate] = $pBreak;
1621 }
1622 } else {
1623 throw new Exception('No cell coordinate specified.');
1624 }
1625
1626 return $this;
1627 }
1628
1638 public function setBreakByColumnAndRow($columnIndex, $row, $break)
1639 {
1640 return $this->setBreak(Coordinate::stringFromColumnIndex($columnIndex) . $row, $break);
1641 }
1642
1648 public function getBreaks()
1649 {
1650 return $this->breaks;
1651 }
1652
1660 public function mergeCells($pRange)
1661 {
1662 // Uppercase coordinate
1663 $pRange = strtoupper($pRange);
1664
1665 if (strpos($pRange, ':') !== false) {
1666 $this->mergeCells[$pRange] = $pRange;
1667
1668 // make sure cells are created
1669
1670 // get the cells in the range
1671 $aReferences = Coordinate::extractAllCellReferencesInRange($pRange);
1672
1673 // create upper left cell if it does not already exist
1674 $upperLeft = $aReferences[0];
1675 if (!$this->cellExists($upperLeft)) {
1676 $this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL);
1677 }
1678
1679 // Blank out the rest of the cells in the range (if they exist)
1680 $count = count($aReferences);
1681 for ($i = 1; $i < $count; ++$i) {
1682 if ($this->cellExists($aReferences[$i])) {
1683 $this->getCell($aReferences[$i])->setValueExplicit(null, DataType::TYPE_NULL);
1684 }
1685 }
1686 } else {
1687 throw new Exception('Merge must be set on a range of cells.');
1688 }
1689
1690 return $this;
1691 }
1692
1703 public function mergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
1704 {
1705 $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
1706
1707 return $this->mergeCells($cellRange);
1708 }
1709
1717 public function unmergeCells($pRange)
1718 {
1719 // Uppercase coordinate
1720 $pRange = strtoupper($pRange);
1721
1722 if (strpos($pRange, ':') !== false) {
1723 if (isset($this->mergeCells[$pRange])) {
1724 unset($this->mergeCells[$pRange]);
1725 } else {
1726 throw new Exception('Cell range ' . $pRange . ' not known as merged.');
1727 }
1728 } else {
1729 throw new Exception('Merge can only be removed from a range of cells.');
1730 }
1731
1732 return $this;
1733 }
1734
1745 public function unmergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
1746 {
1747 $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
1748
1749 return $this->unmergeCells($cellRange);
1750 }
1751
1757 public function getMergeCells()
1758 {
1759 return $this->mergeCells;
1760 }
1761
1770 public function setMergeCells(array $pValue)
1771 {
1772 $this->mergeCells = $pValue;
1773
1774 return $this;
1775 }
1776
1786 public function protectCells($pRange, $pPassword, $pAlreadyHashed = false)
1787 {
1788 // Uppercase coordinate
1789 $pRange = strtoupper($pRange);
1790
1791 if (!$pAlreadyHashed) {
1792 $pPassword = Shared\PasswordHasher::hashPassword($pPassword);
1793 }
1794 $this->protectedCells[$pRange] = $pPassword;
1795
1796 return $this;
1797 }
1798
1811 public function protectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2, $password, $alreadyHashed = false)
1812 {
1813 $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
1814
1815 return $this->protectCells($cellRange, $password, $alreadyHashed);
1816 }
1817
1825 public function unprotectCells($pRange)
1826 {
1827 // Uppercase coordinate
1828 $pRange = strtoupper($pRange);
1829
1830 if (isset($this->protectedCells[$pRange])) {
1831 unset($this->protectedCells[$pRange]);
1832 } else {
1833 throw new Exception('Cell range ' . $pRange . ' not known as protected.');
1834 }
1835
1836 return $this;
1837 }
1838
1849 public function unprotectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
1850 {
1851 $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
1852
1853 return $this->unprotectCells($cellRange);
1854 }
1855
1861 public function getProtectedCells()
1862 {
1863 return $this->protectedCells;
1864 }
1865
1871 public function getAutoFilter()
1872 {
1873 return $this->autoFilter;
1874 }
1875
1884 public function setAutoFilter($pValue)
1885 {
1886 if (is_string($pValue)) {
1887 $this->autoFilter->setRange($pValue);
1888 } elseif (is_object($pValue) && ($pValue instanceof AutoFilter)) {
1889 $this->autoFilter = $pValue;
1890 }
1891
1892 return $this;
1893 }
1894
1905 public function setAutoFilterByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
1906 {
1907 return $this->setAutoFilter(
1908 Coordinate::stringFromColumnIndex($columnIndex1) . $row1
1909 . ':' .
1910 Coordinate::stringFromColumnIndex($columnIndex2) . $row2
1911 );
1912 }
1913
1919 public function removeAutoFilter()
1920 {
1921 $this->autoFilter->setRange(null);
1922
1923 return $this;
1924 }
1925
1931 public function getFreezePane()
1932 {
1933 return $this->freezePane;
1934 }
1935
1950 public function freezePane($cell, $topLeftCell = null)
1951 {
1952 if (is_string($cell) && Coordinate::coordinateIsRange($cell)) {
1953 throw new Exception('Freeze pane can not be set on a range of cells.');
1954 }
1955
1956 if ($cell !== null && $topLeftCell === null) {
1957 $coordinate = Coordinate::coordinateFromString($cell);
1958 $topLeftCell = $coordinate[0] . $coordinate[1];
1959 }
1960
1961 $this->freezePane = $cell;
1962 $this->topLeftCell = $topLeftCell;
1963
1964 return $this;
1965 }
1966
1975 public function freezePaneByColumnAndRow($columnIndex, $row)
1976 {
1977 return $this->freezePane(Coordinate::stringFromColumnIndex($columnIndex) . $row);
1978 }
1979
1985 public function unfreezePane()
1986 {
1987 return $this->freezePane(null);
1988 }
1989
1995 public function getTopLeftCell()
1996 {
1997 return $this->topLeftCell;
1998 }
1999
2008 public function insertNewRowBefore($pBefore, $pNumRows = 1)
2009 {
2010 if ($pBefore >= 1) {
2011 $objReferenceHelper = ReferenceHelper::getInstance();
2012 $objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this);
2013 } else {
2014 throw new Exception('Rows can only be inserted before at least row 1.');
2015 }
2016
2017 return $this;
2018 }
2019
2028 public function insertNewColumnBefore($pBefore, $pNumCols = 1)
2029 {
2030 if (!is_numeric($pBefore)) {
2031 $objReferenceHelper = ReferenceHelper::getInstance();
2032 $objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this);
2033 } else {
2034 throw new Exception('Column references should not be numeric.');
2035 }
2036
2037 return $this;
2038 }
2039
2048 public function insertNewColumnBeforeByIndex($beforeColumnIndex, $pNumCols = 1)
2049 {
2050 if ($beforeColumnIndex >= 1) {
2051 return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $pNumCols);
2052 }
2053
2054 throw new Exception('Columns can only be inserted before at least column A (1).');
2055 }
2056
2065 public function removeRow($pRow, $pNumRows = 1)
2066 {
2067 if ($pRow < 1) {
2068 throw new Exception('Rows to be deleted should at least start from row 1.');
2069 }
2070
2071 $highestRow = $this->getHighestDataRow();
2072 $removedRowsCounter = 0;
2073
2074 for ($r = 0; $r < $pNumRows; ++$r) {
2075 if ($pRow + $r <= $highestRow) {
2076 $this->getCellCollection()->removeRow($pRow + $r);
2077 ++$removedRowsCounter;
2078 }
2079 }
2080
2081 $objReferenceHelper = ReferenceHelper::getInstance();
2082 $objReferenceHelper->insertNewBefore('A' . ($pRow + $pNumRows), 0, -$pNumRows, $this);
2083 for ($r = 0; $r < $removedRowsCounter; ++$r) {
2084 $this->getCellCollection()->removeRow($highestRow);
2085 --$highestRow;
2086 }
2087
2088 return $this;
2089 }
2090
2099 public function removeColumn($pColumn, $pNumCols = 1)
2100 {
2101 if (is_numeric($pColumn)) {
2102 throw new Exception('Column references should not be numeric.');
2103 }
2104
2105 $highestColumn = $this->getHighestDataColumn();
2106 $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
2107 $pColumnIndex = Coordinate::columnIndexFromString($pColumn);
2108
2109 if ($pColumnIndex > $highestColumnIndex) {
2110 return $this;
2111 }
2112
2113 $pColumn = Coordinate::stringFromColumnIndex($pColumnIndex + $pNumCols);
2114 $objReferenceHelper = ReferenceHelper::getInstance();
2115 $objReferenceHelper->insertNewBefore($pColumn . '1', -$pNumCols, 0, $this);
2116
2117 $maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1;
2118
2119 for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $pNumCols); $c < $n; ++$c) {
2120 $this->getCellCollection()->removeColumn($highestColumn);
2121 $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1);
2122 }
2123
2124 $this->garbageCollect();
2125
2126 return $this;
2127 }
2128
2137 public function removeColumnByIndex($columnIndex, $numColumns = 1)
2138 {
2139 if ($columnIndex >= 1) {
2140 return $this->removeColumn(Coordinate::stringFromColumnIndex($columnIndex), $numColumns);
2141 }
2142
2143 throw new Exception('Columns to be deleted should at least start from column A (1)');
2144 }
2145
2151 public function getShowGridlines()
2152 {
2153 return $this->showGridlines;
2154 }
2155
2163 public function setShowGridlines($pValue)
2164 {
2165 $this->showGridlines = $pValue;
2166
2167 return $this;
2168 }
2169
2175 public function getPrintGridlines()
2176 {
2177 return $this->printGridlines;
2178 }
2179
2187 public function setPrintGridlines($pValue)
2188 {
2189 $this->printGridlines = $pValue;
2190
2191 return $this;
2192 }
2193
2199 public function getShowRowColHeaders()
2200 {
2201 return $this->showRowColHeaders;
2202 }
2203
2211 public function setShowRowColHeaders($pValue)
2212 {
2213 $this->showRowColHeaders = $pValue;
2214
2215 return $this;
2216 }
2217
2223 public function getShowSummaryBelow()
2224 {
2225 return $this->showSummaryBelow;
2226 }
2227
2235 public function setShowSummaryBelow($pValue)
2236 {
2237 $this->showSummaryBelow = $pValue;
2238
2239 return $this;
2240 }
2241
2247 public function getShowSummaryRight()
2248 {
2249 return $this->showSummaryRight;
2250 }
2251
2259 public function setShowSummaryRight($pValue)
2260 {
2261 $this->showSummaryRight = $pValue;
2262
2263 return $this;
2264 }
2265
2271 public function getComments()
2272 {
2273 return $this->comments;
2274 }
2275
2283 public function setComments(array $pValue)
2284 {
2285 $this->comments = $pValue;
2286
2287 return $this;
2288 }
2289
2297 public function getComment($pCellCoordinate)
2298 {
2299 // Uppercase coordinate
2300 $pCellCoordinate = strtoupper($pCellCoordinate);
2301
2302 if (Coordinate::coordinateIsRange($pCellCoordinate)) {
2303 throw new Exception('Cell coordinate string can not be a range of cells.');
2304 } elseif (strpos($pCellCoordinate, '$') !== false) {
2305 throw new Exception('Cell coordinate string must not be absolute.');
2306 } elseif ($pCellCoordinate == '') {
2307 throw new Exception('Cell coordinate can not be zero-length string.');
2308 }
2309
2310 // Check if we already have a comment for this cell.
2311 if (isset($this->comments[$pCellCoordinate])) {
2312 return $this->comments[$pCellCoordinate];
2313 }
2314
2315 // If not, create a new comment.
2316 $newComment = new Comment();
2317 $this->comments[$pCellCoordinate] = $newComment;
2318
2319 return $newComment;
2320 }
2321
2330 public function getCommentByColumnAndRow($columnIndex, $row)
2331 {
2332 return $this->getComment(Coordinate::stringFromColumnIndex($columnIndex) . $row);
2333 }
2334
2340 public function getActiveCell()
2341 {
2342 return $this->activeCell;
2343 }
2344
2350 public function getSelectedCells()
2351 {
2352 return $this->selectedCells;
2353 }
2354
2362 public function setSelectedCell($pCoordinate)
2363 {
2364 return $this->setSelectedCells($pCoordinate);
2365 }
2366
2374 public function setSelectedCells($pCoordinate)
2375 {
2376 // Uppercase coordinate
2377 $pCoordinate = strtoupper($pCoordinate);
2378
2379 // Convert 'A' to 'A:A'
2380 $pCoordinate = preg_replace('/^([A-Z]+)$/', '${1}:${1}', $pCoordinate);
2381
2382 // Convert '1' to '1:1'
2383 $pCoordinate = preg_replace('/^(\d+)$/', '${1}:${1}', $pCoordinate);
2384
2385 // Convert 'A:C' to 'A1:C1048576'
2386 $pCoordinate = preg_replace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $pCoordinate);
2387
2388 // Convert '1:3' to 'A1:XFD3'
2389 $pCoordinate = preg_replace('/^(\d+):(\d+)$/', 'A${1}:XFD${2}', $pCoordinate);
2390
2391 if (Coordinate::coordinateIsRange($pCoordinate)) {
2392 [$first] = Coordinate::splitRange($pCoordinate);
2393 $this->activeCell = $first[0];
2394 } else {
2395 $this->activeCell = $pCoordinate;
2396 }
2397 $this->selectedCells = $pCoordinate;
2398
2399 return $this;
2400 }
2401
2410 public function setSelectedCellByColumnAndRow($columnIndex, $row)
2411 {
2412 return $this->setSelectedCells(Coordinate::stringFromColumnIndex($columnIndex) . $row);
2413 }
2414
2420 public function getRightToLeft()
2421 {
2422 return $this->rightToLeft;
2423 }
2424
2432 public function setRightToLeft($value)
2433 {
2434 $this->rightToLeft = $value;
2435
2436 return $this;
2437 }
2438
2449 public function fromArray(array $source, $nullValue = null, $startCell = 'A1', $strictNullComparison = false)
2450 {
2451 // Convert a 1-D array to 2-D (for ease of looping)
2452 if (!is_array(end($source))) {
2453 $source = [$source];
2454 }
2455
2456 // start coordinate
2457 [$startColumn, $startRow] = Coordinate::coordinateFromString($startCell);
2458
2459 // Loop through $source
2460 foreach ($source as $rowData) {
2461 $currentColumn = $startColumn;
2462 foreach ($rowData as $cellValue) {
2463 if ($strictNullComparison) {
2464 if ($cellValue !== $nullValue) {
2465 // Set cell value
2466 $this->getCell($currentColumn . $startRow)->setValue($cellValue);
2467 }
2468 } else {
2469 if ($cellValue != $nullValue) {
2470 // Set cell value
2471 $this->getCell($currentColumn . $startRow)->setValue($cellValue);
2472 }
2473 }
2474 ++$currentColumn;
2475 }
2476 ++$startRow;
2477 }
2478
2479 return $this;
2480 }
2481
2494 public function rangeToArray($pRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
2495 {
2496 // Returnvalue
2497 $returnValue = [];
2498 // Identify the range that we need to extract from the worksheet
2499 [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($pRange);
2500 $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]);
2501 $minRow = $rangeStart[1];
2502 $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]);
2503 $maxRow = $rangeEnd[1];
2504
2505 ++$maxCol;
2506 // Loop through rows
2507 $r = -1;
2508 for ($row = $minRow; $row <= $maxRow; ++$row) {
2509 $rRef = $returnCellRef ? $row : ++$r;
2510 $c = -1;
2511 // Loop through columns in the current row
2512 for ($col = $minCol; $col != $maxCol; ++$col) {
2513 $cRef = $returnCellRef ? $col : ++$c;
2514 // Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen
2515 // so we test and retrieve directly against cellCollection
2516 if ($this->cellCollection->has($col . $row)) {
2517 // Cell exists
2518 $cell = $this->cellCollection->get($col . $row);
2519 if ($cell->getValue() !== null) {
2520 if ($cell->getValue() instanceof RichText) {
2521 $returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText();
2522 } else {
2523 if ($calculateFormulas) {
2524 $returnValue[$rRef][$cRef] = $cell->getCalculatedValue();
2525 } else {
2526 $returnValue[$rRef][$cRef] = $cell->getValue();
2527 }
2528 }
2529
2530 if ($formatData) {
2531 $style = $this->parent->getCellXfByIndex($cell->getXfIndex());
2532 $returnValue[$rRef][$cRef] = NumberFormat::toFormattedString(
2533 $returnValue[$rRef][$cRef],
2534 ($style && $style->getNumberFormat()) ? $style->getNumberFormat()->getFormatCode() : NumberFormat::FORMAT_GENERAL
2535 );
2536 }
2537 } else {
2538 // Cell holds a NULL
2539 $returnValue[$rRef][$cRef] = $nullValue;
2540 }
2541 } else {
2542 // Cell doesn't exist
2543 $returnValue[$rRef][$cRef] = $nullValue;
2544 }
2545 }
2546 }
2547
2548 // Return
2549 return $returnValue;
2550 }
2551
2552 private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName
2553 {
2554 $namedRange = DefinedName::resolveName($definedName, $this);
2555 if ($namedRange === null) {
2556 if ($returnNullIfInvalid) {
2557 return null;
2558 }
2559
2560 throw new Exception('Named Range ' . $definedName . ' does not exist.');
2561 }
2562
2563 if ($namedRange->isFormula()) {
2564 if ($returnNullIfInvalid) {
2565 return null;
2566 }
2567
2568 throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.');
2569 }
2570
2571 if ($namedRange->getLocalOnly() && $this->getHashCode() !== $namedRange->getWorksheet()->getHashCode()) {
2572 if ($returnNullIfInvalid) {
2573 return null;
2574 }
2575
2576 throw new Exception(
2577 'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle()
2578 );
2579 }
2580
2581 return $namedRange;
2582 }
2583
2596 public function namedRangeToArray(string $definedName, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
2597 {
2598 $namedRange = $this->validateNamedRange($definedName);
2599 $workSheet = $namedRange->getWorksheet();
2600 $cellRange = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!');
2601 $cellRange = str_replace('$', '', $cellRange);
2602
2603 return $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef);
2604 }
2605
2617 public function toArray($nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
2618 {
2619 // Garbage collect...
2620 $this->garbageCollect();
2621
2622 // Identify the range that we need to extract from the worksheet
2623 $maxCol = $this->getHighestColumn();
2624 $maxRow = $this->getHighestRow();
2625
2626 // Return
2627 return $this->rangeToArray('A1:' . $maxCol . $maxRow, $nullValue, $calculateFormulas, $formatData, $returnCellRef);
2628 }
2629
2638 public function getRowIterator($startRow = 1, $endRow = null)
2639 {
2640 return new RowIterator($this, $startRow, $endRow);
2641 }
2642
2651 public function getColumnIterator($startColumn = 'A', $endColumn = null)
2652 {
2653 return new ColumnIterator($this, $startColumn, $endColumn);
2654 }
2655
2661 public function garbageCollect()
2662 {
2663 // Flush cache
2664 $this->cellCollection->get('A1');
2665
2666 // Lookup highest column and highest row if cells are cleaned
2667 $colRow = $this->cellCollection->getHighestRowAndColumn();
2668 $highestRow = $colRow['row'];
2669 $highestColumn = Coordinate::columnIndexFromString($colRow['column']);
2670
2671 // Loop through column dimensions
2672 foreach ($this->columnDimensions as $dimension) {
2673 $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex()));
2674 }
2675
2676 // Loop through row dimensions
2677 foreach ($this->rowDimensions as $dimension) {
2678 $highestRow = max($highestRow, $dimension->getRowIndex());
2679 }
2680
2681 // Cache values
2682 if ($highestColumn < 1) {
2683 $this->cachedHighestColumn = 1;
2684 } else {
2685 $this->cachedHighestColumn = $highestColumn;
2686 }
2687 $this->cachedHighestRow = $highestRow;
2688
2689 // Return
2690 return $this;
2691 }
2692
2698 public function getHashCode()
2699 {
2700 if ($this->dirty) {
2701 $this->hash = md5($this->title . $this->autoFilter . ($this->protection->isProtectionEnabled() ? 't' : 'f') . __CLASS__);
2702 $this->dirty = false;
2703 }
2704
2705 return $this->hash;
2706 }
2707
2719 public static function extractSheetTitle($pRange, $returnRange = false)
2720 {
2721 // Sheet title included?
2722 if (($sep = strrpos($pRange, '!')) === false) {
2723 return $returnRange ? ['', $pRange] : '';
2724 }
2725
2726 if ($returnRange) {
2727 return [substr($pRange, 0, $sep), substr($pRange, $sep + 1)];
2728 }
2729
2730 return substr($pRange, $sep + 1);
2731 }
2732
2740 public function getHyperlink($pCellCoordinate)
2741 {
2742 // return hyperlink if we already have one
2743 if (isset($this->hyperlinkCollection[$pCellCoordinate])) {
2744 return $this->hyperlinkCollection[$pCellCoordinate];
2745 }
2746
2747 // else create hyperlink
2748 $this->hyperlinkCollection[$pCellCoordinate] = new Hyperlink();
2749
2750 return $this->hyperlinkCollection[$pCellCoordinate];
2751 }
2752
2760 public function setHyperlink($pCellCoordinate, ?Hyperlink $pHyperlink = null)
2761 {
2762 if ($pHyperlink === null) {
2763 unset($this->hyperlinkCollection[$pCellCoordinate]);
2764 } else {
2765 $this->hyperlinkCollection[$pCellCoordinate] = $pHyperlink;
2766 }
2767
2768 return $this;
2769 }
2770
2778 public function hyperlinkExists($pCoordinate)
2779 {
2780 return isset($this->hyperlinkCollection[$pCoordinate]);
2781 }
2782
2788 public function getHyperlinkCollection()
2789 {
2790 return $this->hyperlinkCollection;
2791 }
2792
2800 public function getDataValidation($pCellCoordinate)
2801 {
2802 // return data validation if we already have one
2803 if (isset($this->dataValidationCollection[$pCellCoordinate])) {
2804 return $this->dataValidationCollection[$pCellCoordinate];
2805 }
2806
2807 // else create data validation
2808 $this->dataValidationCollection[$pCellCoordinate] = new DataValidation();
2809
2810 return $this->dataValidationCollection[$pCellCoordinate];
2811 }
2812
2820 public function setDataValidation($pCellCoordinate, ?DataValidation $pDataValidation = null)
2821 {
2822 if ($pDataValidation === null) {
2823 unset($this->dataValidationCollection[$pCellCoordinate]);
2824 } else {
2825 $this->dataValidationCollection[$pCellCoordinate] = $pDataValidation;
2826 }
2827
2828 return $this;
2829 }
2830
2838 public function dataValidationExists($pCoordinate)
2839 {
2840 return isset($this->dataValidationCollection[$pCoordinate]);
2841 }
2842
2848 public function getDataValidationCollection()
2849 {
2850 return $this->dataValidationCollection;
2851 }
2852
2860 public function shrinkRangeToFit($range)
2861 {
2862 $maxCol = $this->getHighestColumn();
2863 $maxRow = $this->getHighestRow();
2864 $maxCol = Coordinate::columnIndexFromString($maxCol);
2865
2866 $rangeBlocks = explode(' ', $range);
2867 foreach ($rangeBlocks as &$rangeSet) {
2868 $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet);
2869
2870 if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) {
2871 $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol);
2872 }
2873 if ($rangeBoundaries[0][1] > $maxRow) {
2874 $rangeBoundaries[0][1] = $maxRow;
2875 }
2876 if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) {
2877 $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol);
2878 }
2879 if ($rangeBoundaries[1][1] > $maxRow) {
2880 $rangeBoundaries[1][1] = $maxRow;
2881 }
2882 $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1];
2883 }
2884 unset($rangeSet);
2885
2886 return implode(' ', $rangeBlocks);
2887 }
2888
2894 public function getTabColor()
2895 {
2896 if ($this->tabColor === null) {
2897 $this->tabColor = new Color();
2898 }
2899
2900 return $this->tabColor;
2901 }
2902
2908 public function resetTabColor()
2909 {
2910 $this->tabColor = null;
2911
2912 return $this;
2913 }
2914
2920 public function isTabColorSet()
2921 {
2922 return $this->tabColor !== null;
2923 }
2924
2930 public function copy()
2931 {
2932 return clone $this;
2933 }
2934
2938 public function __clone()
2939 {
2940 // @phpstan-ignore-next-line
2941 foreach ($this as $key => $val) {
2942 if ($key == 'parent') {
2943 continue;
2944 }
2945
2946 if (is_object($val) || (is_array($val))) {
2947 if ($key == 'cellCollection') {
2948 $newCollection = $this->cellCollection->cloneCellCollection($this);
2949 $this->cellCollection = $newCollection;
2950 } elseif ($key == 'drawingCollection') {
2951 $currentCollection = $this->drawingCollection;
2952 $this->drawingCollection = new ArrayObject();
2953 foreach ($currentCollection as $item) {
2954 if (is_object($item)) {
2955 $newDrawing = clone $item;
2956 $newDrawing->setWorksheet($this);
2957 }
2958 }
2959 } elseif (($key == 'autoFilter') && ($this->autoFilter instanceof AutoFilter)) {
2960 $newAutoFilter = clone $this->autoFilter;
2961 $this->autoFilter = $newAutoFilter;
2962 $this->autoFilter->setParent($this);
2963 } else {
2964 $this->{$key} = unserialize(serialize($val));
2965 }
2966 }
2967 }
2968 }
2969
2980 public function setCodeName($pValue, $validate = true)
2981 {
2982 // Is this a 'rename' or not?
2983 if ($this->getCodeName() == $pValue) {
2984 return $this;
2985 }
2986
2987 if ($validate) {
2988 $pValue = str_replace(' ', '_', $pValue); //Excel does this automatically without flinching, we are doing the same
2989
2990 // Syntax check
2991 // throw an exception if not valid
2992 self::checkSheetCodeName($pValue);
2993
2994 // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_'
2995
2996 if ($this->getParent()) {
2997 // Is there already such sheet name?
2998 if ($this->getParent()->sheetCodeNameExists($pValue)) {
2999 // Use name, but append with lowest possible integer
3000
3001 if (Shared\StringHelper::countCharacters($pValue) > 29) {
3002 $pValue = Shared\StringHelper::substring($pValue, 0, 29);
3003 }
3004 $i = 1;
3005 while ($this->getParent()->sheetCodeNameExists($pValue . '_' . $i)) {
3006 ++$i;
3007 if ($i == 10) {
3008 if (Shared\StringHelper::countCharacters($pValue) > 28) {
3009 $pValue = Shared\StringHelper::substring($pValue, 0, 28);
3010 }
3011 } elseif ($i == 100) {
3012 if (Shared\StringHelper::countCharacters($pValue) > 27) {
3013 $pValue = Shared\StringHelper::substring($pValue, 0, 27);
3014 }
3015 }
3016 }
3017
3018 $pValue .= '_' . $i; // ok, we have a valid name
3019 }
3020 }
3021 }
3022
3023 $this->codeName = $pValue;
3024
3025 return $this;
3026 }
3027
3033 public function getCodeName()
3034 {
3035 return $this->codeName;
3036 }
3037
3043 public function hasCodeName()
3044 {
3045 return $this->codeName !== null;
3046 }
3047}
$n
Definition: RandomTest.php:85
$source
Definition: linkback.php:22
An exception for terminatinating execution or to throw for unit testing.
static getInstance(?Spreadsheet $spreadsheet=null)
Get an instance of this class.
Helper class to manipulate cell coordinates.
Definition: Coordinate.php:15
static getRangeBoundaries($pRange)
Calculate range boundaries.
Definition: Coordinate.php:238
static coordinateFromString($pCoordinateString)
Coordinate from string.
Definition: Coordinate.php:32
static coordinateIsRange($coord)
Checks if a coordinate represents a range of cells.
Definition: Coordinate.php:69
static indexesFromString(string $coordinates)
Get indexes from a string coordinates.
Definition: Coordinate.php:52
static columnIndexFromString($pString)
Column index from string.
Definition: Coordinate.php:265
static stringFromColumnIndex($columnIndex)
String from column index.
Definition: Coordinate.php:313
static splitRange($pRange)
Split range into coordinate strings.
Definition: Coordinate.php:140
static rangeDimension($pRange)
Calculate range dimension.
Definition: Coordinate.php:222
static rangeBoundaries($pRange)
Calculate range boundaries.
Definition: Coordinate.php:187
static extractAllCellReferencesInRange($cellRange)
Extract all cell references in range, which may be comprised of multiple cell ranges.
Definition: Coordinate.php:338
static getInstance(Worksheet $parent)
Initialise the cache storage.
static resolveName(string $pDefinedName, Worksheet $pSheet, string $sheetName='')
Resolve a named range to a regular cell range or formula.
static getInstance()
Get an instance of this class.
static calculateColumnWidth(\PhpOffice\PhpSpreadsheet\Style\Font $font, $cellText='', $rotation=0, ?\PhpOffice\PhpSpreadsheet\Style\Font $defaultFont=null)
Calculate an (approximate) OpenXML column width, based on font size and text contained.
Definition: Font.php:227
static hashPassword(string $password, string $algorithm='', string $salt='', int $spinCount=10000)
Create a password hash from a given string by a specific algorithm.
static countCharacters($value, $enc='UTF-8')
Get character count.
static substring($pValue, $pStart, $pLength=0)
Get a substring of a UTF-8 encoded string.
static toFormattedString($value, $format, $callBack=null)
Convert a value in a pre-defined format to a PHP string.
Header/Footer Formatting Syntax taken from Office Open XML Part 4 - Markup Language Reference,...
Paper size taken from Office Open XML Part 4 - Markup Language Reference, page 1988:.
Definition: PageSetup.php:81
$password
Definition: cron.php:14
$key
Definition: croninfo.php:18
$i
Definition: disco.tpl.php:19
$style
Definition: example_012.php:70
$r
Definition: example_031.php:79
$index
Definition: metadata.php:60
$row
hash(StreamInterface $stream, $algo, $rawOutput=false)
Calculate a hash of a Stream.
Definition: functions.php:406
toArray($value)
Wrap the given value in an array if it is no array.