composer package updates
[openemr.git] / vendor / phpoffice / phpspreadsheet / src / PhpSpreadsheet / Worksheet / Worksheet.php
bloba0c8f6af7ea90837c57159991bdc1037bd9e18b3
1 <?php
3 namespace PhpOffice\PhpSpreadsheet\Worksheet;
5 use ArrayObject;
6 use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
7 use PhpOffice\PhpSpreadsheet\Cell\Cell;
8 use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
9 use PhpOffice\PhpSpreadsheet\Cell\DataType;
10 use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
11 use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
12 use PhpOffice\PhpSpreadsheet\Chart\Chart;
13 use PhpOffice\PhpSpreadsheet\Collection\Cells;
14 use PhpOffice\PhpSpreadsheet\Collection\CellsFactory;
15 use PhpOffice\PhpSpreadsheet\Comment;
16 use PhpOffice\PhpSpreadsheet\Exception;
17 use PhpOffice\PhpSpreadsheet\IComparable;
18 use PhpOffice\PhpSpreadsheet\NamedRange;
19 use PhpOffice\PhpSpreadsheet\ReferenceHelper;
20 use PhpOffice\PhpSpreadsheet\RichText\RichText;
21 use PhpOffice\PhpSpreadsheet\Shared;
22 use PhpOffice\PhpSpreadsheet\Spreadsheet;
23 use PhpOffice\PhpSpreadsheet\Style\Color;
24 use PhpOffice\PhpSpreadsheet\Style\Conditional;
25 use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
26 use PhpOffice\PhpSpreadsheet\Style\Style;
28 class Worksheet implements IComparable
30 // Break types
31 const BREAK_NONE = 0;
32 const BREAK_ROW = 1;
33 const BREAK_COLUMN = 2;
35 // Sheet state
36 const SHEETSTATE_VISIBLE = 'visible';
37 const SHEETSTATE_HIDDEN = 'hidden';
38 const SHEETSTATE_VERYHIDDEN = 'veryHidden';
40 /**
41 * Maximum 31 characters allowed for sheet title.
43 * @var int
45 const SHEET_TITLE_MAXIMUM_LENGTH = 31;
47 /**
48 * Invalid characters in sheet title.
50 * @var array
52 private static $invalidCharacters = ['*', ':', '/', '\\', '?', '[', ']'];
54 /**
55 * Parent spreadsheet.
57 * @var Spreadsheet
59 private $parent;
61 /**
62 * Collection of cells.
64 * @var Cells
66 private $cellCollection;
68 /**
69 * Collection of row dimensions.
71 * @var RowDimension[]
73 private $rowDimensions = [];
75 /**
76 * Default row dimension.
78 * @var RowDimension
80 private $defaultRowDimension;
82 /**
83 * Collection of column dimensions.
85 * @var ColumnDimension[]
87 private $columnDimensions = [];
89 /**
90 * Default column dimension.
92 * @var ColumnDimension
94 private $defaultColumnDimension;
96 /**
97 * Collection of drawings.
99 * @var BaseDrawing[]
101 private $drawingCollection;
104 * Collection of Chart objects.
106 * @var Chart[]
108 private $chartCollection = [];
111 * Worksheet title.
113 * @var string
115 private $title;
118 * Sheet state.
120 * @var string
122 private $sheetState;
125 * Page setup.
127 * @var PageSetup
129 private $pageSetup;
132 * Page margins.
134 * @var PageMargins
136 private $pageMargins;
139 * Page header/footer.
141 * @var HeaderFooter
143 private $headerFooter;
146 * Sheet view.
148 * @var SheetView
150 private $sheetView;
153 * Protection.
155 * @var Protection
157 private $protection;
160 * Collection of styles.
162 * @var Style[]
164 private $styles = [];
167 * Conditional styles. Indexed by cell coordinate, e.g. 'A1'.
169 * @var array
171 private $conditionalStylesCollection = [];
174 * Is the current cell collection sorted already?
176 * @var bool
178 private $cellCollectionIsSorted = false;
181 * Collection of breaks.
183 * @var array
185 private $breaks = [];
188 * Collection of merged cell ranges.
190 * @var array
192 private $mergeCells = [];
195 * Collection of protected cell ranges.
197 * @var array
199 private $protectedCells = [];
202 * Autofilter Range and selection.
204 * @var AutoFilter
206 private $autoFilter;
209 * Freeze pane.
211 * @var null|string
213 private $freezePane;
216 * Default position of the right bottom pane.
218 * @var null|string
220 private $topLeftCell;
223 * Show gridlines?
225 * @var bool
227 private $showGridlines = true;
230 * Print gridlines?
232 * @var bool
234 private $printGridlines = false;
237 * Show row and column headers?
239 * @var bool
241 private $showRowColHeaders = true;
244 * Show summary below? (Row/Column outline).
246 * @var bool
248 private $showSummaryBelow = true;
251 * Show summary right? (Row/Column outline).
253 * @var bool
255 private $showSummaryRight = true;
258 * Collection of comments.
260 * @var Comment[]
262 private $comments = [];
265 * Active cell. (Only one!).
267 * @var string
269 private $activeCell = 'A1';
272 * Selected cells.
274 * @var string
276 private $selectedCells = 'A1';
279 * Cached highest column.
281 * @var string
283 private $cachedHighestColumn = 'A';
286 * Cached highest row.
288 * @var int
290 private $cachedHighestRow = 1;
293 * Right-to-left?
295 * @var bool
297 private $rightToLeft = false;
300 * Hyperlinks. Indexed by cell coordinate, e.g. 'A1'.
302 * @var array
304 private $hyperlinkCollection = [];
307 * Data validation objects. Indexed by cell coordinate, e.g. 'A1'.
309 * @var array
311 private $dataValidationCollection = [];
314 * Tab color.
316 * @var Color
318 private $tabColor;
321 * Dirty flag.
323 * @var bool
325 private $dirty = true;
328 * Hash.
330 * @var string
332 private $hash;
335 * CodeName.
337 * @var string
339 private $codeName;
342 * Create a new worksheet.
344 * @param Spreadsheet $parent
345 * @param string $pTitle
347 public function __construct(Spreadsheet $parent = null, $pTitle = 'Worksheet')
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);
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);
379 * Disconnect all cells from this Worksheet object,
380 * typically so that the worksheet object can be unset.
382 public function disconnectCells()
384 if ($this->cellCollection !== null) {
385 $this->cellCollection->unsetWorksheetCells();
386 $this->cellCollection = null;
388 // detach ourself from the workbook, so that it can then delete this worksheet successfully
389 $this->parent = null;
393 * Code to execute when this worksheet is unset().
395 public function __destruct()
397 Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title);
399 $this->disconnectCells();
403 * Return the cell collection.
405 * @return Cells
407 public function getCellCollection()
409 return $this->cellCollection;
413 * Get array of invalid characters for sheet title.
415 * @return array
417 public static function getInvalidCharacters()
419 return self::$invalidCharacters;
423 * Check sheet code name for valid Excel syntax.
425 * @param string $pValue The string to check
427 * @throws Exception
429 * @return string The valid string
431 private static function checkSheetCodeName($pValue)
433 $CharCount = Shared\StringHelper::countCharacters($pValue);
434 if ($CharCount == 0) {
435 throw new Exception('Sheet code name cannot be empty.');
437 // Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'"
438 if ((str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) ||
439 (Shared\StringHelper::substring($pValue, -1, 1) == '\'') ||
440 (Shared\StringHelper::substring($pValue, 0, 1) == '\'')) {
441 throw new Exception('Invalid character found in sheet code name');
444 // Enforce maximum characters allowed for sheet title
445 if ($CharCount > self::SHEET_TITLE_MAXIMUM_LENGTH) {
446 throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.');
449 return $pValue;
453 * Check sheet title for valid Excel syntax.
455 * @param string $pValue The string to check
457 * @throws Exception
459 * @return string The valid string
461 private static function checkSheetTitle($pValue)
463 // Some of the printable ASCII characters are invalid: * : / \ ? [ ]
464 if (str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) {
465 throw new Exception('Invalid character found in sheet title');
468 // Enforce maximum characters allowed for sheet title
469 if (Shared\StringHelper::countCharacters($pValue) > self::SHEET_TITLE_MAXIMUM_LENGTH) {
470 throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.');
473 return $pValue;
477 * Get a sorted list of all cell coordinates currently held in the collection by row and column.
479 * @param bool $sorted Also sort the cell collection?
481 * @return string[]
483 public function getCoordinates($sorted = true)
485 if ($this->cellCollection == null) {
486 return [];
489 if ($sorted) {
490 return $this->cellCollection->getSortedCoordinates();
493 return $this->cellCollection->getCoordinates();
497 * Get collection of row dimensions.
499 * @return RowDimension[]
501 public function getRowDimensions()
503 return $this->rowDimensions;
507 * Get default row dimension.
509 * @return RowDimension
511 public function getDefaultRowDimension()
513 return $this->defaultRowDimension;
517 * Get collection of column dimensions.
519 * @return ColumnDimension[]
521 public function getColumnDimensions()
523 return $this->columnDimensions;
527 * Get default column dimension.
529 * @return ColumnDimension
531 public function getDefaultColumnDimension()
533 return $this->defaultColumnDimension;
537 * Get collection of drawings.
539 * @return BaseDrawing[]
541 public function getDrawingCollection()
543 return $this->drawingCollection;
547 * Get collection of charts.
549 * @return Chart[]
551 public function getChartCollection()
553 return $this->chartCollection;
557 * Add chart.
559 * @param Chart $pChart
560 * @param null|int $iChartIndex Index where chart should go (0,1,..., or null for last)
562 * @return Chart
564 public function addChart(Chart $pChart, $iChartIndex = null)
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]);
574 return $pChart;
578 * Return the count of charts on this worksheet.
580 * @return int The number of charts
582 public function getChartCount()
584 return count($this->chartCollection);
588 * Get a chart by its index position.
590 * @param string $index Chart index position
592 * @return Chart|false
594 public function getChartByIndex($index)
596 $chartCount = count($this->chartCollection);
597 if ($chartCount == 0) {
598 return false;
600 if ($index === null) {
601 $index = --$chartCount;
603 if (!isset($this->chartCollection[$index])) {
604 return false;
607 return $this->chartCollection[$index];
611 * Return an array of the names of charts on this worksheet.
613 * @return string[] The names of charts
615 public function getChartNames()
617 $chartNames = [];
618 foreach ($this->chartCollection as $chart) {
619 $chartNames[] = $chart->getName();
622 return $chartNames;
626 * Get a chart by name.
628 * @param string $chartName Chart name
630 * @return Chart|false
632 public function getChartByName($chartName)
634 $chartCount = count($this->chartCollection);
635 if ($chartCount == 0) {
636 return false;
638 foreach ($this->chartCollection as $index => $chart) {
639 if ($chart->getName() == $chartName) {
640 return $this->chartCollection[$index];
644 return false;
648 * Refresh column dimensions.
650 * @return Worksheet
652 public function refreshColumnDimensions()
654 $currentColumnDimensions = $this->getColumnDimensions();
655 $newColumnDimensions = [];
657 foreach ($currentColumnDimensions as $objColumnDimension) {
658 $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension;
661 $this->columnDimensions = $newColumnDimensions;
663 return $this;
667 * Refresh row dimensions.
669 * @return Worksheet
671 public function refreshRowDimensions()
673 $currentRowDimensions = $this->getRowDimensions();
674 $newRowDimensions = [];
676 foreach ($currentRowDimensions as $objRowDimension) {
677 $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension;
680 $this->rowDimensions = $newRowDimensions;
682 return $this;
686 * Calculate worksheet dimension.
688 * @return string String containing the dimension of this worksheet
690 public function calculateWorksheetDimension()
692 // Return
693 return 'A1' . ':' . $this->getHighestColumn() . $this->getHighestRow();
697 * Calculate worksheet data dimension.
699 * @return string String containing the dimension of this worksheet that actually contain data
701 public function calculateWorksheetDataDimension()
703 // Return
704 return 'A1' . ':' . $this->getHighestDataColumn() . $this->getHighestDataRow();
708 * Calculate widths for auto-size columns.
710 * @return Worksheet;
712 public function calculateColumnWidths()
714 // initialize $autoSizes array
715 $autoSizes = [];
716 foreach ($this->getColumnDimensions() as $colDimension) {
717 if ($colDimension->getAutoSize()) {
718 $autoSizes[$colDimension->getColumnIndex()] = -1;
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;
732 // loop through all cells in the worksheet
733 foreach ($this->getCoordinates(false) as $coordinate) {
734 $cell = $this->getCell($coordinate, false);
735 if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) {
736 //Determine if cell is in merge range
737 $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]);
739 //By default merged cells should be ignored
740 $isMergedButProceed = false;
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;
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
755 $cellValue = NumberFormat::toFormattedString(
756 $cell->getCalculatedValue(),
757 $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode()
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()
773 // adjust column widths
774 foreach ($autoSizes as $columnIndex => $width) {
775 if ($width == -1) {
776 $width = $this->getDefaultColumnDimension()->getWidth();
778 $this->getColumnDimension($columnIndex)->setWidth($width);
782 return $this;
786 * Get parent.
788 * @return Spreadsheet
790 public function getParent()
792 return $this->parent;
796 * Re-bind parent.
798 * @param Spreadsheet $parent
800 * @return Worksheet
802 public function rebindParent(Spreadsheet $parent)
804 if ($this->parent !== null) {
805 $namedRanges = $this->parent->getNamedRanges();
806 foreach ($namedRanges as $namedRange) {
807 $parent->addNamedRange($namedRange);
810 $this->parent->removeSheetByIndex(
811 $this->parent->getIndex($this)
814 $this->parent = $parent;
816 return $this;
820 * Get title.
822 * @return string
824 public function getTitle()
826 return $this->title;
830 * Set title.
832 * @param string $pValue String containing the dimension of this worksheet
833 * @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should
834 * be updated to reflect the new sheet name.
835 * This should be left as the default true, unless you are
836 * certain that no formula cells on any worksheet contain
837 * references to this worksheet
838 * @param bool $validate False to skip validation of new title. WARNING: This should only be set
839 * at parse time (by Readers), where titles can be assumed to be valid.
841 * @return Worksheet
843 public function setTitle($pValue, $updateFormulaCellReferences = true, $validate = true)
845 // Is this a 'rename' or not?
846 if ($this->getTitle() == $pValue) {
847 return $this;
850 // Old title
851 $oldTitle = $this->getTitle();
853 if ($validate) {
854 // Syntax check
855 self::checkSheetTitle($pValue);
857 if ($this->parent) {
858 // Is there already such sheet name?
859 if ($this->parent->sheetNameExists($pValue)) {
860 // Use name, but append with lowest possible integer
862 if (Shared\StringHelper::countCharacters($pValue) > 29) {
863 $pValue = Shared\StringHelper::substring($pValue, 0, 29);
865 $i = 1;
866 while ($this->parent->sheetNameExists($pValue . ' ' . $i)) {
867 ++$i;
868 if ($i == 10) {
869 if (Shared\StringHelper::countCharacters($pValue) > 28) {
870 $pValue = Shared\StringHelper::substring($pValue, 0, 28);
872 } elseif ($i == 100) {
873 if (Shared\StringHelper::countCharacters($pValue) > 27) {
874 $pValue = Shared\StringHelper::substring($pValue, 0, 27);
879 $pValue .= " $i";
884 // Set title
885 $this->title = $pValue;
886 $this->dirty = true;
888 if ($this->parent && $this->parent->getCalculationEngine()) {
889 // New title
890 $newTitle = $this->getTitle();
891 $this->parent->getCalculationEngine()
892 ->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
893 if ($updateFormulaCellReferences) {
894 ReferenceHelper::getInstance()->updateNamedFormulas($this->parent, $oldTitle, $newTitle);
898 return $this;
902 * Get sheet state.
904 * @return string Sheet state (visible, hidden, veryHidden)
906 public function getSheetState()
908 return $this->sheetState;
912 * Set sheet state.
914 * @param string $value Sheet state (visible, hidden, veryHidden)
916 * @return Worksheet
918 public function setSheetState($value)
920 $this->sheetState = $value;
922 return $this;
926 * Get page setup.
928 * @return PageSetup
930 public function getPageSetup()
932 return $this->pageSetup;
936 * Set page setup.
938 * @param PageSetup $pValue
940 * @return Worksheet
942 public function setPageSetup(PageSetup $pValue)
944 $this->pageSetup = $pValue;
946 return $this;
950 * Get page margins.
952 * @return PageMargins
954 public function getPageMargins()
956 return $this->pageMargins;
960 * Set page margins.
962 * @param PageMargins $pValue
964 * @return Worksheet
966 public function setPageMargins(PageMargins $pValue)
968 $this->pageMargins = $pValue;
970 return $this;
974 * Get page header/footer.
976 * @return HeaderFooter
978 public function getHeaderFooter()
980 return $this->headerFooter;
984 * Set page header/footer.
986 * @param HeaderFooter $pValue
988 * @return Worksheet
990 public function setHeaderFooter(HeaderFooter $pValue)
992 $this->headerFooter = $pValue;
994 return $this;
998 * Get sheet view.
1000 * @return SheetView
1002 public function getSheetView()
1004 return $this->sheetView;
1008 * Set sheet view.
1010 * @param SheetView $pValue
1012 * @return Worksheet
1014 public function setSheetView(SheetView $pValue)
1016 $this->sheetView = $pValue;
1018 return $this;
1022 * Get Protection.
1024 * @return Protection
1026 public function getProtection()
1028 return $this->protection;
1032 * Set Protection.
1034 * @param Protection $pValue
1036 * @return Worksheet
1038 public function setProtection(Protection $pValue)
1040 $this->protection = $pValue;
1041 $this->dirty = true;
1043 return $this;
1047 * Get highest worksheet column.
1049 * @param string $row Return the data highest column for the specified row,
1050 * or the highest column of any row if no row number is passed
1052 * @return string Highest column name
1054 public function getHighestColumn($row = null)
1056 if ($row == null) {
1057 return $this->cachedHighestColumn;
1060 return $this->getHighestDataColumn($row);
1064 * Get highest worksheet column that contains data.
1066 * @param string $row Return the highest data column for the specified row,
1067 * or the highest data column of any row if no row number is passed
1069 * @return string Highest column name that contains data
1071 public function getHighestDataColumn($row = null)
1073 return $this->cellCollection->getHighestColumn($row);
1077 * Get highest worksheet row.
1079 * @param string $column Return the highest data row for the specified column,
1080 * or the highest row of any column if no column letter is passed
1082 * @return int Highest row number
1084 public function getHighestRow($column = null)
1086 if ($column == null) {
1087 return $this->cachedHighestRow;
1090 return $this->getHighestDataRow($column);
1094 * Get highest worksheet row that contains data.
1096 * @param string $column Return the highest data row for the specified column,
1097 * or the highest data row of any column if no column letter is passed
1099 * @return string Highest row number that contains data
1101 public function getHighestDataRow($column = null)
1103 return $this->cellCollection->getHighestRow($column);
1107 * Get highest worksheet column and highest row that have cell records.
1109 * @return array Highest column name and highest row number
1111 public function getHighestRowAndColumn()
1113 return $this->cellCollection->getHighestRowAndColumn();
1117 * Set a cell value.
1119 * @param string $pCoordinate Coordinate of the cell, eg: 'A1'
1120 * @param mixed $pValue Value of the cell
1122 * @return Worksheet
1124 public function setCellValue($pCoordinate, $pValue)
1126 $this->getCell($pCoordinate)->setValue($pValue);
1128 return $this;
1132 * Set a cell value by using numeric cell coordinates.
1134 * @param int $columnIndex Numeric column coordinate of the cell
1135 * @param int $row Numeric row coordinate of the cell
1136 * @param mixed $value Value of the cell
1138 * @return Worksheet
1140 public function setCellValueByColumnAndRow($columnIndex, $row, $value)
1142 $this->getCellByColumnAndRow($columnIndex, $row)->setValue($value);
1144 return $this;
1148 * Set a cell value.
1150 * @param string $pCoordinate Coordinate of the cell, eg: 'A1'
1151 * @param mixed $pValue Value of the cell
1152 * @param string $pDataType Explicit data type, see DataType::TYPE_*
1154 * @return Worksheet
1156 public function setCellValueExplicit($pCoordinate, $pValue, $pDataType)
1158 // Set value
1159 $this->getCell($pCoordinate)->setValueExplicit($pValue, $pDataType);
1161 return $this;
1165 * Set a cell value by using numeric cell coordinates.
1167 * @param int $columnIndex Numeric column coordinate of the cell
1168 * @param int $row Numeric row coordinate of the cell
1169 * @param mixed $value Value of the cell
1170 * @param string $dataType Explicit data type, see DataType::TYPE_*
1172 * @return Worksheet
1174 public function setCellValueExplicitByColumnAndRow($columnIndex, $row, $value, $dataType)
1176 $this->getCellByColumnAndRow($columnIndex, $row)->setValueExplicit($value, $dataType);
1178 return $this;
1182 * Get cell at a specific coordinate.
1184 * @param string $pCoordinate Coordinate of the cell, eg: 'A1'
1185 * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't
1186 * already exist, or a null should be returned instead
1188 * @throws Exception
1190 * @return null|Cell Cell that was found/created or null
1192 public function getCell($pCoordinate, $createIfNotExists = true)
1194 // Check cell collection
1195 if ($this->cellCollection->has(strtoupper($pCoordinate))) {
1196 return $this->cellCollection->get($pCoordinate);
1199 // Worksheet reference?
1200 if (strpos($pCoordinate, '!') !== false) {
1201 $worksheetReference = self::extractSheetTitle($pCoordinate, true);
1203 return $this->parent->getSheetByName($worksheetReference[0])->getCell(strtoupper($worksheetReference[1]), $createIfNotExists);
1206 // Named range?
1207 if ((!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) &&
1208 (preg_match('/^' . Calculation::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $pCoordinate, $matches))) {
1209 $namedRange = NamedRange::resolveRange($pCoordinate, $this);
1210 if ($namedRange !== null) {
1211 $pCoordinate = $namedRange->getRange();
1213 return $namedRange->getWorksheet()->getCell($pCoordinate, $createIfNotExists);
1217 // Uppercase coordinate
1218 $pCoordinate = strtoupper($pCoordinate);
1220 if (Coordinate::coordinateIsRange($pCoordinate)) {
1221 throw new Exception('Cell coordinate can not be a range of cells.');
1222 } elseif (strpos($pCoordinate, '$') !== false) {
1223 throw new Exception('Cell coordinate must not be absolute.');
1226 // Create new cell object, if required
1227 return $createIfNotExists ? $this->createNewCell($pCoordinate) : null;
1231 * Get cell at a specific coordinate by using numeric cell coordinates.
1233 * @param int $columnIndex Numeric column coordinate of the cell
1234 * @param int $row Numeric row coordinate of the cell
1235 * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't
1236 * already exist, or a null should be returned instead
1238 * @return null|Cell Cell that was found/created or null
1240 public function getCellByColumnAndRow($columnIndex, $row, $createIfNotExists = true)
1242 $columnLetter = Coordinate::stringFromColumnIndex($columnIndex);
1243 $coordinate = $columnLetter . $row;
1245 if ($this->cellCollection->has($coordinate)) {
1246 return $this->cellCollection->get($coordinate);
1249 // Create new cell object, if required
1250 return $createIfNotExists ? $this->createNewCell($coordinate) : null;
1254 * Create a new cell at the specified coordinate.
1256 * @param string $pCoordinate Coordinate of the cell
1258 * @return Cell Cell that was created
1260 private function createNewCell($pCoordinate)
1262 $cell = new Cell(null, DataType::TYPE_NULL, $this);
1263 $this->cellCollection->add($pCoordinate, $cell);
1264 $this->cellCollectionIsSorted = false;
1266 // Coordinates
1267 $aCoordinates = Coordinate::coordinateFromString($pCoordinate);
1268 if (Coordinate::columnIndexFromString($this->cachedHighestColumn) < Coordinate::columnIndexFromString($aCoordinates[0])) {
1269 $this->cachedHighestColumn = $aCoordinates[0];
1271 $this->cachedHighestRow = max($this->cachedHighestRow, $aCoordinates[1]);
1273 // Cell needs appropriate xfIndex from dimensions records
1274 // but don't create dimension records if they don't already exist
1275 $rowDimension = $this->getRowDimension($aCoordinates[1], false);
1276 $columnDimension = $this->getColumnDimension($aCoordinates[0], false);
1278 if ($rowDimension !== null && $rowDimension->getXfIndex() > 0) {
1279 // then there is a row dimension with explicit style, assign it to the cell
1280 $cell->setXfIndex($rowDimension->getXfIndex());
1281 } elseif ($columnDimension !== null && $columnDimension->getXfIndex() > 0) {
1282 // then there is a column dimension, assign it to the cell
1283 $cell->setXfIndex($columnDimension->getXfIndex());
1286 return $cell;
1290 * Does the cell at a specific coordinate exist?
1292 * @param string $pCoordinate Coordinate of the cell eg: 'A1'
1294 * @throws Exception
1296 * @return bool
1298 public function cellExists($pCoordinate)
1300 // Worksheet reference?
1301 if (strpos($pCoordinate, '!') !== false) {
1302 $worksheetReference = self::extractSheetTitle($pCoordinate, true);
1304 return $this->parent->getSheetByName($worksheetReference[0])->cellExists(strtoupper($worksheetReference[1]));
1307 // Named range?
1308 if ((!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) &&
1309 (preg_match('/^' . Calculation::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $pCoordinate, $matches))) {
1310 $namedRange = NamedRange::resolveRange($pCoordinate, $this);
1311 if ($namedRange !== null) {
1312 $pCoordinate = $namedRange->getRange();
1313 if ($this->getHashCode() != $namedRange->getWorksheet()->getHashCode()) {
1314 if (!$namedRange->getLocalOnly()) {
1315 return $namedRange->getWorksheet()->cellExists($pCoordinate);
1318 throw new Exception('Named range ' . $namedRange->getName() . ' is not accessible from within sheet ' . $this->getTitle());
1320 } else {
1321 return false;
1325 // Uppercase coordinate
1326 $pCoordinate = strtoupper($pCoordinate);
1328 if (Coordinate::coordinateIsRange($pCoordinate)) {
1329 throw new Exception('Cell coordinate can not be a range of cells.');
1330 } elseif (strpos($pCoordinate, '$') !== false) {
1331 throw new Exception('Cell coordinate must not be absolute.');
1334 // Cell exists?
1335 return $this->cellCollection->has($pCoordinate);
1339 * Cell at a specific coordinate by using numeric cell coordinates exists?
1341 * @param int $columnIndex Numeric column coordinate of the cell
1342 * @param int $row Numeric row coordinate of the cell
1344 * @return bool
1346 public function cellExistsByColumnAndRow($columnIndex, $row)
1348 return $this->cellExists(Coordinate::stringFromColumnIndex($columnIndex) . $row);
1352 * Get row dimension at a specific row.
1354 * @param int $pRow Numeric index of the row
1355 * @param bool $create
1357 * @return RowDimension
1359 public function getRowDimension($pRow, $create = true)
1361 // Found
1362 $found = null;
1364 // Get row dimension
1365 if (!isset($this->rowDimensions[$pRow])) {
1366 if (!$create) {
1367 return null;
1369 $this->rowDimensions[$pRow] = new RowDimension($pRow);
1371 $this->cachedHighestRow = max($this->cachedHighestRow, $pRow);
1374 return $this->rowDimensions[$pRow];
1378 * Get column dimension at a specific column.
1380 * @param string $pColumn String index of the column eg: 'A'
1381 * @param bool $create
1383 * @return ColumnDimension
1385 public function getColumnDimension($pColumn, $create = true)
1387 // Uppercase coordinate
1388 $pColumn = strtoupper($pColumn);
1390 // Fetch dimensions
1391 if (!isset($this->columnDimensions[$pColumn])) {
1392 if (!$create) {
1393 return null;
1395 $this->columnDimensions[$pColumn] = new ColumnDimension($pColumn);
1397 if (Coordinate::columnIndexFromString($this->cachedHighestColumn) < Coordinate::columnIndexFromString($pColumn)) {
1398 $this->cachedHighestColumn = $pColumn;
1402 return $this->columnDimensions[$pColumn];
1406 * Get column dimension at a specific column by using numeric cell coordinates.
1408 * @param int $columnIndex Numeric column coordinate of the cell
1410 * @return ColumnDimension
1412 public function getColumnDimensionByColumn($columnIndex)
1414 return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex));
1418 * Get styles.
1420 * @return Style[]
1422 public function getStyles()
1424 return $this->styles;
1428 * Get style for cell.
1430 * @param string $pCellCoordinate Cell coordinate (or range) to get style for, eg: 'A1'
1432 * @throws Exception
1434 * @return Style
1436 public function getStyle($pCellCoordinate)
1438 // set this sheet as active
1439 $this->parent->setActiveSheetIndex($this->parent->getIndex($this));
1441 // set cell coordinate as active
1442 $this->setSelectedCells(strtoupper($pCellCoordinate));
1444 return $this->parent->getCellXfSupervisor();
1448 * Get conditional styles for a cell.
1450 * @param string $pCoordinate eg: 'A1'
1452 * @return Conditional[]
1454 public function getConditionalStyles($pCoordinate)
1456 $pCoordinate = strtoupper($pCoordinate);
1457 if (!isset($this->conditionalStylesCollection[$pCoordinate])) {
1458 $this->conditionalStylesCollection[$pCoordinate] = [];
1461 return $this->conditionalStylesCollection[$pCoordinate];
1465 * Do conditional styles exist for this cell?
1467 * @param string $pCoordinate eg: 'A1'
1469 * @return bool
1471 public function conditionalStylesExists($pCoordinate)
1473 return isset($this->conditionalStylesCollection[strtoupper($pCoordinate)]);
1477 * Removes conditional styles for a cell.
1479 * @param string $pCoordinate eg: 'A1'
1481 * @return Worksheet
1483 public function removeConditionalStyles($pCoordinate)
1485 unset($this->conditionalStylesCollection[strtoupper($pCoordinate)]);
1487 return $this;
1491 * Get collection of conditional styles.
1493 * @return array
1495 public function getConditionalStylesCollection()
1497 return $this->conditionalStylesCollection;
1501 * Set conditional styles.
1503 * @param string $pCoordinate eg: 'A1'
1504 * @param $pValue Conditional[]
1506 * @return Worksheet
1508 public function setConditionalStyles($pCoordinate, $pValue)
1510 $this->conditionalStylesCollection[strtoupper($pCoordinate)] = $pValue;
1512 return $this;
1516 * Get style for cell by using numeric cell coordinates.
1518 * @param int $columnIndex1 Numeric column coordinate of the cell
1519 * @param int $row1 Numeric row coordinate of the cell
1520 * @param null|int $columnIndex2 Numeric column coordinate of the range cell
1521 * @param null|int $row2 Numeric row coordinate of the range cell
1523 * @return Style
1525 public function getStyleByColumnAndRow($columnIndex1, $row1, $columnIndex2 = null, $row2 = null)
1527 if ($columnIndex2 !== null && $row2 !== null) {
1528 $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
1530 return $this->getStyle($cellRange);
1533 return $this->getStyle(Coordinate::stringFromColumnIndex($columnIndex1) . $row1);
1537 * Duplicate cell style to a range of cells.
1539 * Please note that this will overwrite existing cell styles for cells in range!
1541 * @param Style $pCellStyle Cell style to duplicate
1542 * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
1544 * @throws Exception
1546 * @return Worksheet
1548 public function duplicateStyle(Style $pCellStyle, $pRange)
1550 // Add the style to the workbook if necessary
1551 $workbook = $this->parent;
1552 if ($existingStyle = $this->parent->getCellXfByHashCode($pCellStyle->getHashCode())) {
1553 // there is already such cell Xf in our collection
1554 $xfIndex = $existingStyle->getIndex();
1555 } else {
1556 // we don't have such a cell Xf, need to add
1557 $workbook->addCellXf($pCellStyle);
1558 $xfIndex = $pCellStyle->getIndex();
1561 // Calculate range outer borders
1562 list($rangeStart, $rangeEnd) = Coordinate::rangeBoundaries($pRange . ':' . $pRange);
1564 // Make sure we can loop upwards on rows and columns
1565 if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
1566 $tmp = $rangeStart;
1567 $rangeStart = $rangeEnd;
1568 $rangeEnd = $tmp;
1571 // Loop through cells and apply styles
1572 for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
1573 for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
1574 $this->getCell(Coordinate::stringFromColumnIndex($col) . $row)->setXfIndex($xfIndex);
1578 return $this;
1582 * Duplicate conditional style to a range of cells.
1584 * Please note that this will overwrite existing cell styles for cells in range!
1586 * @param Conditional[] $pCellStyle Cell style to duplicate
1587 * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
1589 * @throws Exception
1591 * @return Worksheet
1593 public function duplicateConditionalStyle(array $pCellStyle, $pRange = '')
1595 foreach ($pCellStyle as $cellStyle) {
1596 if (!($cellStyle instanceof Conditional)) {
1597 throw new Exception('Style is not a conditional style');
1601 // Calculate range outer borders
1602 list($rangeStart, $rangeEnd) = Coordinate::rangeBoundaries($pRange . ':' . $pRange);
1604 // Make sure we can loop upwards on rows and columns
1605 if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
1606 $tmp = $rangeStart;
1607 $rangeStart = $rangeEnd;
1608 $rangeEnd = $tmp;
1611 // Loop through cells and apply styles
1612 for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
1613 for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
1614 $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $pCellStyle);
1618 return $this;
1622 * Set break on a cell.
1624 * @param string $pCoordinate Cell coordinate (e.g. A1)
1625 * @param int $pBreak Break type (type of Worksheet::BREAK_*)
1627 * @throws Exception
1629 * @return Worksheet
1631 public function setBreak($pCoordinate, $pBreak)
1633 // Uppercase coordinate
1634 $pCoordinate = strtoupper($pCoordinate);
1636 if ($pCoordinate != '') {
1637 if ($pBreak == self::BREAK_NONE) {
1638 if (isset($this->breaks[$pCoordinate])) {
1639 unset($this->breaks[$pCoordinate]);
1641 } else {
1642 $this->breaks[$pCoordinate] = $pBreak;
1644 } else {
1645 throw new Exception('No cell coordinate specified.');
1648 return $this;
1652 * Set break on a cell by using numeric cell coordinates.
1654 * @param int $columnIndex Numeric column coordinate of the cell
1655 * @param int $row Numeric row coordinate of the cell
1656 * @param int $break Break type (type of Worksheet::BREAK_*)
1658 * @return Worksheet
1660 public function setBreakByColumnAndRow($columnIndex, $row, $break)
1662 return $this->setBreak(Coordinate::stringFromColumnIndex($columnIndex) . $row, $break);
1666 * Get breaks.
1668 * @return array[]
1670 public function getBreaks()
1672 return $this->breaks;
1676 * Set merge on a cell range.
1678 * @param string $pRange Cell range (e.g. A1:E1)
1680 * @throws Exception
1682 * @return Worksheet
1684 public function mergeCells($pRange)
1686 // Uppercase coordinate
1687 $pRange = strtoupper($pRange);
1689 if (strpos($pRange, ':') !== false) {
1690 $this->mergeCells[$pRange] = $pRange;
1692 // make sure cells are created
1694 // get the cells in the range
1695 $aReferences = Coordinate::extractAllCellReferencesInRange($pRange);
1697 // create upper left cell if it does not already exist
1698 $upperLeft = $aReferences[0];
1699 if (!$this->cellExists($upperLeft)) {
1700 $this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL);
1703 // Blank out the rest of the cells in the range (if they exist)
1704 $count = count($aReferences);
1705 for ($i = 1; $i < $count; ++$i) {
1706 if ($this->cellExists($aReferences[$i])) {
1707 $this->getCell($aReferences[$i])->setValueExplicit(null, DataType::TYPE_NULL);
1710 } else {
1711 throw new Exception('Merge must be set on a range of cells.');
1714 return $this;
1718 * Set merge on a cell range by using numeric cell coordinates.
1720 * @param int $columnIndex1 Numeric column coordinate of the first cell
1721 * @param int $row1 Numeric row coordinate of the first cell
1722 * @param int $columnIndex2 Numeric column coordinate of the last cell
1723 * @param int $row2 Numeric row coordinate of the last cell
1725 * @throws Exception
1727 * @return Worksheet
1729 public function mergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
1731 $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
1733 return $this->mergeCells($cellRange);
1737 * Remove merge on a cell range.
1739 * @param string $pRange Cell range (e.g. A1:E1)
1741 * @throws Exception
1743 * @return Worksheet
1745 public function unmergeCells($pRange)
1747 // Uppercase coordinate
1748 $pRange = strtoupper($pRange);
1750 if (strpos($pRange, ':') !== false) {
1751 if (isset($this->mergeCells[$pRange])) {
1752 unset($this->mergeCells[$pRange]);
1753 } else {
1754 throw new Exception('Cell range ' . $pRange . ' not known as merged.');
1756 } else {
1757 throw new Exception('Merge can only be removed from a range of cells.');
1760 return $this;
1764 * Remove merge on a cell range by using numeric cell coordinates.
1766 * @param int $columnIndex1 Numeric column coordinate of the first cell
1767 * @param int $row1 Numeric row coordinate of the first cell
1768 * @param int $columnIndex2 Numeric column coordinate of the last cell
1769 * @param int $row2 Numeric row coordinate of the last cell
1771 * @throws Exception
1773 * @return Worksheet
1775 public function unmergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
1777 $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
1779 return $this->unmergeCells($cellRange);
1783 * Get merge cells array.
1785 * @return array[]
1787 public function getMergeCells()
1789 return $this->mergeCells;
1793 * Set merge cells array for the entire sheet. Use instead mergeCells() to merge
1794 * a single cell range.
1796 * @param array $pValue
1798 * @return Worksheet
1800 public function setMergeCells(array $pValue)
1802 $this->mergeCells = $pValue;
1804 return $this;
1808 * Set protection on a cell range.
1810 * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1)
1811 * @param string $pPassword Password to unlock the protection
1812 * @param bool $pAlreadyHashed If the password has already been hashed, set this to true
1814 * @return Worksheet
1816 public function protectCells($pRange, $pPassword, $pAlreadyHashed = false)
1818 // Uppercase coordinate
1819 $pRange = strtoupper($pRange);
1821 if (!$pAlreadyHashed) {
1822 $pPassword = Shared\PasswordHasher::hashPassword($pPassword);
1824 $this->protectedCells[$pRange] = $pPassword;
1826 return $this;
1830 * Set protection on a cell range by using numeric cell coordinates.
1832 * @param int $columnIndex1 Numeric column coordinate of the first cell
1833 * @param int $row1 Numeric row coordinate of the first cell
1834 * @param int $columnIndex2 Numeric column coordinate of the last cell
1835 * @param int $row2 Numeric row coordinate of the last cell
1836 * @param string $password Password to unlock the protection
1837 * @param bool $alreadyHashed If the password has already been hashed, set this to true
1839 * @return Worksheet
1841 public function protectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2, $password, $alreadyHashed = false)
1843 $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
1845 return $this->protectCells($cellRange, $password, $alreadyHashed);
1849 * Remove protection on a cell range.
1851 * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1)
1853 * @throws Exception
1855 * @return Worksheet
1857 public function unprotectCells($pRange)
1859 // Uppercase coordinate
1860 $pRange = strtoupper($pRange);
1862 if (isset($this->protectedCells[$pRange])) {
1863 unset($this->protectedCells[$pRange]);
1864 } else {
1865 throw new Exception('Cell range ' . $pRange . ' not known as protected.');
1868 return $this;
1872 * Remove protection on a cell range by using numeric cell coordinates.
1874 * @param int $columnIndex1 Numeric column coordinate of the first cell
1875 * @param int $row1 Numeric row coordinate of the first cell
1876 * @param int $columnIndex2 Numeric column coordinate of the last cell
1877 * @param int $row2 Numeric row coordinate of the last cell
1879 * @throws Exception
1881 * @return Worksheet
1883 public function unprotectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
1885 $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
1887 return $this->unprotectCells($cellRange);
1891 * Get protected cells.
1893 * @return array[]
1895 public function getProtectedCells()
1897 return $this->protectedCells;
1901 * Get Autofilter.
1903 * @return AutoFilter
1905 public function getAutoFilter()
1907 return $this->autoFilter;
1911 * Set AutoFilter.
1913 * @param AutoFilter|string $pValue
1914 * A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility
1916 * @throws Exception
1918 * @return Worksheet
1920 public function setAutoFilter($pValue)
1922 if (is_string($pValue)) {
1923 $this->autoFilter->setRange($pValue);
1924 } elseif (is_object($pValue) && ($pValue instanceof AutoFilter)) {
1925 $this->autoFilter = $pValue;
1928 return $this;
1932 * Set Autofilter Range by using numeric cell coordinates.
1934 * @param int $columnIndex1 Numeric column coordinate of the first cell
1935 * @param int $row1 Numeric row coordinate of the first cell
1936 * @param int $columnIndex2 Numeric column coordinate of the second cell
1937 * @param int $row2 Numeric row coordinate of the second cell
1939 * @throws Exception
1941 * @return Worksheet
1943 public function setAutoFilterByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
1945 return $this->setAutoFilter(
1946 Coordinate::stringFromColumnIndex($columnIndex1) . $row1
1947 . ':' .
1948 Coordinate::stringFromColumnIndex($columnIndex2) . $row2
1953 * Remove autofilter.
1955 * @return Worksheet
1957 public function removeAutoFilter()
1959 $this->autoFilter->setRange(null);
1961 return $this;
1965 * Get Freeze Pane.
1967 * @return string
1969 public function getFreezePane()
1971 return $this->freezePane;
1975 * Freeze Pane.
1977 * Examples:
1979 * - A2 will freeze the rows above cell A2 (i.e row 1)
1980 * - B1 will freeze the columns to the left of cell B1 (i.e column A)
1981 * - B2 will freeze the rows above and to the left of cell B2 (i.e row 1 and column A)
1983 * @param null|string $cell Position of the split
1984 * @param null|string $topLeftCell default position of the right bottom pane
1986 * @throws Exception
1988 * @return Worksheet
1990 public function freezePane($cell, $topLeftCell = null)
1992 if (is_string($cell) && Coordinate::coordinateIsRange($cell)) {
1993 throw new Exception('Freeze pane can not be set on a range of cells.');
1996 if ($cell !== null && $topLeftCell === null) {
1997 $coordinate = Coordinate::coordinateFromString($cell);
1998 $topLeftCell = $coordinate[0] . $coordinate[1];
2001 $this->freezePane = $cell;
2002 $this->topLeftCell = $topLeftCell;
2004 return $this;
2008 * Freeze Pane by using numeric cell coordinates.
2010 * @param int $columnIndex Numeric column coordinate of the cell
2011 * @param int $row Numeric row coordinate of the cell
2013 * @return Worksheet
2015 public function freezePaneByColumnAndRow($columnIndex, $row)
2017 return $this->freezePane(Coordinate::stringFromColumnIndex($columnIndex) . $row);
2021 * Unfreeze Pane.
2023 * @return Worksheet
2025 public function unfreezePane()
2027 return $this->freezePane(null);
2031 * Get the default position of the right bottom pane.
2033 * @return int
2035 public function getTopLeftCell()
2037 return $this->topLeftCell;
2041 * Insert a new row, updating all possible related data.
2043 * @param int $pBefore Insert before this one
2044 * @param int $pNumRows Number of rows to insert
2046 * @throws Exception
2048 * @return Worksheet
2050 public function insertNewRowBefore($pBefore, $pNumRows = 1)
2052 if ($pBefore >= 1) {
2053 $objReferenceHelper = ReferenceHelper::getInstance();
2054 $objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this);
2055 } else {
2056 throw new Exception('Rows can only be inserted before at least row 1.');
2059 return $this;
2063 * Insert a new column, updating all possible related data.
2065 * @param int $pBefore Insert before this one, eg: 'A'
2066 * @param int $pNumCols Number of columns to insert
2068 * @throws Exception
2070 * @return Worksheet
2072 public function insertNewColumnBefore($pBefore, $pNumCols = 1)
2074 if (!is_numeric($pBefore)) {
2075 $objReferenceHelper = ReferenceHelper::getInstance();
2076 $objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this);
2077 } else {
2078 throw new Exception('Column references should not be numeric.');
2081 return $this;
2085 * Insert a new column, updating all possible related data.
2087 * @param int $beforeColumnIndex Insert before this one (numeric column coordinate of the cell)
2088 * @param int $pNumCols Number of columns to insert
2090 * @throws Exception
2092 * @return Worksheet
2094 public function insertNewColumnBeforeByIndex($beforeColumnIndex, $pNumCols = 1)
2096 if ($beforeColumnIndex >= 1) {
2097 return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $pNumCols);
2100 throw new Exception('Columns can only be inserted before at least column A (1).');
2104 * Delete a row, updating all possible related data.
2106 * @param int $pRow Remove starting with this one
2107 * @param int $pNumRows Number of rows to remove
2109 * @throws Exception
2111 * @return Worksheet
2113 public function removeRow($pRow, $pNumRows = 1)
2115 if ($pRow >= 1) {
2116 $highestRow = $this->getHighestDataRow();
2117 $objReferenceHelper = ReferenceHelper::getInstance();
2118 $objReferenceHelper->insertNewBefore('A' . ($pRow + $pNumRows), 0, -$pNumRows, $this);
2119 for ($r = 0; $r < $pNumRows; ++$r) {
2120 $this->getCellCollection()->removeRow($highestRow);
2121 --$highestRow;
2123 } else {
2124 throw new Exception('Rows to be deleted should at least start from row 1.');
2127 return $this;
2131 * Remove a column, updating all possible related data.
2133 * @param string $pColumn Remove starting with this one, eg: 'A'
2134 * @param int $pNumCols Number of columns to remove
2136 * @throws Exception
2138 * @return Worksheet
2140 public function removeColumn($pColumn, $pNumCols = 1)
2142 if (!is_numeric($pColumn)) {
2143 $highestColumn = $this->getHighestDataColumn();
2144 $pColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($pColumn) + $pNumCols);
2145 $objReferenceHelper = ReferenceHelper::getInstance();
2146 $objReferenceHelper->insertNewBefore($pColumn . '1', -$pNumCols, 0, $this);
2147 for ($c = 0; $c < $pNumCols; ++$c) {
2148 $this->getCellCollection()->removeColumn($highestColumn);
2149 $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1);
2151 } else {
2152 throw new Exception('Column references should not be numeric.');
2155 return $this;
2159 * Remove a column, updating all possible related data.
2161 * @param int $columnIndex Remove starting with this one (numeric column coordinate of the cell)
2162 * @param int $numColumns Number of columns to remove
2164 * @throws Exception
2166 * @return Worksheet
2168 public function removeColumnByIndex($columnIndex, $numColumns = 1)
2170 if ($columnIndex >= 1) {
2171 return $this->removeColumn(Coordinate::stringFromColumnIndex($columnIndex), $numColumns);
2174 throw new Exception('Columns to be deleted should at least start from column A (1)');
2178 * Show gridlines?
2180 * @return bool
2182 public function getShowGridlines()
2184 return $this->showGridlines;
2188 * Set show gridlines.
2190 * @param bool $pValue Show gridlines (true/false)
2192 * @return Worksheet
2194 public function setShowGridlines($pValue)
2196 $this->showGridlines = $pValue;
2198 return $this;
2202 * Print gridlines?
2204 * @return bool
2206 public function getPrintGridlines()
2208 return $this->printGridlines;
2212 * Set print gridlines.
2214 * @param bool $pValue Print gridlines (true/false)
2216 * @return Worksheet
2218 public function setPrintGridlines($pValue)
2220 $this->printGridlines = $pValue;
2222 return $this;
2226 * Show row and column headers?
2228 * @return bool
2230 public function getShowRowColHeaders()
2232 return $this->showRowColHeaders;
2236 * Set show row and column headers.
2238 * @param bool $pValue Show row and column headers (true/false)
2240 * @return Worksheet
2242 public function setShowRowColHeaders($pValue)
2244 $this->showRowColHeaders = $pValue;
2246 return $this;
2250 * Show summary below? (Row/Column outlining).
2252 * @return bool
2254 public function getShowSummaryBelow()
2256 return $this->showSummaryBelow;
2260 * Set show summary below.
2262 * @param bool $pValue Show summary below (true/false)
2264 * @return Worksheet
2266 public function setShowSummaryBelow($pValue)
2268 $this->showSummaryBelow = $pValue;
2270 return $this;
2274 * Show summary right? (Row/Column outlining).
2276 * @return bool
2278 public function getShowSummaryRight()
2280 return $this->showSummaryRight;
2284 * Set show summary right.
2286 * @param bool $pValue Show summary right (true/false)
2288 * @return Worksheet
2290 public function setShowSummaryRight($pValue)
2292 $this->showSummaryRight = $pValue;
2294 return $this;
2298 * Get comments.
2300 * @return Comment[]
2302 public function getComments()
2304 return $this->comments;
2308 * Set comments array for the entire sheet.
2310 * @param Comment[] $pValue
2312 * @return Worksheet
2314 public function setComments(array $pValue)
2316 $this->comments = $pValue;
2318 return $this;
2322 * Get comment for cell.
2324 * @param string $pCellCoordinate Cell coordinate to get comment for, eg: 'A1'
2326 * @throws Exception
2328 * @return Comment
2330 public function getComment($pCellCoordinate)
2332 // Uppercase coordinate
2333 $pCellCoordinate = strtoupper($pCellCoordinate);
2335 if (Coordinate::coordinateIsRange($pCellCoordinate)) {
2336 throw new Exception('Cell coordinate string can not be a range of cells.');
2337 } elseif (strpos($pCellCoordinate, '$') !== false) {
2338 throw new Exception('Cell coordinate string must not be absolute.');
2339 } elseif ($pCellCoordinate == '') {
2340 throw new Exception('Cell coordinate can not be zero-length string.');
2343 // Check if we already have a comment for this cell.
2344 if (isset($this->comments[$pCellCoordinate])) {
2345 return $this->comments[$pCellCoordinate];
2348 // If not, create a new comment.
2349 $newComment = new Comment();
2350 $this->comments[$pCellCoordinate] = $newComment;
2352 return $newComment;
2356 * Get comment for cell by using numeric cell coordinates.
2358 * @param int $columnIndex Numeric column coordinate of the cell
2359 * @param int $row Numeric row coordinate of the cell
2361 * @return Comment
2363 public function getCommentByColumnAndRow($columnIndex, $row)
2365 return $this->getComment(Coordinate::stringFromColumnIndex($columnIndex) . $row);
2369 * Get active cell.
2371 * @return string Example: 'A1'
2373 public function getActiveCell()
2375 return $this->activeCell;
2379 * Get selected cells.
2381 * @return string
2383 public function getSelectedCells()
2385 return $this->selectedCells;
2389 * Selected cell.
2391 * @param string $pCoordinate Cell (i.e. A1)
2393 * @return Worksheet
2395 public function setSelectedCell($pCoordinate)
2397 return $this->setSelectedCells($pCoordinate);
2401 * Select a range of cells.
2403 * @param string $pCoordinate Cell range, examples: 'A1', 'B2:G5', 'A:C', '3:6'
2405 * @return Worksheet
2407 public function setSelectedCells($pCoordinate)
2409 // Uppercase coordinate
2410 $pCoordinate = strtoupper($pCoordinate);
2412 // Convert 'A' to 'A:A'
2413 $pCoordinate = preg_replace('/^([A-Z]+)$/', '${1}:${1}', $pCoordinate);
2415 // Convert '1' to '1:1'
2416 $pCoordinate = preg_replace('/^(\d+)$/', '${1}:${1}', $pCoordinate);
2418 // Convert 'A:C' to 'A1:C1048576'
2419 $pCoordinate = preg_replace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $pCoordinate);
2421 // Convert '1:3' to 'A1:XFD3'
2422 $pCoordinate = preg_replace('/^(\d+):(\d+)$/', 'A${1}:XFD${2}', $pCoordinate);
2424 if (Coordinate::coordinateIsRange($pCoordinate)) {
2425 list($first) = Coordinate::splitRange($pCoordinate);
2426 $this->activeCell = $first[0];
2427 } else {
2428 $this->activeCell = $pCoordinate;
2430 $this->selectedCells = $pCoordinate;
2432 return $this;
2436 * Selected cell by using numeric cell coordinates.
2438 * @param int $columnIndex Numeric column coordinate of the cell
2439 * @param int $row Numeric row coordinate of the cell
2441 * @throws Exception
2443 * @return Worksheet
2445 public function setSelectedCellByColumnAndRow($columnIndex, $row)
2447 return $this->setSelectedCells(Coordinate::stringFromColumnIndex($columnIndex) . $row);
2451 * Get right-to-left.
2453 * @return bool
2455 public function getRightToLeft()
2457 return $this->rightToLeft;
2461 * Set right-to-left.
2463 * @param bool $value Right-to-left true/false
2465 * @return Worksheet
2467 public function setRightToLeft($value)
2469 $this->rightToLeft = $value;
2471 return $this;
2475 * Fill worksheet from values in array.
2477 * @param array $source Source array
2478 * @param mixed $nullValue Value in source array that stands for blank cell
2479 * @param string $startCell Insert array starting from this cell address as the top left coordinate
2480 * @param bool $strictNullComparison Apply strict comparison when testing for null values in the array
2482 * @throws Exception
2484 * @return Worksheet
2486 public function fromArray(array $source, $nullValue = null, $startCell = 'A1', $strictNullComparison = false)
2488 // Convert a 1-D array to 2-D (for ease of looping)
2489 if (!is_array(end($source))) {
2490 $source = [$source];
2493 // start coordinate
2494 list($startColumn, $startRow) = Coordinate::coordinateFromString($startCell);
2496 // Loop through $source
2497 foreach ($source as $rowData) {
2498 $currentColumn = $startColumn;
2499 foreach ($rowData as $cellValue) {
2500 if ($strictNullComparison) {
2501 if ($cellValue !== $nullValue) {
2502 // Set cell value
2503 $this->getCell($currentColumn . $startRow)->setValue($cellValue);
2505 } else {
2506 if ($cellValue != $nullValue) {
2507 // Set cell value
2508 $this->getCell($currentColumn . $startRow)->setValue($cellValue);
2511 ++$currentColumn;
2513 ++$startRow;
2516 return $this;
2520 * Create array from a range of cells.
2522 * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
2523 * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
2524 * @param bool $calculateFormulas Should formulas be calculated?
2525 * @param bool $formatData Should formatting be applied to cell values?
2526 * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2527 * True - Return rows and columns indexed by their actual row and column IDs
2529 * @return array
2531 public function rangeToArray($pRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
2533 // Returnvalue
2534 $returnValue = [];
2535 // Identify the range that we need to extract from the worksheet
2536 list($rangeStart, $rangeEnd) = Coordinate::rangeBoundaries($pRange);
2537 $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]);
2538 $minRow = $rangeStart[1];
2539 $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]);
2540 $maxRow = $rangeEnd[1];
2542 ++$maxCol;
2543 // Loop through rows
2544 $r = -1;
2545 for ($row = $minRow; $row <= $maxRow; ++$row) {
2546 $rRef = ($returnCellRef) ? $row : ++$r;
2547 $c = -1;
2548 // Loop through columns in the current row
2549 for ($col = $minCol; $col != $maxCol; ++$col) {
2550 $cRef = ($returnCellRef) ? $col : ++$c;
2551 // Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen
2552 // so we test and retrieve directly against cellCollection
2553 if ($this->cellCollection->has($col . $row)) {
2554 // Cell exists
2555 $cell = $this->cellCollection->get($col . $row);
2556 if ($cell->getValue() !== null) {
2557 if ($cell->getValue() instanceof RichText) {
2558 $returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText();
2559 } else {
2560 if ($calculateFormulas) {
2561 $returnValue[$rRef][$cRef] = $cell->getCalculatedValue();
2562 } else {
2563 $returnValue[$rRef][$cRef] = $cell->getValue();
2567 if ($formatData) {
2568 $style = $this->parent->getCellXfByIndex($cell->getXfIndex());
2569 $returnValue[$rRef][$cRef] = NumberFormat::toFormattedString(
2570 $returnValue[$rRef][$cRef],
2571 ($style && $style->getNumberFormat()) ? $style->getNumberFormat()->getFormatCode() : NumberFormat::FORMAT_GENERAL
2574 } else {
2575 // Cell holds a NULL
2576 $returnValue[$rRef][$cRef] = $nullValue;
2578 } else {
2579 // Cell doesn't exist
2580 $returnValue[$rRef][$cRef] = $nullValue;
2585 // Return
2586 return $returnValue;
2590 * Create array from a range of cells.
2592 * @param string $pNamedRange Name of the Named Range
2593 * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
2594 * @param bool $calculateFormulas Should formulas be calculated?
2595 * @param bool $formatData Should formatting be applied to cell values?
2596 * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2597 * True - Return rows and columns indexed by their actual row and column IDs
2599 * @throws Exception
2601 * @return array
2603 public function namedRangeToArray($pNamedRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
2605 $namedRange = NamedRange::resolveRange($pNamedRange, $this);
2606 if ($namedRange !== null) {
2607 $pWorkSheet = $namedRange->getWorksheet();
2608 $pCellRange = $namedRange->getRange();
2610 return $pWorkSheet->rangeToArray($pCellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef);
2613 throw new Exception('Named Range ' . $pNamedRange . ' does not exist.');
2617 * Create array from worksheet.
2619 * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
2620 * @param bool $calculateFormulas Should formulas be calculated?
2621 * @param bool $formatData Should formatting be applied to cell values?
2622 * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2623 * True - Return rows and columns indexed by their actual row and column IDs
2625 * @return array
2627 public function toArray($nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
2629 // Garbage collect...
2630 $this->garbageCollect();
2632 // Identify the range that we need to extract from the worksheet
2633 $maxCol = $this->getHighestColumn();
2634 $maxRow = $this->getHighestRow();
2636 // Return
2637 return $this->rangeToArray('A1:' . $maxCol . $maxRow, $nullValue, $calculateFormulas, $formatData, $returnCellRef);
2641 * Get row iterator.
2643 * @param int $startRow The row number at which to start iterating
2644 * @param int $endRow The row number at which to stop iterating
2646 * @return RowIterator
2648 public function getRowIterator($startRow = 1, $endRow = null)
2650 return new RowIterator($this, $startRow, $endRow);
2654 * Get column iterator.
2656 * @param string $startColumn The column address at which to start iterating
2657 * @param string $endColumn The column address at which to stop iterating
2659 * @return ColumnIterator
2661 public function getColumnIterator($startColumn = 'A', $endColumn = null)
2663 return new ColumnIterator($this, $startColumn, $endColumn);
2667 * Run PhpSpreadsheet garbage collector.
2669 * @return Worksheet
2671 public function garbageCollect()
2673 // Flush cache
2674 $this->cellCollection->get('A1');
2676 // Lookup highest column and highest row if cells are cleaned
2677 $colRow = $this->cellCollection->getHighestRowAndColumn();
2678 $highestRow = $colRow['row'];
2679 $highestColumn = Coordinate::columnIndexFromString($colRow['column']);
2681 // Loop through column dimensions
2682 foreach ($this->columnDimensions as $dimension) {
2683 $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex()));
2686 // Loop through row dimensions
2687 foreach ($this->rowDimensions as $dimension) {
2688 $highestRow = max($highestRow, $dimension->getRowIndex());
2691 // Cache values
2692 if ($highestColumn < 1) {
2693 $this->cachedHighestColumn = 'A';
2694 } else {
2695 $this->cachedHighestColumn = Coordinate::stringFromColumnIndex($highestColumn);
2697 $this->cachedHighestRow = $highestRow;
2699 // Return
2700 return $this;
2704 * Get hash code.
2706 * @return string Hash code
2708 public function getHashCode()
2710 if ($this->dirty) {
2711 $this->hash = md5($this->title . $this->autoFilter . ($this->protection->isProtectionEnabled() ? 't' : 'f') . __CLASS__);
2712 $this->dirty = false;
2715 return $this->hash;
2719 * Extract worksheet title from range.
2721 * Example: extractSheetTitle("testSheet!A1") ==> 'A1'
2722 * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1'];
2724 * @param string $pRange Range to extract title from
2725 * @param bool $returnRange Return range? (see example)
2727 * @return mixed
2729 public static function extractSheetTitle($pRange, $returnRange = false)
2731 // Sheet title included?
2732 if (($sep = strpos($pRange, '!')) === false) {
2733 return '';
2736 if ($returnRange) {
2737 return [trim(substr($pRange, 0, $sep), "'"), substr($pRange, $sep + 1)];
2740 return substr($pRange, $sep + 1);
2744 * Get hyperlink.
2746 * @param string $pCellCoordinate Cell coordinate to get hyperlink for, eg: 'A1'
2748 * @return Hyperlink
2750 public function getHyperlink($pCellCoordinate)
2752 // return hyperlink if we already have one
2753 if (isset($this->hyperlinkCollection[$pCellCoordinate])) {
2754 return $this->hyperlinkCollection[$pCellCoordinate];
2757 // else create hyperlink
2758 $this->hyperlinkCollection[$pCellCoordinate] = new Hyperlink();
2760 return $this->hyperlinkCollection[$pCellCoordinate];
2764 * Set hyperlink.
2766 * @param string $pCellCoordinate Cell coordinate to insert hyperlink, eg: 'A1'
2767 * @param null|Hyperlink $pHyperlink
2769 * @return Worksheet
2771 public function setHyperlink($pCellCoordinate, Hyperlink $pHyperlink = null)
2773 if ($pHyperlink === null) {
2774 unset($this->hyperlinkCollection[$pCellCoordinate]);
2775 } else {
2776 $this->hyperlinkCollection[$pCellCoordinate] = $pHyperlink;
2779 return $this;
2783 * Hyperlink at a specific coordinate exists?
2785 * @param string $pCoordinate eg: 'A1'
2787 * @return bool
2789 public function hyperlinkExists($pCoordinate)
2791 return isset($this->hyperlinkCollection[$pCoordinate]);
2795 * Get collection of hyperlinks.
2797 * @return Hyperlink[]
2799 public function getHyperlinkCollection()
2801 return $this->hyperlinkCollection;
2805 * Get data validation.
2807 * @param string $pCellCoordinate Cell coordinate to get data validation for, eg: 'A1'
2809 * @return DataValidation
2811 public function getDataValidation($pCellCoordinate)
2813 // return data validation if we already have one
2814 if (isset($this->dataValidationCollection[$pCellCoordinate])) {
2815 return $this->dataValidationCollection[$pCellCoordinate];
2818 // else create data validation
2819 $this->dataValidationCollection[$pCellCoordinate] = new DataValidation();
2821 return $this->dataValidationCollection[$pCellCoordinate];
2825 * Set data validation.
2827 * @param string $pCellCoordinate Cell coordinate to insert data validation, eg: 'A1'
2828 * @param null|DataValidation $pDataValidation
2830 * @return Worksheet
2832 public function setDataValidation($pCellCoordinate, DataValidation $pDataValidation = null)
2834 if ($pDataValidation === null) {
2835 unset($this->dataValidationCollection[$pCellCoordinate]);
2836 } else {
2837 $this->dataValidationCollection[$pCellCoordinate] = $pDataValidation;
2840 return $this;
2844 * Data validation at a specific coordinate exists?
2846 * @param string $pCoordinate eg: 'A1'
2848 * @return bool
2850 public function dataValidationExists($pCoordinate)
2852 return isset($this->dataValidationCollection[$pCoordinate]);
2856 * Get collection of data validations.
2858 * @return DataValidation[]
2860 public function getDataValidationCollection()
2862 return $this->dataValidationCollection;
2866 * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet.
2868 * @param string $range
2870 * @return string Adjusted range value
2872 public function shrinkRangeToFit($range)
2874 $maxCol = $this->getHighestColumn();
2875 $maxRow = $this->getHighestRow();
2876 $maxCol = Coordinate::columnIndexFromString($maxCol);
2878 $rangeBlocks = explode(' ', $range);
2879 foreach ($rangeBlocks as &$rangeSet) {
2880 $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet);
2882 if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) {
2883 $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol);
2885 if ($rangeBoundaries[0][1] > $maxRow) {
2886 $rangeBoundaries[0][1] = $maxRow;
2888 if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) {
2889 $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol);
2891 if ($rangeBoundaries[1][1] > $maxRow) {
2892 $rangeBoundaries[1][1] = $maxRow;
2894 $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1];
2896 unset($rangeSet);
2897 $stRange = implode(' ', $rangeBlocks);
2899 return $stRange;
2903 * Get tab color.
2905 * @return Color
2907 public function getTabColor()
2909 if ($this->tabColor === null) {
2910 $this->tabColor = new Color();
2913 return $this->tabColor;
2917 * Reset tab color.
2919 * @return Worksheet
2921 public function resetTabColor()
2923 $this->tabColor = null;
2924 unset($this->tabColor);
2926 return $this;
2930 * Tab color set?
2932 * @return bool
2934 public function isTabColorSet()
2936 return $this->tabColor !== null;
2940 * Copy worksheet (!= clone!).
2942 * @return Worksheet
2944 public function copy()
2946 $copied = clone $this;
2948 return $copied;
2952 * Implement PHP __clone to create a deep clone, not just a shallow copy.
2954 public function __clone()
2956 foreach ($this as $key => $val) {
2957 if ($key == 'parent') {
2958 continue;
2961 if (is_object($val) || (is_array($val))) {
2962 if ($key == 'cellCollection') {
2963 $newCollection = $this->cellCollection->cloneCellCollection($this);
2964 $this->cellCollection = $newCollection;
2965 } elseif ($key == 'drawingCollection') {
2966 $newCollection = new ArrayObject();
2967 foreach ($this->drawingCollection as $id => $item) {
2968 if (is_object($item)) {
2969 $newCollection[$id] = clone $this->drawingCollection[$id];
2972 $this->drawingCollection = $newCollection;
2973 } elseif (($key == 'autoFilter') && ($this->autoFilter instanceof AutoFilter)) {
2974 $newAutoFilter = clone $this->autoFilter;
2975 $this->autoFilter = $newAutoFilter;
2976 $this->autoFilter->setParent($this);
2977 } else {
2978 $this->{$key} = unserialize(serialize($val));
2985 * Define the code name of the sheet.
2987 * @param string $pValue Same rule as Title minus space not allowed (but, like Excel, change
2988 * silently space to underscore)
2989 * @param bool $validate False to skip validation of new title. WARNING: This should only be set
2990 * at parse time (by Readers), where titles can be assumed to be valid.
2992 * @throws Exception
2994 * @return Worksheet
2996 public function setCodeName($pValue, $validate = true)
2998 // Is this a 'rename' or not?
2999 if ($this->getCodeName() == $pValue) {
3000 return $this;
3003 if ($validate) {
3004 $pValue = str_replace(' ', '_', $pValue); //Excel does this automatically without flinching, we are doing the same
3006 // Syntax check
3007 // throw an exception if not valid
3008 self::checkSheetCodeName($pValue);
3010 // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_'
3012 if ($this->getParent()) {
3013 // Is there already such sheet name?
3014 if ($this->getParent()->sheetCodeNameExists($pValue)) {
3015 // Use name, but append with lowest possible integer
3017 if (Shared\StringHelper::countCharacters($pValue) > 29) {
3018 $pValue = Shared\StringHelper::substring($pValue, 0, 29);
3020 $i = 1;
3021 while ($this->getParent()->sheetCodeNameExists($pValue . '_' . $i)) {
3022 ++$i;
3023 if ($i == 10) {
3024 if (Shared\StringHelper::countCharacters($pValue) > 28) {
3025 $pValue = Shared\StringHelper::substring($pValue, 0, 28);
3027 } elseif ($i == 100) {
3028 if (Shared\StringHelper::countCharacters($pValue) > 27) {
3029 $pValue = Shared\StringHelper::substring($pValue, 0, 27);
3034 $pValue = $pValue . '_' . $i; // ok, we have a valid name
3039 $this->codeName = $pValue;
3041 return $this;
3045 * Return the code name of the sheet.
3047 * @return null|string
3049 public function getCodeName()
3051 return $this->codeName;
3055 * Sheet has a code name ?
3057 * @return bool
3059 public function hasCodeName()
3061 return !($this->codeName === null);