Passed
Pull Request — master (#4240)
by Owen
27:46 queued 17:34
created

Worksheet::getChartCollection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Worksheet;
4
5
use ArrayObject;
6
use Generator;
7
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
8
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
9
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
10
use PhpOffice\PhpSpreadsheet\Cell\Cell;
11
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
12
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
13
use PhpOffice\PhpSpreadsheet\Cell\DataType;
14
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
15
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
16
use PhpOffice\PhpSpreadsheet\Cell\IValueBinder;
17
use PhpOffice\PhpSpreadsheet\Chart\Chart;
18
use PhpOffice\PhpSpreadsheet\Collection\Cells;
19
use PhpOffice\PhpSpreadsheet\Collection\CellsFactory;
20
use PhpOffice\PhpSpreadsheet\Comment;
21
use PhpOffice\PhpSpreadsheet\DefinedName;
22
use PhpOffice\PhpSpreadsheet\Exception;
23
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
24
use PhpOffice\PhpSpreadsheet\RichText\RichText;
25
use PhpOffice\PhpSpreadsheet\Shared;
26
use PhpOffice\PhpSpreadsheet\Spreadsheet;
27
use PhpOffice\PhpSpreadsheet\Style\Alignment;
28
use PhpOffice\PhpSpreadsheet\Style\Color;
29
use PhpOffice\PhpSpreadsheet\Style\Conditional;
30
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
31
use PhpOffice\PhpSpreadsheet\Style\Protection as StyleProtection;
32
use PhpOffice\PhpSpreadsheet\Style\Style;
33
34
class Worksheet
35
{
36
    // Break types
37
    public const BREAK_NONE = 0;
38
    public const BREAK_ROW = 1;
39
    public const BREAK_COLUMN = 2;
40
    // Maximum column for row break
41
    public const BREAK_ROW_MAX_COLUMN = 16383;
42
43
    // Sheet state
44
    public const SHEETSTATE_VISIBLE = 'visible';
45
    public const SHEETSTATE_HIDDEN = 'hidden';
46
    public const SHEETSTATE_VERYHIDDEN = 'veryHidden';
47
48
    public const MERGE_CELL_CONTENT_EMPTY = 'empty';
49
    public const MERGE_CELL_CONTENT_HIDE = 'hide';
50
    public const MERGE_CELL_CONTENT_MERGE = 'merge';
51
52
    public const FUNCTION_LIKE_GROUPBY = '/\\b(groupby|_xleta)\\b/i'; // weird new syntax
53
54
    protected const SHEET_NAME_REQUIRES_NO_QUOTES = '/^[_\p{L}][_\p{L}\p{N}]*$/mui';
55
56
    /**
57
     * Maximum 31 characters allowed for sheet title.
58
     *
59
     * @var int
60
     */
61
    const SHEET_TITLE_MAXIMUM_LENGTH = 31;
62
63
    /**
64
     * Invalid characters in sheet title.
65
     */
66
    private static array $invalidCharacters = ['*', ':', '/', '\\', '?', '[', ']'];
67
68
    /**
69
     * Parent spreadsheet.
70
     */
71
    private ?Spreadsheet $parent = null;
72
73
    /**
74
     * Collection of cells.
75
     */
76
    private Cells $cellCollection;
77
78
    private bool $cellCollectionInitialized = true;
79
80
    /**
81
     * Collection of row dimensions.
82
     *
83
     * @var RowDimension[]
84
     */
85
    private array $rowDimensions = [];
86
87
    /**
88
     * Default row dimension.
89
     */
90
    private RowDimension $defaultRowDimension;
91
92
    /**
93
     * Collection of column dimensions.
94
     *
95
     * @var ColumnDimension[]
96
     */
97
    private array $columnDimensions = [];
98
99
    /**
100
     * Default column dimension.
101
     */
102
    private ColumnDimension $defaultColumnDimension;
103
104
    /**
105
     * Collection of drawings.
106
     *
107
     * @var ArrayObject<int, BaseDrawing>
108
     */
109
    private ArrayObject $drawingCollection;
110
111
    /**
112
     * Collection of Chart objects.
113
     *
114
     * @var ArrayObject<int, Chart>
115
     */
116
    private ArrayObject $chartCollection;
117
118
    /**
119
     * Collection of Table objects.
120
     *
121
     * @var ArrayObject<int, Table>
122
     */
123
    private ArrayObject $tableCollection;
124
125
    /**
126
     * Worksheet title.
127
     */
128
    private string $title = '';
129
130
    /**
131
     * Sheet state.
132
     */
133
    private string $sheetState;
134
135
    /**
136
     * Page setup.
137
     */
138
    private PageSetup $pageSetup;
139
140
    /**
141
     * Page margins.
142
     */
143
    private PageMargins $pageMargins;
144
145
    /**
146
     * Page header/footer.
147
     */
148
    private HeaderFooter $headerFooter;
149
150
    /**
151
     * Sheet view.
152
     */
153
    private SheetView $sheetView;
154
155
    /**
156
     * Protection.
157
     */
158
    private Protection $protection;
159
160
    /**
161
     * Collection of styles.
162
     *
163
     * @var Style[]
164
     */
165
    private array $styles = [];
166
167
    /**
168
     * Conditional styles. Indexed by cell coordinate, e.g. 'A1'.
169
     */
170
    private array $conditionalStylesCollection = [];
171
172
    /**
173
     * Collection of row breaks.
174
     *
175
     * @var PageBreak[]
176
     */
177
    private array $rowBreaks = [];
178
179
    /**
180
     * Collection of column breaks.
181
     *
182
     * @var PageBreak[]
183
     */
184
    private array $columnBreaks = [];
185
186
    /**
187
     * Collection of merged cell ranges.
188
     *
189
     * @var string[]
190
     */
191
    private array $mergeCells = [];
192
193
    /**
194
     * Collection of protected cell ranges.
195
     *
196
     * @var ProtectedRange[]
197
     */
198
    private array $protectedCells = [];
199
200
    /**
201
     * Autofilter Range and selection.
202
     */
203
    private AutoFilter $autoFilter;
204
205
    /**
206
     * Freeze pane.
207
     */
208
    private ?string $freezePane = null;
209
210
    /**
211
     * Default position of the right bottom pane.
212
     */
213
    private ?string $topLeftCell = null;
214
215
    private string $paneTopLeftCell = '';
216
217
    private string $activePane = '';
218
219
    private int $xSplit = 0;
220
221
    private int $ySplit = 0;
222
223
    private string $paneState = '';
224
225
    /**
226
     * Properties of the 4 panes.
227
     *
228
     * @var (null|Pane)[]
229
     */
230
    private array $panes = [
231
        'bottomRight' => null,
232
        'bottomLeft' => null,
233
        'topRight' => null,
234
        'topLeft' => null,
235
    ];
236
237
    /**
238
     * Show gridlines?
239
     */
240
    private bool $showGridlines = true;
241
242
    /**
243
     * Print gridlines?
244
     */
245
    private bool $printGridlines = false;
246
247
    /**
248
     * Show row and column headers?
249
     */
250
    private bool $showRowColHeaders = true;
251
252
    /**
253
     * Show summary below? (Row/Column outline).
254
     */
255
    private bool $showSummaryBelow = true;
256
257
    /**
258
     * Show summary right? (Row/Column outline).
259
     */
260
    private bool $showSummaryRight = true;
261
262
    /**
263
     * Collection of comments.
264
     *
265
     * @var Comment[]
266
     */
267
    private array $comments = [];
268
269
    /**
270
     * Active cell. (Only one!).
271
     */
272
    private string $activeCell = 'A1';
273
274
    /**
275
     * Selected cells.
276
     */
277
    private string $selectedCells = 'A1';
278
279
    /**
280
     * Cached highest column.
281
     */
282
    private int $cachedHighestColumn = 1;
283
284
    /**
285
     * Cached highest row.
286
     */
287
    private int $cachedHighestRow = 1;
288
289
    /**
290
     * Right-to-left?
291
     */
292
    private bool $rightToLeft = false;
293
294
    /**
295
     * Hyperlinks. Indexed by cell coordinate, e.g. 'A1'.
296
     */
297
    private array $hyperlinkCollection = [];
298
299
    /**
300
     * Data validation objects. Indexed by cell coordinate, e.g. 'A1'.
301
     * Index can include ranges, and multiple cells/ranges.
302
     */
303
    private array $dataValidationCollection = [];
304
305
    /**
306
     * Tab color.
307
     */
308
    private ?Color $tabColor = null;
309
310
    /**
311
     * Hash.
312
     */
313
    private int $hash;
314
315
    /**
316
     * CodeName.
317
     */
318
    private ?string $codeName = null;
319
320
    /**
321
     * Create a new worksheet.
322
     */
323 10446
    public function __construct(?Spreadsheet $parent = null, string $title = 'Worksheet')
324
    {
325
        // Set parent and title
326 10446
        $this->parent = $parent;
327 10446
        $this->hash = spl_object_id($this);
328 10446
        $this->setTitle($title, false);
329
        // setTitle can change $pTitle
330 10446
        $this->setCodeName($this->getTitle());
331 10446
        $this->setSheetState(self::SHEETSTATE_VISIBLE);
332
333 10446
        $this->cellCollection = CellsFactory::getInstance($this);
334
        // Set page setup
335 10446
        $this->pageSetup = new PageSetup();
336
        // Set page margins
337 10446
        $this->pageMargins = new PageMargins();
338
        // Set page header/footer
339 10446
        $this->headerFooter = new HeaderFooter();
340
        // Set sheet view
341 10446
        $this->sheetView = new SheetView();
342
        // Drawing collection
343 10446
        $this->drawingCollection = new ArrayObject();
344
        // Chart collection
345 10446
        $this->chartCollection = new ArrayObject();
346
        // Protection
347 10446
        $this->protection = new Protection();
348
        // Default row dimension
349 10446
        $this->defaultRowDimension = new RowDimension(null);
350
        // Default column dimension
351 10446
        $this->defaultColumnDimension = new ColumnDimension(null);
352
        // AutoFilter
353 10446
        $this->autoFilter = new AutoFilter('', $this);
354
        // Table collection
355 10446
        $this->tableCollection = new ArrayObject();
356
    }
357
358
    /**
359
     * Disconnect all cells from this Worksheet object,
360
     * typically so that the worksheet object can be unset.
361
     */
362 9057
    public function disconnectCells(): void
363
    {
364 9057
        if ($this->cellCollectionInitialized) {
365 9056
            $this->cellCollection->unsetWorksheetCells();
366 9056
            unset($this->cellCollection);
367 9056
            $this->cellCollectionInitialized = false;
368
        }
369
        //    detach ourself from the workbook, so that it can then delete this worksheet successfully
370 9057
        $this->parent = null;
371
    }
372
373
    /**
374
     * Code to execute when this worksheet is unset().
375
     */
376 117
    public function __destruct()
377
    {
378 117
        Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title);
379
380 117
        $this->disconnectCells();
381 117
        unset($this->rowDimensions, $this->columnDimensions, $this->tableCollection, $this->drawingCollection, $this->chartCollection, $this->autoFilter);
382
    }
383
384 1
    public function __wakeup(): void
385
    {
386 1
        $this->hash = spl_object_id($this);
387 1
        $this->parent = null;
388
    }
389
390
    /**
391
     * Return the cell collection.
392
     */
393 10118
    public function getCellCollection(): Cells
394
    {
395 10118
        return $this->cellCollection;
396
    }
397
398
    /**
399
     * Get array of invalid characters for sheet title.
400
     */
401 1
    public static function getInvalidCharacters(): array
402
    {
403 1
        return self::$invalidCharacters;
404
    }
405
406
    /**
407
     * Check sheet code name for valid Excel syntax.
408
     *
409
     * @param string $sheetCodeName The string to check
410
     *
411
     * @return string The valid string
412
     */
413 10446
    private static function checkSheetCodeName(string $sheetCodeName): string
414
    {
415 10446
        $charCount = Shared\StringHelper::countCharacters($sheetCodeName);
416 10446
        if ($charCount == 0) {
417 1
            throw new Exception('Sheet code name cannot be empty.');
418
        }
419
        // Some of the printable ASCII characters are invalid:  * : / \ ? [ ] and  first and last characters cannot be a "'"
420
        if (
421 10446
            (str_replace(self::$invalidCharacters, '', $sheetCodeName) !== $sheetCodeName)
422 10446
            || (Shared\StringHelper::substring($sheetCodeName, -1, 1) == '\'')
423 10446
            || (Shared\StringHelper::substring($sheetCodeName, 0, 1) == '\'')
424
        ) {
425 1
            throw new Exception('Invalid character found in sheet code name');
426
        }
427
428
        // Enforce maximum characters allowed for sheet title
429 10446
        if ($charCount > self::SHEET_TITLE_MAXIMUM_LENGTH) {
430 1
            throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.');
431
        }
432
433 10446
        return $sheetCodeName;
434
    }
435
436
    /**
437
     * Check sheet title for valid Excel syntax.
438
     *
439
     * @param string $sheetTitle The string to check
440
     *
441
     * @return string The valid string
442
     */
443 10446
    private static function checkSheetTitle(string $sheetTitle): string
444
    {
445
        // Some of the printable ASCII characters are invalid:  * : / \ ? [ ]
446 10446
        if (str_replace(self::$invalidCharacters, '', $sheetTitle) !== $sheetTitle) {
447 2
            throw new Exception('Invalid character found in sheet title');
448
        }
449
450
        // Enforce maximum characters allowed for sheet title
451 10446
        if (Shared\StringHelper::countCharacters($sheetTitle) > self::SHEET_TITLE_MAXIMUM_LENGTH) {
452 3
            throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.');
453
        }
454
455 10446
        return $sheetTitle;
456
    }
457
458
    /**
459
     * Get a sorted list of all cell coordinates currently held in the collection by row and column.
460
     *
461
     * @param bool $sorted Also sort the cell collection?
462
     *
463
     * @return string[]
464
     */
465 1381
    public function getCoordinates(bool $sorted = true): array
466
    {
467 1381
        if ($this->cellCollectionInitialized === false) {
468 1
            return [];
469
        }
470
471 1380
        if ($sorted) {
472 488
            return $this->cellCollection->getSortedCoordinates();
473
        }
474
475 1287
        return $this->cellCollection->getCoordinates();
476
    }
477
478
    /**
479
     * Get collection of row dimensions.
480
     *
481
     * @return RowDimension[]
482
     */
483 1106
    public function getRowDimensions(): array
484
    {
485 1106
        return $this->rowDimensions;
486
    }
487
488
    /**
489
     * Get default row dimension.
490
     */
491 1054
    public function getDefaultRowDimension(): RowDimension
492
    {
493 1054
        return $this->defaultRowDimension;
494
    }
495
496
    /**
497
     * Get collection of column dimensions.
498
     *
499
     * @return ColumnDimension[]
500
     */
501 1112
    public function getColumnDimensions(): array
502
    {
503
        /** @var callable $callable */
504 1112
        $callable = [self::class, 'columnDimensionCompare'];
505 1112
        uasort($this->columnDimensions, $callable);
506
507 1112
        return $this->columnDimensions;
508
    }
509
510 80
    private static function columnDimensionCompare(ColumnDimension $a, ColumnDimension $b): int
511
    {
512 80
        return $a->getColumnNumeric() - $b->getColumnNumeric();
513
    }
514
515
    /**
516
     * Get default column dimension.
517
     */
518 513
    public function getDefaultColumnDimension(): ColumnDimension
519
    {
520 513
        return $this->defaultColumnDimension;
521
    }
522
523
    /**
524
     * Get collection of drawings.
525
     *
526
     * @return ArrayObject<int, BaseDrawing>
527
     */
528 1085
    public function getDrawingCollection(): ArrayObject
529
    {
530 1085
        return $this->drawingCollection;
531
    }
532
533
    /**
534
     * Get collection of charts.
535
     *
536
     * @return ArrayObject<int, Chart>
537
     */
538 100
    public function getChartCollection(): ArrayObject
539
    {
540 100
        return $this->chartCollection;
541
    }
542
543 105
    public function addChart(Chart $chart): Chart
544
    {
545 105
        $chart->setWorksheet($this);
546 105
        $this->chartCollection[] = $chart;
547
548 105
        return $chart;
549
    }
550
551
    /**
552
     * Return the count of charts on this worksheet.
553
     *
554
     * @return int The number of charts
555
     */
556 83
    public function getChartCount(): int
557
    {
558 83
        return count($this->chartCollection);
559
    }
560
561
    /**
562
     * Get a chart by its index position.
563
     *
564
     * @param ?string $index Chart index position
565
     *
566
     * @return Chart|false
567
     */
568 77
    public function getChartByIndex(?string $index)
569
    {
570 77
        $chartCount = count($this->chartCollection);
571 77
        if ($chartCount == 0) {
572
            return false;
573
        }
574 77
        if ($index === null) {
575
            $index = --$chartCount;
576
        }
577 77
        if (!isset($this->chartCollection[$index])) {
578
            return false;
579
        }
580
581 77
        return $this->chartCollection[$index];
582
    }
583
584
    /**
585
     * Return an array of the names of charts on this worksheet.
586
     *
587
     * @return string[] The names of charts
588
     */
589 5
    public function getChartNames(): array
590
    {
591 5
        $chartNames = [];
592 5
        foreach ($this->chartCollection as $chart) {
593 5
            $chartNames[] = $chart->getName();
594
        }
595
596 5
        return $chartNames;
597
    }
598
599
    /**
600
     * Get a chart by name.
601
     *
602
     * @param string $chartName Chart name
603
     *
604
     * @return Chart|false
605
     */
606 6
    public function getChartByName(string $chartName)
607
    {
608 6
        foreach ($this->chartCollection as $index => $chart) {
609 6
            if ($chart->getName() == $chartName) {
610 6
                return $chart;
611
            }
612
        }
613
614 1
        return false;
615
    }
616
617 6
    public function getChartByNameOrThrow(string $chartName): Chart
618
    {
619 6
        $chart = $this->getChartByName($chartName);
620 6
        if ($chart !== false) {
621 6
            return $chart;
622
        }
623
624 1
        throw new Exception("Sheet does not have a chart named $chartName.");
625
    }
626
627
    /**
628
     * Refresh column dimensions.
629
     *
630
     * @return $this
631
     */
632 25
    public function refreshColumnDimensions(): static
633
    {
634 25
        $newColumnDimensions = [];
635 25
        foreach ($this->getColumnDimensions() as $objColumnDimension) {
636 25
            $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension;
637
        }
638
639 25
        $this->columnDimensions = $newColumnDimensions;
640
641 25
        return $this;
642
    }
643
644
    /**
645
     * Refresh row dimensions.
646
     *
647
     * @return $this
648
     */
649 7
    public function refreshRowDimensions(): static
650
    {
651 7
        $newRowDimensions = [];
652 7
        foreach ($this->getRowDimensions() as $objRowDimension) {
653 7
            $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension;
654
        }
655
656 7
        $this->rowDimensions = $newRowDimensions;
657
658 7
        return $this;
659
    }
660
661
    /**
662
     * Calculate worksheet dimension.
663
     *
664
     * @return string String containing the dimension of this worksheet
665
     */
666 425
    public function calculateWorksheetDimension(): string
667
    {
668
        // Return
669 425
        return 'A1:' . $this->getHighestColumn() . $this->getHighestRow();
670
    }
671
672
    /**
673
     * Calculate worksheet data dimension.
674
     *
675
     * @return string String containing the dimension of this worksheet that actually contain data
676
     */
677 539
    public function calculateWorksheetDataDimension(): string
678
    {
679
        // Return
680 539
        return 'A1:' . $this->getHighestDataColumn() . $this->getHighestDataRow();
681
    }
682
683
    /**
684
     * Calculate widths for auto-size columns.
685
     *
686
     * @return $this
687
     */
688 745
    public function calculateColumnWidths(): static
689
    {
690 745
        $activeSheet = $this->getParent()?->getActiveSheetIndex();
691 745
        $selectedCells = $this->selectedCells;
692
        // initialize $autoSizes array
693 745
        $autoSizes = [];
694 745
        foreach ($this->getColumnDimensions() as $colDimension) {
695 139
            if ($colDimension->getAutoSize()) {
696 58
                $autoSizes[$colDimension->getColumnIndex()] = -1;
697
            }
698
        }
699
700
        // There is only something to do if there are some auto-size columns
701 745
        if (!empty($autoSizes)) {
702 58
            $holdActivePane = $this->activePane;
703
            // build list of cells references that participate in a merge
704 58
            $isMergeCell = [];
705 58
            foreach ($this->getMergeCells() as $cells) {
706 16
                foreach (Coordinate::extractAllCellReferencesInRange($cells) as $cellReference) {
707 16
                    $isMergeCell[$cellReference] = true;
708
                }
709
            }
710
711 58
            $autoFilterIndentRanges = (new AutoFit($this))->getAutoFilterIndentRanges();
712
713
            // loop through all cells in the worksheet
714 58
            foreach ($this->getCoordinates(false) as $coordinate) {
715 58
                $cell = $this->getCellOrNull($coordinate);
716
717 58
                if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) {
718
                    //Determine if cell is in merge range
719 58
                    $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]);
720
721
                    //By default merged cells should be ignored
722 58
                    $isMergedButProceed = false;
723
724
                    //The only exception is if it's a merge range value cell of a 'vertical' range (1 column wide)
725 58
                    if ($isMerged && $cell->isMergeRangeValueCell()) {
726
                        $range = (string) $cell->getMergeRange();
727
                        $rangeBoundaries = Coordinate::rangeDimension($range);
728
                        if ($rangeBoundaries[0] === 1) {
729
                            $isMergedButProceed = true;
730
                        }
731
                    }
732
733
                    // Determine width if cell is not part of a merge or does and is a value cell of 1-column wide range
734 58
                    if (!$isMerged || $isMergedButProceed) {
735
                        // Determine if we need to make an adjustment for the first row in an AutoFilter range that
736
                        //    has a column filter dropdown
737 58
                        $filterAdjustment = false;
738 58
                        if (!empty($autoFilterIndentRanges)) {
739 4
                            foreach ($autoFilterIndentRanges as $autoFilterFirstRowRange) {
740 4
                                if ($cell->isInRange($autoFilterFirstRowRange)) {
741 4
                                    $filterAdjustment = true;
742
743 4
                                    break;
744
                                }
745
                            }
746
                        }
747
748 58
                        $indentAdjustment = $cell->getStyle()->getAlignment()->getIndent();
749 58
                        $indentAdjustment += (int) ($cell->getStyle()->getAlignment()->getHorizontal() === Alignment::HORIZONTAL_CENTER);
750
751
                        // Calculated value
752
                        // To formatted string
753 58
                        $cellValue = NumberFormat::toFormattedString(
754 58
                            $cell->getCalculatedValueString(),
755 58
                            (string) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())
756 58
                                ->getNumberFormat()->getFormatCode(true)
757 58
                        );
758
759 58
                        if ($cellValue !== null && $cellValue !== '') {
760 58
                            $autoSizes[$this->cellCollection->getCurrentColumn()] = max(
761 58
                                $autoSizes[$this->cellCollection->getCurrentColumn()],
762 58
                                round(
763 58
                                    Shared\Font::calculateColumnWidth(
764 58
                                        $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont(),
765 58
                                        $cellValue,
766 58
                                        (int) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())
767 58
                                            ->getAlignment()->getTextRotation(),
768 58
                                        $this->getParentOrThrow()->getDefaultStyle()->getFont(),
769 58
                                        $filterAdjustment,
770 58
                                        $indentAdjustment
771 58
                                    ),
772 58
                                    3
773 58
                                )
774 58
                            );
775
                        }
776
                    }
777
                }
778
            }
779
780
            // adjust column widths
781 58
            foreach ($autoSizes as $columnIndex => $width) {
782 58
                if ($width == -1) {
783
                    $width = $this->getDefaultColumnDimension()->getWidth();
784
                }
785 58
                $this->getColumnDimension($columnIndex)->setWidth($width);
786
            }
787 58
            $this->activePane = $holdActivePane;
788
        }
789 745
        if ($activeSheet !== null && $activeSheet >= 0) {
790 745
            $this->getParent()?->setActiveSheetIndex($activeSheet);
791
        }
792 745
        $this->setSelectedCells($selectedCells);
793
794 745
        return $this;
795
    }
796
797
    /**
798
     * Get parent or null.
799
     */
800 10119
    public function getParent(): ?Spreadsheet
801
    {
802 10119
        return $this->parent;
803
    }
804
805
    /**
806
     * Get parent, throw exception if null.
807
     */
808 10152
    public function getParentOrThrow(): Spreadsheet
809
    {
810 10152
        if ($this->parent !== null) {
811 10151
            return $this->parent;
812
        }
813
814 1
        throw new Exception('Sheet does not have a parent.');
815
    }
816
817
    /**
818
     * Re-bind parent.
819
     *
820
     * @return $this
821
     */
822 54
    public function rebindParent(Spreadsheet $parent): static
823
    {
824 54
        if ($this->parent !== null) {
825 4
            $definedNames = $this->parent->getDefinedNames();
826 4
            foreach ($definedNames as $definedName) {
827
                $parent->addDefinedName($definedName);
828
            }
829
830 4
            $this->parent->removeSheetByIndex(
831 4
                $this->parent->getIndex($this)
832 4
            );
833
        }
834 54
        $this->parent = $parent;
835
836 54
        return $this;
837
    }
838
839
    /**
840
     * Get title.
841
     */
842 10446
    public function getTitle(): string
843
    {
844 10446
        return $this->title;
845
    }
846
847
    /**
848
     * Set title.
849
     *
850
     * @param string $title String containing the dimension of this worksheet
851
     * @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should
852
     *            be updated to reflect the new sheet name.
853
     *          This should be left as the default true, unless you are
854
     *          certain that no formula cells on any worksheet contain
855
     *          references to this worksheet
856
     * @param bool $validate False to skip validation of new title. WARNING: This should only be set
857
     *                       at parse time (by Readers), where titles can be assumed to be valid.
858
     *
859
     * @return $this
860
     */
861 10446
    public function setTitle(string $title, bool $updateFormulaCellReferences = true, bool $validate = true): static
862
    {
863
        // Is this a 'rename' or not?
864 10446
        if ($this->getTitle() == $title) {
865 268
            return $this;
866
        }
867
868
        // Old title
869 10446
        $oldTitle = $this->getTitle();
870
871 10446
        if ($validate) {
872
            // Syntax check
873 10446
            self::checkSheetTitle($title);
874
875 10446
            if ($this->parent && $this->parent->getIndex($this, true) >= 0) {
876
                // Is there already such sheet name?
877 791
                if ($this->parent->sheetNameExists($title)) {
878
                    // Use name, but append with lowest possible integer
879
880 2
                    if (Shared\StringHelper::countCharacters($title) > 29) {
881
                        $title = Shared\StringHelper::substring($title, 0, 29);
882
                    }
883 2
                    $i = 1;
884 2
                    while ($this->parent->sheetNameExists($title . ' ' . $i)) {
885 1
                        ++$i;
886 1
                        if ($i == 10) {
887
                            if (Shared\StringHelper::countCharacters($title) > 28) {
888
                                $title = Shared\StringHelper::substring($title, 0, 28);
889
                            }
890 1
                        } elseif ($i == 100) {
891
                            if (Shared\StringHelper::countCharacters($title) > 27) {
892
                                $title = Shared\StringHelper::substring($title, 0, 27);
893
                            }
894
                        }
895
                    }
896
897 2
                    $title .= " $i";
898
                }
899
            }
900
        }
901
902
        // Set title
903 10446
        $this->title = $title;
904
905 10446
        if ($this->parent && $this->parent->getIndex($this, true) >= 0 && $this->parent->getCalculationEngine()) {
906
            // New title
907 1370
            $newTitle = $this->getTitle();
908 1370
            $this->parent->getCalculationEngine()
909 1370
                ->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
910 1370
            if ($updateFormulaCellReferences) {
911 791
                ReferenceHelper::getInstance()->updateNamedFormulae($this->parent, $oldTitle, $newTitle);
912
            }
913
        }
914
915 10446
        return $this;
916
    }
917
918
    /**
919
     * Get sheet state.
920
     *
921
     * @return string Sheet state (visible, hidden, veryHidden)
922
     */
923 470
    public function getSheetState(): string
924
    {
925 470
        return $this->sheetState;
926
    }
927
928
    /**
929
     * Set sheet state.
930
     *
931
     * @param string $value Sheet state (visible, hidden, veryHidden)
932
     *
933
     * @return $this
934
     */
935 10446
    public function setSheetState(string $value): static
936
    {
937 10446
        $this->sheetState = $value;
938
939 10446
        return $this;
940
    }
941
942
    /**
943
     * Get page setup.
944
     */
945 1492
    public function getPageSetup(): PageSetup
946
    {
947 1492
        return $this->pageSetup;
948
    }
949
950
    /**
951
     * Set page setup.
952
     *
953
     * @return $this
954
     */
955 1
    public function setPageSetup(PageSetup $pageSetup): static
956
    {
957 1
        $this->pageSetup = $pageSetup;
958
959 1
        return $this;
960
    }
961
962
    /**
963
     * Get page margins.
964
     */
965 1505
    public function getPageMargins(): PageMargins
966
    {
967 1505
        return $this->pageMargins;
968
    }
969
970
    /**
971
     * Set page margins.
972
     *
973
     * @return $this
974
     */
975 1
    public function setPageMargins(PageMargins $pageMargins): static
976
    {
977 1
        $this->pageMargins = $pageMargins;
978
979 1
        return $this;
980
    }
981
982
    /**
983
     * Get page header/footer.
984
     */
985 521
    public function getHeaderFooter(): HeaderFooter
986
    {
987 521
        return $this->headerFooter;
988
    }
989
990
    /**
991
     * Set page header/footer.
992
     *
993
     * @return $this
994
     */
995 1
    public function setHeaderFooter(HeaderFooter $headerFooter): static
996
    {
997 1
        $this->headerFooter = $headerFooter;
998
999 1
        return $this;
1000
    }
1001
1002
    /**
1003
     * Get sheet view.
1004
     */
1005 547
    public function getSheetView(): SheetView
1006
    {
1007 547
        return $this->sheetView;
1008
    }
1009
1010
    /**
1011
     * Set sheet view.
1012
     *
1013
     * @return $this
1014
     */
1015 1
    public function setSheetView(SheetView $sheetView): static
1016
    {
1017 1
        $this->sheetView = $sheetView;
1018
1019 1
        return $this;
1020
    }
1021
1022
    /**
1023
     * Get Protection.
1024
     */
1025 572
    public function getProtection(): Protection
1026
    {
1027 572
        return $this->protection;
1028
    }
1029
1030
    /**
1031
     * Set Protection.
1032
     *
1033
     * @return $this
1034
     */
1035 1
    public function setProtection(Protection $protection): static
1036
    {
1037 1
        $this->protection = $protection;
1038
1039 1
        return $this;
1040
    }
1041
1042
    /**
1043
     * Get highest worksheet column.
1044
     *
1045
     * @param null|int|string $row Return the data highest column for the specified row,
1046
     *                                     or the highest column of any row if no row number is passed
1047
     *
1048
     * @return string Highest column name
1049
     */
1050 1397
    public function getHighestColumn($row = null): string
1051
    {
1052 1397
        if ($row === null) {
1053 1396
            return Coordinate::stringFromColumnIndex($this->cachedHighestColumn);
1054
        }
1055
1056 1
        return $this->getHighestDataColumn($row);
1057
    }
1058
1059
    /**
1060
     * Get highest worksheet column that contains data.
1061
     *
1062
     * @param null|int|string $row Return the highest data column for the specified row,
1063
     *                                     or the highest data column of any row if no row number is passed
1064
     *
1065
     * @return string Highest column name that contains data
1066
     */
1067 668
    public function getHighestDataColumn($row = null): string
1068
    {
1069 668
        return $this->cellCollection->getHighestColumn($row);
1070
    }
1071
1072
    /**
1073
     * Get highest worksheet row.
1074
     *
1075
     * @param null|string $column Return the highest data row for the specified column,
1076
     *                                     or the highest row of any column if no column letter is passed
1077
     *
1078
     * @return int Highest row number
1079
     */
1080 895
    public function getHighestRow(?string $column = null): int
1081
    {
1082 895
        if ($column === null) {
1083 894
            return $this->cachedHighestRow;
1084
        }
1085
1086 1
        return $this->getHighestDataRow($column);
1087
    }
1088
1089
    /**
1090
     * Get highest worksheet row that contains data.
1091
     *
1092
     * @param null|string $column Return the highest data row for the specified column,
1093
     *                                     or the highest data row of any column if no column letter is passed
1094
     *
1095
     * @return int Highest row number that contains data
1096
     */
1097 667
    public function getHighestDataRow(?string $column = null): int
1098
    {
1099 667
        return $this->cellCollection->getHighestRow($column);
1100
    }
1101
1102
    /**
1103
     * Get highest worksheet column and highest row that have cell records.
1104
     *
1105
     * @return array Highest column name and highest row number
1106
     */
1107 1
    public function getHighestRowAndColumn(): array
1108
    {
1109 1
        return $this->cellCollection->getHighestRowAndColumn();
1110
    }
1111
1112
    /**
1113
     * Set a cell value.
1114
     *
1115
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1116
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1117
     * @param mixed $value Value for the cell
1118
     * @param null|IValueBinder $binder Value Binder to override the currently set Value Binder
1119
     *
1120
     * @return $this
1121
     */
1122 4669
    public function setCellValue(CellAddress|string|array $coordinate, mixed $value, ?IValueBinder $binder = null): static
1123
    {
1124 4669
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
1125 4669
        $this->getCell($cellAddress)->setValue($value, $binder);
1126
1127 4669
        return $this;
1128
    }
1129
1130
    /**
1131
     * Set a cell value.
1132
     *
1133
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1134
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1135
     * @param mixed $value Value of the cell
1136
     * @param string $dataType Explicit data type, see DataType::TYPE_*
1137
     *        Note that PhpSpreadsheet does not validate that the value and datatype are consistent, in using this
1138
     *             method, then it is your responsibility as an end-user developer to validate that the value and
1139
     *             the datatype match.
1140
     *       If you do mismatch value and datatpe, then the value you enter may be changed to match the datatype
1141
     *          that you specify.
1142
     *
1143
     * @see DataType
1144
     *
1145
     * @return $this
1146
     */
1147 104
    public function setCellValueExplicit(CellAddress|string|array $coordinate, mixed $value, string $dataType): static
1148
    {
1149 104
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
1150 104
        $this->getCell($cellAddress)->setValueExplicit($value, $dataType);
1151
1152 104
        return $this;
1153
    }
1154
1155
    /**
1156
     * Get cell at a specific coordinate.
1157
     *
1158
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1159
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1160
     *
1161
     * @return Cell Cell that was found or created
1162
     *              WARNING: Because the cell collection can be cached to reduce memory, it only allows one
1163
     *              "active" cell at a time in memory. If you assign that cell to a variable, then select
1164
     *              another cell using getCell() or any of its variants, the newly selected cell becomes
1165
     *              the "active" cell, and any previous assignment becomes a disconnected reference because
1166
     *              the active cell has changed.
1167
     */
1168 10075
    public function getCell(CellAddress|string|array $coordinate): Cell
1169
    {
1170 10075
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
1171
1172
        // Shortcut for increased performance for the vast majority of simple cases
1173 10075
        if ($this->cellCollection->has($cellAddress)) {
1174
            /** @var Cell $cell */
1175 10041
            $cell = $this->cellCollection->get($cellAddress);
1176
1177 10041
            return $cell;
1178
        }
1179
1180
        /** @var Worksheet $sheet */
1181 10075
        [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress);
1182 10075
        $cell = $sheet->getCellCollection()->get($finalCoordinate);
1183
1184 10075
        return $cell ?? $sheet->createNewCell($finalCoordinate);
1185
    }
1186
1187
    /**
1188
     * Get the correct Worksheet and coordinate from a coordinate that may
1189
     * contains reference to another sheet or a named range.
1190
     *
1191
     * @return array{0: Worksheet, 1: string}
1192
     */
1193 10077
    private function getWorksheetAndCoordinate(string $coordinate): array
1194
    {
1195 10077
        $sheet = null;
1196 10077
        $finalCoordinate = null;
1197
1198
        // Worksheet reference?
1199 10077
        if (str_contains($coordinate, '!')) {
1200
            $worksheetReference = self::extractSheetTitle($coordinate, true);
1201
1202
            $sheet = $this->getParentOrThrow()->getSheetByName($worksheetReference[0]);
1203
            $finalCoordinate = strtoupper($worksheetReference[1]);
1204
1205
            if ($sheet === null) {
1206
                throw new Exception('Sheet not found for name: ' . $worksheetReference[0]);
1207
            }
1208
        } elseif (
1209 10077
            !preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $coordinate)
1210 10077
            && preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/iu', $coordinate)
1211
        ) {
1212
            // Named range?
1213 15
            $namedRange = $this->validateNamedRange($coordinate, true);
1214 15
            if ($namedRange !== null) {
1215 10
                $sheet = $namedRange->getWorksheet();
1216 10
                if ($sheet === null) {
1217
                    throw new Exception('Sheet not found for named range: ' . $namedRange->getName());
1218
                }
1219
1220
                /** @phpstan-ignore-next-line */
1221 10
                $cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!');
1222 10
                $finalCoordinate = str_replace('$', '', $cellCoordinate);
1223
            }
1224
        }
1225
1226 10077
        if ($sheet === null || $finalCoordinate === null) {
1227 10077
            $sheet = $this;
1228 10077
            $finalCoordinate = strtoupper($coordinate);
1229
        }
1230
1231 10077
        if (Coordinate::coordinateIsRange($finalCoordinate)) {
1232 2
            throw new Exception('Cell coordinate string can not be a range of cells.');
1233 10077
        } elseif (str_contains($finalCoordinate, '$')) {
1234
            throw new Exception('Cell coordinate must not be absolute.');
1235
        }
1236
1237 10077
        return [$sheet, $finalCoordinate];
1238
    }
1239
1240
    /**
1241
     * Get an existing cell at a specific coordinate, or null.
1242
     *
1243
     * @param string $coordinate Coordinate of the cell, eg: 'A1'
1244
     *
1245
     * @return null|Cell Cell that was found or null
1246
     */
1247 58
    private function getCellOrNull(string $coordinate): ?Cell
1248
    {
1249
        // Check cell collection
1250 58
        if ($this->cellCollection->has($coordinate)) {
1251 58
            return $this->cellCollection->get($coordinate);
1252
        }
1253
1254
        return null;
1255
    }
1256
1257
    /**
1258
     * Create a new cell at the specified coordinate.
1259
     *
1260
     * @param string $coordinate Coordinate of the cell
1261
     *
1262
     * @return Cell Cell that was created
1263
     *              WARNING: Because the cell collection can be cached to reduce memory, it only allows one
1264
     *              "active" cell at a time in memory. If you assign that cell to a variable, then select
1265
     *              another cell using getCell() or any of its variants, the newly selected cell becomes
1266
     *              the "active" cell, and any previous assignment becomes a disconnected reference because
1267
     *              the active cell has changed.
1268
     */
1269 10075
    public function createNewCell(string $coordinate): Cell
1270
    {
1271 10075
        [$column, $row, $columnString] = Coordinate::indexesFromString($coordinate);
1272 10075
        $cell = new Cell(null, DataType::TYPE_NULL, $this);
1273 10075
        $this->cellCollection->add($coordinate, $cell);
1274
1275
        // Coordinates
1276 10075
        if ($column > $this->cachedHighestColumn) {
1277 6903
            $this->cachedHighestColumn = $column;
1278
        }
1279 10075
        if ($row > $this->cachedHighestRow) {
1280 8461
            $this->cachedHighestRow = $row;
1281
        }
1282
1283
        // Cell needs appropriate xfIndex from dimensions records
1284
        //    but don't create dimension records if they don't already exist
1285 10075
        $rowDimension = $this->rowDimensions[$row] ?? null;
1286 10075
        $columnDimension = $this->columnDimensions[$columnString] ?? null;
1287
1288 10075
        $xfSet = false;
1289 10075
        if ($rowDimension !== null) {
1290 385
            $rowXf = (int) $rowDimension->getXfIndex();
1291 385
            if ($rowXf > 0) {
1292
                // then there is a row dimension with explicit style, assign it to the cell
1293 203
                $cell->setXfIndex($rowXf);
1294 203
                $xfSet = true;
1295
            }
1296
        }
1297 10075
        if (!$xfSet && $columnDimension !== null) {
1298 526
            $colXf = (int) $columnDimension->getXfIndex();
1299 526
            if ($colXf > 0) {
1300
                // then there is a column dimension, assign it to the cell
1301 214
                $cell->setXfIndex($colXf);
1302
            }
1303
        }
1304
1305 10075
        return $cell;
1306
    }
1307
1308
    /**
1309
     * Does the cell at a specific coordinate exist?
1310
     *
1311
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1312
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1313
     */
1314 9982
    public function cellExists(CellAddress|string|array $coordinate): bool
1315
    {
1316 9982
        $cellAddress = Validations::validateCellAddress($coordinate);
1317 9982
        [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress);
1318
1319 9982
        return $sheet->getCellCollection()->has($finalCoordinate);
1320
    }
1321
1322
    /**
1323
     * Get row dimension at a specific row.
1324
     *
1325
     * @param int $row Numeric index of the row
1326
     */
1327 545
    public function getRowDimension(int $row): RowDimension
1328
    {
1329
        // Get row dimension
1330 545
        if (!isset($this->rowDimensions[$row])) {
1331 545
            $this->rowDimensions[$row] = new RowDimension($row);
1332
1333 545
            $this->cachedHighestRow = max($this->cachedHighestRow, $row);
1334
        }
1335
1336 545
        return $this->rowDimensions[$row];
1337
    }
1338
1339 1
    public function getRowStyle(int $row): ?Style
1340
    {
1341 1
        return $this->parent?->getCellXfByIndexOrNull(
1342 1
            ($this->rowDimensions[$row] ?? null)?->getXfIndex()
1343 1
        );
1344
    }
1345
1346 563
    public function rowDimensionExists(int $row): bool
1347
    {
1348 563
        return isset($this->rowDimensions[$row]);
1349
    }
1350
1351 37
    public function columnDimensionExists(string $column): bool
1352
    {
1353 37
        return isset($this->columnDimensions[$column]);
1354
    }
1355
1356
    /**
1357
     * Get column dimension at a specific column.
1358
     *
1359
     * @param string $column String index of the column eg: 'A'
1360
     */
1361 624
    public function getColumnDimension(string $column): ColumnDimension
1362
    {
1363
        // Uppercase coordinate
1364 624
        $column = strtoupper($column);
1365
1366
        // Fetch dimensions
1367 624
        if (!isset($this->columnDimensions[$column])) {
1368 624
            $this->columnDimensions[$column] = new ColumnDimension($column);
1369
1370 624
            $columnIndex = Coordinate::columnIndexFromString($column);
1371 624
            if ($this->cachedHighestColumn < $columnIndex) {
1372 438
                $this->cachedHighestColumn = $columnIndex;
1373
            }
1374
        }
1375
1376 624
        return $this->columnDimensions[$column];
1377
    }
1378
1379
    /**
1380
     * Get column dimension at a specific column by using numeric cell coordinates.
1381
     *
1382
     * @param int $columnIndex Numeric column coordinate of the cell
1383
     */
1384 100
    public function getColumnDimensionByColumn(int $columnIndex): ColumnDimension
1385
    {
1386 100
        return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex));
1387
    }
1388
1389 1
    public function getColumnStyle(string $column): ?Style
1390
    {
1391 1
        return $this->parent?->getCellXfByIndexOrNull(
1392 1
            ($this->columnDimensions[$column] ?? null)?->getXfIndex()
1393 1
        );
1394
    }
1395
1396
    /**
1397
     * Get styles.
1398
     *
1399
     * @return Style[]
1400
     */
1401 1
    public function getStyles(): array
1402
    {
1403 1
        return $this->styles;
1404
    }
1405
1406
    /**
1407
     * Get style for cell.
1408
     *
1409
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $cellCoordinate
1410
     *              A simple string containing a cell address like 'A1' or a cell range like 'A1:E10'
1411
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1412
     *              or a CellAddress or AddressRange object.
1413
     */
1414 10022
    public function getStyle(AddressRange|CellAddress|int|string|array $cellCoordinate): Style
1415
    {
1416 10022
        $cellCoordinate = Validations::validateCellOrCellRange($cellCoordinate);
1417
1418
        // set this sheet as active
1419 10022
        $this->getParentOrThrow()->setActiveSheetIndex($this->getParentOrThrow()->getIndex($this));
1420
1421
        // set cell coordinate as active
1422 10022
        $this->setSelectedCells($cellCoordinate);
1423
1424 10022
        return $this->getParentOrThrow()->getCellXfSupervisor();
1425
    }
1426
1427
    /**
1428
     * Get conditional styles for a cell.
1429
     *
1430
     * @param string $coordinate eg: 'A1' or 'A1:A3'.
1431
     *          If a single cell is referenced, then the array of conditional styles will be returned if the cell is
1432
     *               included in a conditional style range.
1433
     *          If a range of cells is specified, then the styles will only be returned if the range matches the entire
1434
     *               range of the conditional.
1435
     *
1436
     * @return Conditional[]
1437
     */
1438 236
    public function getConditionalStyles(string $coordinate): array
1439
    {
1440 236
        $coordinate = strtoupper($coordinate);
1441 236
        if (str_contains($coordinate, ':')) {
1442 47
            return $this->conditionalStylesCollection[$coordinate] ?? [];
1443
        }
1444
1445 214
        $cell = $this->getCell($coordinate);
1446 214
        foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) {
1447 201
            $cellBlocks = explode(',', Coordinate::resolveUnionAndIntersection($conditionalRange));
1448 201
            foreach ($cellBlocks as $cellBlock) {
1449 201
                if ($cell->isInRange($cellBlock)) {
1450 194
                    return $this->conditionalStylesCollection[$conditionalRange];
1451
                }
1452
            }
1453
        }
1454
1455 43
        return [];
1456
    }
1457
1458 180
    public function getConditionalRange(string $coordinate): ?string
1459
    {
1460 180
        $coordinate = strtoupper($coordinate);
1461 180
        $cell = $this->getCell($coordinate);
1462 180
        foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) {
1463 180
            $cellBlocks = explode(',', Coordinate::resolveUnionAndIntersection($conditionalRange));
1464 180
            foreach ($cellBlocks as $cellBlock) {
1465 180
                if ($cell->isInRange($cellBlock)) {
1466 179
                    return $conditionalRange;
1467
                }
1468
            }
1469
        }
1470
1471 3
        return null;
1472
    }
1473
1474
    /**
1475
     * Do conditional styles exist for this cell?
1476
     *
1477
     * @param string $coordinate eg: 'A1' or 'A1:A3'.
1478
     *          If a single cell is specified, then this method will return true if that cell is included in a
1479
     *               conditional style range.
1480
     *          If a range of cells is specified, then true will only be returned if the range matches the entire
1481
     *               range of the conditional.
1482
     */
1483 22
    public function conditionalStylesExists(string $coordinate): bool
1484
    {
1485 22
        $coordinate = strtoupper($coordinate);
1486 22
        if (str_contains($coordinate, ':')) {
1487 11
            return isset($this->conditionalStylesCollection[$coordinate]);
1488
        }
1489
1490 11
        $cell = $this->getCell($coordinate);
1491 11
        foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) {
1492 11
            if ($cell->isInRange($conditionalRange)) {
1493 7
                return true;
1494
            }
1495
        }
1496
1497 4
        return false;
1498
    }
1499
1500
    /**
1501
     * Removes conditional styles for a cell.
1502
     *
1503
     * @param string $coordinate eg: 'A1'
1504
     *
1505
     * @return $this
1506
     */
1507 42
    public function removeConditionalStyles(string $coordinate): static
1508
    {
1509 42
        unset($this->conditionalStylesCollection[strtoupper($coordinate)]);
1510
1511 42
        return $this;
1512
    }
1513
1514
    /**
1515
     * Get collection of conditional styles.
1516
     */
1517 549
    public function getConditionalStylesCollection(): array
1518
    {
1519 549
        return $this->conditionalStylesCollection;
1520
    }
1521
1522
    /**
1523
     * Set conditional styles.
1524
     *
1525
     * @param string $coordinate eg: 'A1'
1526
     * @param Conditional[] $styles
1527
     *
1528
     * @return $this
1529
     */
1530 303
    public function setConditionalStyles(string $coordinate, array $styles): static
1531
    {
1532 303
        $this->conditionalStylesCollection[strtoupper($coordinate)] = $styles;
1533
1534 303
        return $this;
1535
    }
1536
1537
    /**
1538
     * Duplicate cell style to a range of cells.
1539
     *
1540
     * Please note that this will overwrite existing cell styles for cells in range!
1541
     *
1542
     * @param Style $style Cell style to duplicate
1543
     * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
1544
     *
1545
     * @return $this
1546
     */
1547 2
    public function duplicateStyle(Style $style, string $range): static
1548
    {
1549
        // Add the style to the workbook if necessary
1550 2
        $workbook = $this->getParentOrThrow();
1551 2
        if ($existingStyle = $workbook->getCellXfByHashCode($style->getHashCode())) {
1552
            // there is already such cell Xf in our collection
1553 1
            $xfIndex = $existingStyle->getIndex();
1554
        } else {
1555
            // we don't have such a cell Xf, need to add
1556 2
            $workbook->addCellXf($style);
1557 2
            $xfIndex = $style->getIndex();
1558
        }
1559
1560
        // Calculate range outer borders
1561 2
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range);
1562
1563
        // Make sure we can loop upwards on rows and columns
1564 2
        if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
1565
            $tmp = $rangeStart;
1566
            $rangeStart = $rangeEnd;
1567
            $rangeEnd = $tmp;
1568
        }
1569
1570
        // Loop through cells and apply styles
1571 2
        for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
1572 2
            for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
1573 2
                $this->getCell(Coordinate::stringFromColumnIndex($col) . $row)->setXfIndex($xfIndex);
1574
            }
1575
        }
1576
1577 2
        return $this;
1578
    }
1579
1580
    /**
1581
     * Duplicate conditional style to a range of cells.
1582
     *
1583
     * Please note that this will overwrite existing cell styles for cells in range!
1584
     *
1585
     * @param Conditional[] $styles Cell style to duplicate
1586
     * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
1587
     *
1588
     * @return $this
1589
     */
1590 18
    public function duplicateConditionalStyle(array $styles, string $range = ''): static
1591
    {
1592 18
        foreach ($styles as $cellStyle) {
1593 18
            if (!($cellStyle instanceof Conditional)) {
1594
                throw new Exception('Style is not a conditional style');
1595
            }
1596
        }
1597
1598
        // Calculate range outer borders
1599 18
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range);
1600
1601
        // Make sure we can loop upwards on rows and columns
1602 18
        if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
1603
            $tmp = $rangeStart;
1604
            $rangeStart = $rangeEnd;
1605
            $rangeEnd = $tmp;
1606
        }
1607
1608
        // Loop through cells and apply styles
1609 18
        for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
1610 18
            for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
1611 18
                $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $styles);
1612
            }
1613
        }
1614
1615 18
        return $this;
1616
    }
1617
1618
    /**
1619
     * Set break on a cell.
1620
     *
1621
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1622
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1623
     * @param int $break Break type (type of Worksheet::BREAK_*)
1624
     *
1625
     * @return $this
1626
     */
1627 29
    public function setBreak(CellAddress|string|array $coordinate, int $break, int $max = -1): static
1628
    {
1629 29
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
1630
1631 29
        if ($break === self::BREAK_NONE) {
1632 7
            unset($this->rowBreaks[$cellAddress], $this->columnBreaks[$cellAddress]);
1633 29
        } elseif ($break === self::BREAK_ROW) {
1634 21
            $this->rowBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max);
1635 17
        } elseif ($break === self::BREAK_COLUMN) {
1636 17
            $this->columnBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max);
1637
        }
1638
1639 29
        return $this;
1640
    }
1641
1642
    /**
1643
     * Get breaks.
1644
     *
1645
     * @return int[]
1646
     */
1647 623
    public function getBreaks(): array
1648
    {
1649 623
        $breaks = [];
1650
        /** @var callable $compareFunction */
1651 623
        $compareFunction = [self::class, 'compareRowBreaks'];
1652 623
        uksort($this->rowBreaks, $compareFunction);
1653 623
        foreach ($this->rowBreaks as $break) {
1654 10
            $breaks[$break->getCoordinate()] = self::BREAK_ROW;
1655
        }
1656
        /** @var callable $compareFunction */
1657 623
        $compareFunction = [self::class, 'compareColumnBreaks'];
1658 623
        uksort($this->columnBreaks, $compareFunction);
1659 623
        foreach ($this->columnBreaks as $break) {
1660 8
            $breaks[$break->getCoordinate()] = self::BREAK_COLUMN;
1661
        }
1662
1663 623
        return $breaks;
1664
    }
1665
1666
    /**
1667
     * Get row breaks.
1668
     *
1669
     * @return PageBreak[]
1670
     */
1671 471
    public function getRowBreaks(): array
1672
    {
1673
        /** @var callable $compareFunction */
1674 471
        $compareFunction = [self::class, 'compareRowBreaks'];
1675 471
        uksort($this->rowBreaks, $compareFunction);
1676
1677 471
        return $this->rowBreaks;
1678
    }
1679
1680 9
    protected static function compareRowBreaks(string $coordinate1, string $coordinate2): int
1681
    {
1682 9
        $row1 = Coordinate::indexesFromString($coordinate1)[1];
1683 9
        $row2 = Coordinate::indexesFromString($coordinate2)[1];
1684
1685 9
        return $row1 - $row2;
1686
    }
1687
1688 5
    protected static function compareColumnBreaks(string $coordinate1, string $coordinate2): int
1689
    {
1690 5
        $column1 = Coordinate::indexesFromString($coordinate1)[0];
1691 5
        $column2 = Coordinate::indexesFromString($coordinate2)[0];
1692
1693 5
        return $column1 - $column2;
1694
    }
1695
1696
    /**
1697
     * Get column breaks.
1698
     *
1699
     * @return PageBreak[]
1700
     */
1701 470
    public function getColumnBreaks(): array
1702
    {
1703
        /** @var callable $compareFunction */
1704 470
        $compareFunction = [self::class, 'compareColumnBreaks'];
1705 470
        uksort($this->columnBreaks, $compareFunction);
1706
1707 470
        return $this->columnBreaks;
1708
    }
1709
1710
    /**
1711
     * Set merge on a cell range.
1712
     *
1713
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range A simple string containing a Cell range like 'A1:E10'
1714
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1715
     *              or an AddressRange.
1716
     * @param string $behaviour How the merged cells should behave.
1717
     *               Possible values are:
1718
     *                   MERGE_CELL_CONTENT_EMPTY - Empty the content of the hidden cells
1719
     *                   MERGE_CELL_CONTENT_HIDE - Keep the content of the hidden cells
1720
     *                   MERGE_CELL_CONTENT_MERGE - Move the content of the hidden cells into the first cell
1721
     *
1722
     * @return $this
1723
     */
1724 167
    public function mergeCells(AddressRange|string|array $range, string $behaviour = self::MERGE_CELL_CONTENT_EMPTY): static
1725
    {
1726 167
        $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range));
1727
1728 166
        if (!str_contains($range, ':')) {
1729 1
            $range .= ":{$range}";
1730
        }
1731
1732 166
        if (preg_match('/^([A-Z]+)(\\d+):([A-Z]+)(\\d+)$/', $range, $matches) !== 1) {
1733 1
            throw new Exception('Merge must be on a valid range of cells.');
1734
        }
1735
1736 165
        $this->mergeCells[$range] = $range;
1737 165
        $firstRow = (int) $matches[2];
1738 165
        $lastRow = (int) $matches[4];
1739 165
        $firstColumn = $matches[1];
1740 165
        $lastColumn = $matches[3];
1741 165
        $firstColumnIndex = Coordinate::columnIndexFromString($firstColumn);
1742 165
        $lastColumnIndex = Coordinate::columnIndexFromString($lastColumn);
1743 165
        $numberRows = $lastRow - $firstRow;
1744 165
        $numberColumns = $lastColumnIndex - $firstColumnIndex;
1745
1746 165
        if ($numberRows === 1 && $numberColumns === 1) {
1747 34
            return $this;
1748
        }
1749
1750
        // create upper left cell if it does not already exist
1751 158
        $upperLeft = "{$firstColumn}{$firstRow}";
1752 158
        if (!$this->cellExists($upperLeft)) {
1753 36
            $this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL);
1754
        }
1755
1756 158
        if ($behaviour !== self::MERGE_CELL_CONTENT_HIDE) {
1757
            // Blank out the rest of the cells in the range (if they exist)
1758 56
            if ($numberRows > $numberColumns) {
1759 17
                $this->clearMergeCellsByColumn($firstColumn, $lastColumn, $firstRow, $lastRow, $upperLeft, $behaviour);
1760
            } else {
1761 39
                $this->clearMergeCellsByRow($firstColumn, $lastColumnIndex, $firstRow, $lastRow, $upperLeft, $behaviour);
1762
            }
1763
        }
1764
1765 158
        return $this;
1766
    }
1767
1768 17
    private function clearMergeCellsByColumn(string $firstColumn, string $lastColumn, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void
1769
    {
1770 17
        $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE)
1771
            ? [$this->getCell($upperLeft)->getFormattedValue()]
1772 17
            : [];
1773
1774 17
        foreach ($this->getColumnIterator($firstColumn, $lastColumn) as $column) {
1775 17
            $iterator = $column->getCellIterator($firstRow);
1776 17
            $iterator->setIterateOnlyExistingCells(true);
1777 17
            foreach ($iterator as $cell) {
1778 17
                if ($cell !== null) {
1779 17
                    $row = $cell->getRow();
1780 17
                    if ($row > $lastRow) {
1781 7
                        break;
1782
                    }
1783 17
                    $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue);
1784
                }
1785
            }
1786
        }
1787
1788 17
        if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
1789
            $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING);
1790
        }
1791
    }
1792
1793 39
    private function clearMergeCellsByRow(string $firstColumn, int $lastColumnIndex, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void
1794
    {
1795 39
        $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE)
1796 4
            ? [$this->getCell($upperLeft)->getFormattedValue()]
1797 35
            : [];
1798
1799 39
        foreach ($this->getRowIterator($firstRow, $lastRow) as $row) {
1800 39
            $iterator = $row->getCellIterator($firstColumn);
1801 39
            $iterator->setIterateOnlyExistingCells(true);
1802 39
            foreach ($iterator as $cell) {
1803 39
                if ($cell !== null) {
1804 39
                    $column = $cell->getColumn();
1805 39
                    $columnIndex = Coordinate::columnIndexFromString($column);
1806 39
                    if ($columnIndex > $lastColumnIndex) {
1807 8
                        break;
1808
                    }
1809 39
                    $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue);
1810
                }
1811
            }
1812
        }
1813
1814 39
        if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
1815 4
            $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING);
1816
        }
1817
    }
1818
1819 56
    public function mergeCellBehaviour(Cell $cell, string $upperLeft, string $behaviour, array $leftCellValue): array
1820
    {
1821 56
        if ($cell->getCoordinate() !== $upperLeft) {
1822 24
            Calculation::getInstance($cell->getWorksheet()->getParentOrThrow())->flushInstance();
1823 24
            if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
1824 4
                $cellValue = $cell->getFormattedValue();
1825 4
                if ($cellValue !== '') {
1826 4
                    $leftCellValue[] = $cellValue;
1827
                }
1828
            }
1829 24
            $cell->setValueExplicit(null, DataType::TYPE_NULL);
1830
        }
1831
1832 56
        return $leftCellValue;
1833
    }
1834
1835
    /**
1836
     * Remove merge on a cell range.
1837
     *
1838
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range A simple string containing a Cell range like 'A1:E10'
1839
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1840
     *              or an AddressRange.
1841
     *
1842
     * @return $this
1843
     */
1844 23
    public function unmergeCells(AddressRange|string|array $range): static
1845
    {
1846 23
        $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range));
1847
1848 23
        if (str_contains($range, ':')) {
1849 22
            if (isset($this->mergeCells[$range])) {
1850 22
                unset($this->mergeCells[$range]);
1851
            } else {
1852
                throw new Exception('Cell range ' . $range . ' not known as merged.');
1853
            }
1854
        } else {
1855 1
            throw new Exception('Merge can only be removed from a range of cells.');
1856
        }
1857
1858 22
        return $this;
1859
    }
1860
1861
    /**
1862
     * Get merge cells array.
1863
     *
1864
     * @return string[]
1865
     */
1866 1117
    public function getMergeCells(): array
1867
    {
1868 1117
        return $this->mergeCells;
1869
    }
1870
1871
    /**
1872
     * Set merge cells array for the entire sheet. Use instead mergeCells() to merge
1873
     * a single cell range.
1874
     *
1875
     * @param string[] $mergeCells
1876
     *
1877
     * @return $this
1878
     */
1879 94
    public function setMergeCells(array $mergeCells): static
1880
    {
1881 94
        $this->mergeCells = $mergeCells;
1882
1883 94
        return $this;
1884
    }
1885
1886
    /**
1887
     * Set protection on a cell or cell range.
1888
     *
1889
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $range A simple string containing a Cell range like 'A1:E10'
1890
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1891
     *              or a CellAddress or AddressRange object.
1892
     * @param string $password Password to unlock the protection
1893
     * @param bool $alreadyHashed If the password has already been hashed, set this to true
1894
     *
1895
     * @return $this
1896
     */
1897 24
    public function protectCells(AddressRange|CellAddress|int|string|array $range, string $password = '', bool $alreadyHashed = false, string $name = '', string $securityDescriptor = ''): static
1898
    {
1899 24
        $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range));
1900
1901 24
        if (!$alreadyHashed && $password !== '') {
1902 24
            $password = Shared\PasswordHasher::hashPassword($password);
1903
        }
1904 24
        $this->protectedCells[$range] = new ProtectedRange($range, $password, $name, $securityDescriptor);
1905
1906 24
        return $this;
1907
    }
1908
1909
    /**
1910
     * Remove protection on a cell or cell range.
1911
     *
1912
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $range A simple string containing a Cell range like 'A1:E10'
1913
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1914
     *              or a CellAddress or AddressRange object.
1915
     *
1916
     * @return $this
1917
     */
1918 20
    public function unprotectCells(AddressRange|CellAddress|int|string|array $range): static
1919
    {
1920 20
        $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range));
1921
1922 20
        if (isset($this->protectedCells[$range])) {
1923 19
            unset($this->protectedCells[$range]);
1924
        } else {
1925 1
            throw new Exception('Cell range ' . $range . ' not known as protected.');
1926
        }
1927
1928 19
        return $this;
1929
    }
1930
1931
    /**
1932
     * Get password for protected cells.
1933
     *
1934
     * @return string[]
1935
     *
1936
     * @deprecated 2.0.1 use getProtectedCellRanges instead
1937
     * @see Worksheet::getProtectedCellRanges()
1938
     */
1939 95
    public function getProtectedCells(): array
1940
    {
1941 95
        $array = [];
1942 95
        foreach ($this->protectedCells as $key => $protectedRange) {
1943 18
            $array[$key] = $protectedRange->getPassword();
1944
        }
1945
1946 95
        return $array;
1947
    }
1948
1949
    /**
1950
     * Get protected cells.
1951
     *
1952
     * @return ProtectedRange[]
1953
     */
1954 470
    public function getProtectedCellRanges(): array
1955
    {
1956 470
        return $this->protectedCells;
1957
    }
1958
1959
    /**
1960
     * Get Autofilter.
1961
     */
1962 739
    public function getAutoFilter(): AutoFilter
1963
    {
1964 739
        return $this->autoFilter;
1965
    }
1966
1967
    /**
1968
     * Set AutoFilter.
1969
     *
1970
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|AutoFilter|string $autoFilterOrRange
1971
     *            A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility
1972
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1973
     *              or an AddressRange.
1974
     *
1975
     * @return $this
1976
     */
1977 18
    public function setAutoFilter(AddressRange|string|array|AutoFilter $autoFilterOrRange): static
1978
    {
1979 18
        if (is_object($autoFilterOrRange) && ($autoFilterOrRange instanceof AutoFilter)) {
1980
            $this->autoFilter = $autoFilterOrRange;
1981
        } else {
1982 18
            $cellRange = Functions::trimSheetFromCellReference(Validations::validateCellRange($autoFilterOrRange));
1983
1984 18
            $this->autoFilter->setRange($cellRange);
1985
        }
1986
1987 18
        return $this;
1988
    }
1989
1990
    /**
1991
     * Remove autofilter.
1992
     */
1993 1
    public function removeAutoFilter(): self
1994
    {
1995 1
        $this->autoFilter->setRange('');
1996
1997 1
        return $this;
1998
    }
1999
2000
    /**
2001
     * Get collection of Tables.
2002
     *
2003
     * @return ArrayObject<int, Table>
2004
     */
2005 10030
    public function getTableCollection(): ArrayObject
2006
    {
2007 10030
        return $this->tableCollection;
2008
    }
2009
2010
    /**
2011
     * Add Table.
2012
     *
2013
     * @return $this
2014
     */
2015 97
    public function addTable(Table $table): self
2016
    {
2017 97
        $table->setWorksheet($this);
2018 97
        $this->tableCollection[] = $table;
2019
2020 97
        return $this;
2021
    }
2022
2023
    /**
2024
     * @return string[] array of Table names
2025
     */
2026 1
    public function getTableNames(): array
2027
    {
2028 1
        $tableNames = [];
2029
2030 1
        foreach ($this->tableCollection as $table) {
2031
            /** @var Table $table */
2032 1
            $tableNames[] = $table->getName();
2033
        }
2034
2035 1
        return $tableNames;
2036
    }
2037
2038
    /**
2039
     * @param string $name the table name to search
2040
     *
2041
     * @return null|Table The table from the tables collection, or null if not found
2042
     */
2043 92
    public function getTableByName(string $name): ?Table
2044
    {
2045 92
        $tableIndex = $this->getTableIndexByName($name);
2046
2047 92
        return ($tableIndex === null) ? null : $this->tableCollection[$tableIndex];
2048
    }
2049
2050
    /**
2051
     * @param string $name the table name to search
2052
     *
2053
     * @return null|int The index of the located table in the tables collection, or null if not found
2054
     */
2055 93
    protected function getTableIndexByName(string $name): ?int
2056
    {
2057 93
        $name = Shared\StringHelper::strToUpper($name);
2058 93
        foreach ($this->tableCollection as $index => $table) {
2059
            /** @var Table $table */
2060 62
            if (Shared\StringHelper::strToUpper($table->getName()) === $name) {
2061 61
                return $index;
2062
            }
2063
        }
2064
2065 37
        return null;
2066
    }
2067
2068
    /**
2069
     * Remove Table by name.
2070
     *
2071
     * @param string $name Table name
2072
     *
2073
     * @return $this
2074
     */
2075 1
    public function removeTableByName(string $name): self
2076
    {
2077 1
        $tableIndex = $this->getTableIndexByName($name);
2078
2079 1
        if ($tableIndex !== null) {
2080 1
            unset($this->tableCollection[$tableIndex]);
2081
        }
2082
2083 1
        return $this;
2084
    }
2085
2086
    /**
2087
     * Remove collection of Tables.
2088
     */
2089 1
    public function removeTableCollection(): self
2090
    {
2091 1
        $this->tableCollection = new ArrayObject();
2092
2093 1
        return $this;
2094
    }
2095
2096
    /**
2097
     * Get Freeze Pane.
2098
     */
2099 242
    public function getFreezePane(): ?string
2100
    {
2101 242
        return $this->freezePane;
2102
    }
2103
2104
    /**
2105
     * Freeze Pane.
2106
     *
2107
     * Examples:
2108
     *
2109
     *     - A2 will freeze the rows above cell A2 (i.e row 1)
2110
     *     - B1 will freeze the columns to the left of cell B1 (i.e column A)
2111
     *     - B2 will freeze the rows above and to the left of cell B2 (i.e row 1 and column A)
2112
     *
2113
     * @param null|array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
2114
     *            or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2115
     *        Passing a null value for this argument will clear any existing freeze pane for this worksheet.
2116
     * @param null|array{0: int, 1: int}|CellAddress|string $topLeftCell default position of the right bottom pane
2117
     *            Coordinate of the cell as a string, eg: 'C5'; or as an array of [$columnIndex, $row] (e.g. [3, 5]),
2118
     *            or a CellAddress object.
2119
     *
2120
     * @return $this
2121
     */
2122 49
    public function freezePane(null|CellAddress|string|array $coordinate, null|CellAddress|string|array $topLeftCell = null, bool $frozenSplit = false): static
2123
    {
2124 49
        $this->panes = [
2125 49
            'bottomRight' => null,
2126 49
            'bottomLeft' => null,
2127 49
            'topRight' => null,
2128 49
            'topLeft' => null,
2129 49
        ];
2130 49
        $cellAddress = ($coordinate !== null)
2131 49
            ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate))
2132 1
            : null;
2133 49
        if ($cellAddress !== null && Coordinate::coordinateIsRange($cellAddress)) {
2134 1
            throw new Exception('Freeze pane can not be set on a range of cells.');
2135
        }
2136 48
        $topLeftCell = ($topLeftCell !== null)
2137 37
            ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($topLeftCell))
2138 36
            : null;
2139
2140 48
        if ($cellAddress !== null && $topLeftCell === null) {
2141 36
            $coordinate = Coordinate::coordinateFromString($cellAddress);
2142 36
            $topLeftCell = $coordinate[0] . $coordinate[1];
2143
        }
2144
2145 48
        $topLeftCell = "$topLeftCell";
2146 48
        $this->paneTopLeftCell = $topLeftCell;
2147
2148 48
        $this->freezePane = $cellAddress;
2149 48
        $this->topLeftCell = $topLeftCell;
2150 48
        if ($cellAddress === null) {
2151 1
            $this->paneState = '';
2152 1
            $this->xSplit = $this->ySplit = 0;
2153 1
            $this->activePane = '';
2154
        } else {
2155 48
            $coordinates = Coordinate::indexesFromString($cellAddress);
2156 48
            $this->xSplit = $coordinates[0] - 1;
2157 48
            $this->ySplit = $coordinates[1] - 1;
2158 48
            if ($this->xSplit > 0 || $this->ySplit > 0) {
2159 47
                $this->paneState = $frozenSplit ? self::PANE_FROZENSPLIT : self::PANE_FROZEN;
2160 47
                $this->setSelectedCellsActivePane();
2161
            } else {
2162 1
                $this->paneState = '';
2163 1
                $this->freezePane = null;
2164 1
                $this->activePane = '';
2165
            }
2166
        }
2167
2168 48
        return $this;
2169
    }
2170
2171 47
    public function setTopLeftCell(string $topLeftCell): self
2172
    {
2173 47
        $this->topLeftCell = $topLeftCell;
2174
2175 47
        return $this;
2176
    }
2177
2178
    /**
2179
     * Unfreeze Pane.
2180
     *
2181
     * @return $this
2182
     */
2183 1
    public function unfreezePane(): static
2184
    {
2185 1
        return $this->freezePane(null);
2186
    }
2187
2188
    /**
2189
     * Get the default position of the right bottom pane.
2190
     */
2191 419
    public function getTopLeftCell(): ?string
2192
    {
2193 419
        return $this->topLeftCell;
2194
    }
2195
2196 11
    public function getPaneTopLeftCell(): string
2197
    {
2198 11
        return $this->paneTopLeftCell;
2199
    }
2200
2201 26
    public function setPaneTopLeftCell(string $paneTopLeftCell): self
2202
    {
2203 26
        $this->paneTopLeftCell = $paneTopLeftCell;
2204
2205 26
        return $this;
2206
    }
2207
2208 407
    public function usesPanes(): bool
2209
    {
2210 407
        return $this->xSplit > 0 || $this->ySplit > 0;
2211
    }
2212
2213 2
    public function getPane(string $position): ?Pane
2214
    {
2215 2
        return $this->panes[$position] ?? null;
2216
    }
2217
2218 35
    public function setPane(string $position, ?Pane $pane): self
2219
    {
2220 35
        if (array_key_exists($position, $this->panes)) {
2221 35
            $this->panes[$position] = $pane;
2222
        }
2223
2224 35
        return $this;
2225
    }
2226
2227
    /** @return (null|Pane)[] */
2228 3
    public function getPanes(): array
2229
    {
2230 3
        return $this->panes;
2231
    }
2232
2233 14
    public function getActivePane(): string
2234
    {
2235 14
        return $this->activePane;
2236
    }
2237
2238 48
    public function setActivePane(string $activePane): self
2239
    {
2240 48
        $this->activePane = array_key_exists($activePane, $this->panes) ? $activePane : '';
2241
2242 48
        return $this;
2243
    }
2244
2245 11
    public function getXSplit(): int
2246
    {
2247 11
        return $this->xSplit;
2248
    }
2249
2250 11
    public function setXSplit(int $xSplit): self
2251
    {
2252 11
        $this->xSplit = $xSplit;
2253 11
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
2254 1
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
2255
        }
2256
2257 11
        return $this;
2258
    }
2259
2260 11
    public function getYSplit(): int
2261
    {
2262 11
        return $this->ySplit;
2263
    }
2264
2265 26
    public function setYSplit(int $ySplit): self
2266
    {
2267 26
        $this->ySplit = $ySplit;
2268 26
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
2269 1
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
2270
        }
2271
2272 26
        return $this;
2273
    }
2274
2275 21
    public function getPaneState(): string
2276
    {
2277 21
        return $this->paneState;
2278
    }
2279
2280
    public const PANE_FROZEN = 'frozen';
2281
    public const PANE_FROZENSPLIT = 'frozenSplit';
2282
    public const PANE_SPLIT = 'split';
2283
    private const VALIDPANESTATE = [self::PANE_FROZEN, self::PANE_SPLIT, self::PANE_FROZENSPLIT];
2284
    private const VALIDFROZENSTATE = [self::PANE_FROZEN, self::PANE_FROZENSPLIT];
2285
2286 26
    public function setPaneState(string $paneState): self
2287
    {
2288 26
        $this->paneState = in_array($paneState, self::VALIDPANESTATE, true) ? $paneState : '';
2289 26
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
2290 25
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
2291
        } else {
2292 3
            $this->freezePane = null;
2293
        }
2294
2295 26
        return $this;
2296
    }
2297
2298
    /**
2299
     * Insert a new row, updating all possible related data.
2300
     *
2301
     * @param int $before Insert before this row number
2302
     * @param int $numberOfRows Number of new rows to insert
2303
     *
2304
     * @return $this
2305
     */
2306 38
    public function insertNewRowBefore(int $before, int $numberOfRows = 1): static
2307
    {
2308 38
        if ($before >= 1) {
2309 37
            $objReferenceHelper = ReferenceHelper::getInstance();
2310 37
            $objReferenceHelper->insertNewBefore('A' . $before, 0, $numberOfRows, $this);
2311
        } else {
2312 1
            throw new Exception('Rows can only be inserted before at least row 1.');
2313
        }
2314
2315 37
        return $this;
2316
    }
2317
2318
    /**
2319
     * Insert a new column, updating all possible related data.
2320
     *
2321
     * @param string $before Insert before this column Name, eg: 'A'
2322
     * @param int $numberOfColumns Number of new columns to insert
2323
     *
2324
     * @return $this
2325
     */
2326 45
    public function insertNewColumnBefore(string $before, int $numberOfColumns = 1): static
2327
    {
2328 45
        if (!is_numeric($before)) {
2329 44
            $objReferenceHelper = ReferenceHelper::getInstance();
2330 44
            $objReferenceHelper->insertNewBefore($before . '1', $numberOfColumns, 0, $this);
2331
        } else {
2332 1
            throw new Exception('Column references should not be numeric.');
2333
        }
2334
2335 44
        return $this;
2336
    }
2337
2338
    /**
2339
     * Insert a new column, updating all possible related data.
2340
     *
2341
     * @param int $beforeColumnIndex Insert before this column ID (numeric column coordinate of the cell)
2342
     * @param int $numberOfColumns Number of new columns to insert
2343
     *
2344
     * @return $this
2345
     */
2346 2
    public function insertNewColumnBeforeByIndex(int $beforeColumnIndex, int $numberOfColumns = 1): static
2347
    {
2348 2
        if ($beforeColumnIndex >= 1) {
2349 1
            return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $numberOfColumns);
2350
        }
2351
2352 1
        throw new Exception('Columns can only be inserted before at least column A (1).');
2353
    }
2354
2355
    /**
2356
     * Delete a row, updating all possible related data.
2357
     *
2358
     * @param int $row Remove rows, starting with this row number
2359
     * @param int $numberOfRows Number of rows to remove
2360
     *
2361
     * @return $this
2362
     */
2363 41
    public function removeRow(int $row, int $numberOfRows = 1): static
2364
    {
2365 41
        if ($row < 1) {
2366 1
            throw new Exception('Rows to be deleted should at least start from row 1.');
2367
        }
2368
2369 40
        $holdRowDimensions = $this->removeRowDimensions($row, $numberOfRows);
2370 40
        $highestRow = $this->getHighestDataRow();
2371 40
        $removedRowsCounter = 0;
2372
2373 40
        for ($r = 0; $r < $numberOfRows; ++$r) {
2374 40
            if ($row + $r <= $highestRow) {
2375 36
                $this->cellCollection->removeRow($row + $r);
2376 36
                ++$removedRowsCounter;
2377
            }
2378
        }
2379
2380 40
        $objReferenceHelper = ReferenceHelper::getInstance();
2381 40
        $objReferenceHelper->insertNewBefore('A' . ($row + $numberOfRows), 0, -$numberOfRows, $this);
2382 40
        for ($r = 0; $r < $removedRowsCounter; ++$r) {
2383 36
            $this->cellCollection->removeRow($highestRow);
2384 36
            --$highestRow;
2385
        }
2386
2387 40
        $this->rowDimensions = $holdRowDimensions;
2388
2389 40
        return $this;
2390
    }
2391
2392 40
    private function removeRowDimensions(int $row, int $numberOfRows): array
2393
    {
2394 40
        $highRow = $row + $numberOfRows - 1;
2395 40
        $holdRowDimensions = [];
2396 40
        foreach ($this->rowDimensions as $rowDimension) {
2397 4
            $num = $rowDimension->getRowIndex();
2398 4
            if ($num < $row) {
2399 3
                $holdRowDimensions[$num] = $rowDimension;
2400 4
            } elseif ($num > $highRow) {
2401 4
                $num -= $numberOfRows;
2402 4
                $cloneDimension = clone $rowDimension;
2403 4
                $cloneDimension->setRowIndex($num);
2404 4
                $holdRowDimensions[$num] = $cloneDimension;
2405
            }
2406
        }
2407
2408 40
        return $holdRowDimensions;
2409
    }
2410
2411
    /**
2412
     * Remove a column, updating all possible related data.
2413
     *
2414
     * @param string $column Remove columns starting with this column name, eg: 'A'
2415
     * @param int $numberOfColumns Number of columns to remove
2416
     *
2417
     * @return $this
2418
     */
2419 33
    public function removeColumn(string $column, int $numberOfColumns = 1): static
2420
    {
2421 33
        if (is_numeric($column)) {
2422 1
            throw new Exception('Column references should not be numeric.');
2423
        }
2424
2425 32
        $highestColumn = $this->getHighestDataColumn();
2426 32
        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
2427 32
        $pColumnIndex = Coordinate::columnIndexFromString($column);
2428
2429 32
        $holdColumnDimensions = $this->removeColumnDimensions($pColumnIndex, $numberOfColumns);
2430
2431 32
        $column = Coordinate::stringFromColumnIndex($pColumnIndex + $numberOfColumns);
2432 32
        $objReferenceHelper = ReferenceHelper::getInstance();
2433 32
        $objReferenceHelper->insertNewBefore($column . '1', -$numberOfColumns, 0, $this);
2434
2435 32
        $this->columnDimensions = $holdColumnDimensions;
2436
2437 32
        if ($pColumnIndex > $highestColumnIndex) {
2438 2
            return $this;
2439
        }
2440
2441 30
        $maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1;
2442
2443 30
        for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $numberOfColumns); $c < $n; ++$c) {
2444 30
            $this->cellCollection->removeColumn($highestColumn);
2445 30
            $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1);
2446
        }
2447
2448 30
        $this->garbageCollect();
2449
2450 30
        return $this;
2451
    }
2452
2453 32
    private function removeColumnDimensions(int $pColumnIndex, int $numberOfColumns): array
2454
    {
2455 32
        $highCol = $pColumnIndex + $numberOfColumns - 1;
2456 32
        $holdColumnDimensions = [];
2457 32
        foreach ($this->columnDimensions as $columnDimension) {
2458 18
            $num = $columnDimension->getColumnNumeric();
2459 18
            if ($num < $pColumnIndex) {
2460 18
                $str = $columnDimension->getColumnIndex();
2461 18
                $holdColumnDimensions[$str] = $columnDimension;
2462 18
            } elseif ($num > $highCol) {
2463 18
                $cloneDimension = clone $columnDimension;
2464 18
                $cloneDimension->setColumnNumeric($num - $numberOfColumns);
2465 18
                $str = $cloneDimension->getColumnIndex();
2466 18
                $holdColumnDimensions[$str] = $cloneDimension;
2467
            }
2468
        }
2469
2470 32
        return $holdColumnDimensions;
2471
    }
2472
2473
    /**
2474
     * Remove a column, updating all possible related data.
2475
     *
2476
     * @param int $columnIndex Remove starting with this column Index (numeric column coordinate)
2477
     * @param int $numColumns Number of columns to remove
2478
     *
2479
     * @return $this
2480
     */
2481 2
    public function removeColumnByIndex(int $columnIndex, int $numColumns = 1): static
2482
    {
2483 2
        if ($columnIndex >= 1) {
2484 1
            return $this->removeColumn(Coordinate::stringFromColumnIndex($columnIndex), $numColumns);
2485
        }
2486
2487 1
        throw new Exception('Columns to be deleted should at least start from column A (1)');
2488
    }
2489
2490
    /**
2491
     * Show gridlines?
2492
     */
2493 982
    public function getShowGridlines(): bool
2494
    {
2495 982
        return $this->showGridlines;
2496
    }
2497
2498
    /**
2499
     * Set show gridlines.
2500
     *
2501
     * @param bool $showGridLines Show gridlines (true/false)
2502
     *
2503
     * @return $this
2504
     */
2505 818
    public function setShowGridlines(bool $showGridLines): self
2506
    {
2507 818
        $this->showGridlines = $showGridLines;
2508
2509 818
        return $this;
2510
    }
2511
2512
    /**
2513
     * Print gridlines?
2514
     */
2515 988
    public function getPrintGridlines(): bool
2516
    {
2517 988
        return $this->printGridlines;
2518
    }
2519
2520
    /**
2521
     * Set print gridlines.
2522
     *
2523
     * @param bool $printGridLines Print gridlines (true/false)
2524
     *
2525
     * @return $this
2526
     */
2527 564
    public function setPrintGridlines(bool $printGridLines): self
2528
    {
2529 564
        $this->printGridlines = $printGridLines;
2530
2531 564
        return $this;
2532
    }
2533
2534
    /**
2535
     * Show row and column headers?
2536
     */
2537 467
    public function getShowRowColHeaders(): bool
2538
    {
2539 467
        return $this->showRowColHeaders;
2540
    }
2541
2542
    /**
2543
     * Set show row and column headers.
2544
     *
2545
     * @param bool $showRowColHeaders Show row and column headers (true/false)
2546
     *
2547
     * @return $this
2548
     */
2549 359
    public function setShowRowColHeaders(bool $showRowColHeaders): self
2550
    {
2551 359
        $this->showRowColHeaders = $showRowColHeaders;
2552
2553 359
        return $this;
2554
    }
2555
2556
    /**
2557
     * Show summary below? (Row/Column outlining).
2558
     */
2559 468
    public function getShowSummaryBelow(): bool
2560
    {
2561 468
        return $this->showSummaryBelow;
2562
    }
2563
2564
    /**
2565
     * Set show summary below.
2566
     *
2567
     * @param bool $showSummaryBelow Show summary below (true/false)
2568
     *
2569
     * @return $this
2570
     */
2571 364
    public function setShowSummaryBelow(bool $showSummaryBelow): self
2572
    {
2573 364
        $this->showSummaryBelow = $showSummaryBelow;
2574
2575 364
        return $this;
2576
    }
2577
2578
    /**
2579
     * Show summary right? (Row/Column outlining).
2580
     */
2581 468
    public function getShowSummaryRight(): bool
2582
    {
2583 468
        return $this->showSummaryRight;
2584
    }
2585
2586
    /**
2587
     * Set show summary right.
2588
     *
2589
     * @param bool $showSummaryRight Show summary right (true/false)
2590
     *
2591
     * @return $this
2592
     */
2593 364
    public function setShowSummaryRight(bool $showSummaryRight): self
2594
    {
2595 364
        $this->showSummaryRight = $showSummaryRight;
2596
2597 364
        return $this;
2598
    }
2599
2600
    /**
2601
     * Get comments.
2602
     *
2603
     * @return Comment[]
2604
     */
2605 1014
    public function getComments(): array
2606
    {
2607 1014
        return $this->comments;
2608
    }
2609
2610
    /**
2611
     * Set comments array for the entire sheet.
2612
     *
2613
     * @param Comment[] $comments
2614
     *
2615
     * @return $this
2616
     */
2617 94
    public function setComments(array $comments): self
2618
    {
2619 94
        $this->comments = $comments;
2620
2621 94
        return $this;
2622
    }
2623
2624
    /**
2625
     * Remove comment from cell.
2626
     *
2627
     * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5';
2628
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2629
     *
2630
     * @return $this
2631
     */
2632 44
    public function removeComment(CellAddress|string|array $cellCoordinate): self
2633
    {
2634 44
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate));
2635
2636 44
        if (Coordinate::coordinateIsRange($cellAddress)) {
2637 1
            throw new Exception('Cell coordinate string can not be a range of cells.');
2638 43
        } elseif (str_contains($cellAddress, '$')) {
2639 1
            throw new Exception('Cell coordinate string must not be absolute.');
2640 42
        } elseif ($cellAddress == '') {
2641 1
            throw new Exception('Cell coordinate can not be zero-length string.');
2642
        }
2643
        // Check if we have a comment for this cell and delete it
2644 41
        if (isset($this->comments[$cellAddress])) {
2645 2
            unset($this->comments[$cellAddress]);
2646
        }
2647
2648 41
        return $this;
2649
    }
2650
2651
    /**
2652
     * Get comment for cell.
2653
     *
2654
     * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5';
2655
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2656
     */
2657 108
    public function getComment(CellAddress|string|array $cellCoordinate, bool $attachNew = true): Comment
2658
    {
2659 108
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate));
2660
2661 108
        if (Coordinate::coordinateIsRange($cellAddress)) {
2662 1
            throw new Exception('Cell coordinate string can not be a range of cells.');
2663 107
        } elseif (str_contains($cellAddress, '$')) {
2664 1
            throw new Exception('Cell coordinate string must not be absolute.');
2665 106
        } elseif ($cellAddress == '') {
2666 1
            throw new Exception('Cell coordinate can not be zero-length string.');
2667
        }
2668
2669
        // Check if we already have a comment for this cell.
2670 105
        if (isset($this->comments[$cellAddress])) {
2671 72
            return $this->comments[$cellAddress];
2672
        }
2673
2674
        // If not, create a new comment.
2675 105
        $newComment = new Comment();
2676 105
        if ($attachNew) {
2677 105
            $this->comments[$cellAddress] = $newComment;
2678
        }
2679
2680 105
        return $newComment;
2681
    }
2682
2683
    /**
2684
     * Get active cell.
2685
     *
2686
     * @return string Example: 'A1'
2687
     */
2688 10069
    public function getActiveCell(): string
2689
    {
2690 10069
        return $this->activeCell;
2691
    }
2692
2693
    /**
2694
     * Get selected cells.
2695
     */
2696 10112
    public function getSelectedCells(): string
2697
    {
2698 10112
        return $this->selectedCells;
2699
    }
2700
2701
    /**
2702
     * Selected cell.
2703
     *
2704
     * @param string $coordinate Cell (i.e. A1)
2705
     *
2706
     * @return $this
2707
     */
2708 36
    public function setSelectedCell(string $coordinate): static
2709
    {
2710 36
        return $this->setSelectedCells($coordinate);
2711
    }
2712
2713
    /**
2714
     * Select a range of cells.
2715
     *
2716
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $coordinate A simple string containing a Cell range like 'A1:E10'
2717
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
2718
     *              or a CellAddress or AddressRange object.
2719
     *
2720
     * @return $this
2721
     */
2722 10092
    public function setSelectedCells(AddressRange|CellAddress|int|string|array $coordinate): static
2723
    {
2724 10092
        if (is_string($coordinate)) {
2725 10092
            $coordinate = Validations::definedNameToCoordinate($coordinate, $this);
2726
        }
2727 10092
        $coordinate = Validations::validateCellOrCellRange($coordinate);
2728
2729 10092
        if (Coordinate::coordinateIsRange($coordinate)) {
2730 481
            [$first] = Coordinate::splitRange($coordinate);
2731 481
            $this->activeCell = $first[0];
2732
        } else {
2733 10061
            $this->activeCell = $coordinate;
2734
        }
2735 10092
        $this->selectedCells = $coordinate;
2736 10092
        $this->setSelectedCellsActivePane();
2737
2738 10092
        return $this;
2739
    }
2740
2741 10093
    private function setSelectedCellsActivePane(): void
2742
    {
2743 10093
        if (!empty($this->freezePane)) {
2744 47
            $coordinateC = Coordinate::indexesFromString($this->freezePane);
2745 47
            $coordinateT = Coordinate::indexesFromString($this->activeCell);
2746 47
            if ($coordinateC[0] === 1) {
2747 26
                $activePane = ($coordinateT[1] <= $coordinateC[1]) ? 'topLeft' : 'bottomLeft';
2748 23
            } elseif ($coordinateC[1] === 1) {
2749 3
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight';
2750 21
            } elseif ($coordinateT[1] <= $coordinateC[1]) {
2751 21
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight';
2752
            } else {
2753 10
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'bottomLeft' : 'bottomRight';
2754
            }
2755 47
            $this->setActivePane($activePane);
2756 47
            $this->panes[$activePane] = new Pane($activePane, $this->selectedCells, $this->activeCell);
2757
        }
2758
    }
2759
2760
    /**
2761
     * Get right-to-left.
2762
     */
2763 467
    public function getRightToLeft(): bool
2764
    {
2765 467
        return $this->rightToLeft;
2766
    }
2767
2768
    /**
2769
     * Set right-to-left.
2770
     *
2771
     * @param bool $value Right-to-left true/false
2772
     *
2773
     * @return $this
2774
     */
2775 129
    public function setRightToLeft(bool $value): static
2776
    {
2777 129
        $this->rightToLeft = $value;
2778
2779 129
        return $this;
2780
    }
2781
2782
    /**
2783
     * Fill worksheet from values in array.
2784
     *
2785
     * @param array $source Source array
2786
     * @param mixed $nullValue Value in source array that stands for blank cell
2787
     * @param string $startCell Insert array starting from this cell address as the top left coordinate
2788
     * @param bool $strictNullComparison Apply strict comparison when testing for null values in the array
2789
     *
2790
     * @return $this
2791
     */
2792 743
    public function fromArray(array $source, mixed $nullValue = null, string $startCell = 'A1', bool $strictNullComparison = false): static
2793
    {
2794
        //    Convert a 1-D array to 2-D (for ease of looping)
2795 743
        if (!is_array(end($source))) {
2796 42
            $source = [$source];
2797
        }
2798
2799
        // start coordinate
2800 743
        [$startColumn, $startRow] = Coordinate::coordinateFromString($startCell);
2801
2802
        // Loop through $source
2803 743
        if ($strictNullComparison) {
2804 346
            foreach ($source as $rowData) {
2805 346
                $currentColumn = $startColumn;
2806 346
                foreach ($rowData as $cellValue) {
2807 346
                    if ($cellValue !== $nullValue) {
2808
                        // Set cell value
2809 346
                        $this->getCell($currentColumn . $startRow)->setValue($cellValue);
2810
                    }
2811 346
                    ++$currentColumn;
2812
                }
2813 346
                ++$startRow;
2814
            }
2815
        } else {
2816 398
            foreach ($source as $rowData) {
2817 398
                $currentColumn = $startColumn;
2818 398
                foreach ($rowData as $cellValue) {
2819 397
                    if ($cellValue != $nullValue) {
2820
                        // Set cell value
2821 391
                        $this->getCell($currentColumn . $startRow)->setValue($cellValue);
2822
                    }
2823 397
                    ++$currentColumn;
2824
                }
2825 398
                ++$startRow;
2826
            }
2827
        }
2828
2829 743
        return $this;
2830
    }
2831
2832
    /**
2833
     * @param null|bool|float|int|RichText|string $nullValue value to use when null
2834
     *
2835
     * @throws Exception
2836
     * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
2837
     */
2838 166
    protected function cellToArray(Cell $cell, bool $calculateFormulas, bool $formatData, mixed $nullValue): mixed
2839
    {
2840 166
        $returnValue = $nullValue;
2841
2842 166
        if ($cell->getValue() !== null) {
2843 166
            if ($cell->getValue() instanceof RichText) {
2844 4
                $returnValue = $cell->getValue()->getPlainText();
2845
            } else {
2846 166
                $returnValue = ($calculateFormulas) ? $cell->getCalculatedValue() : $cell->getValue();
2847
            }
2848
2849 166
            if ($formatData) {
2850 106
                $style = $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex());
2851
                /** @var null|bool|float|int|RichText|string */
2852 106
                $returnValuex = $returnValue;
2853 106
                $returnValue = NumberFormat::toFormattedString(
2854 106
                    $returnValuex,
2855 106
                    $style->getNumberFormat()->getFormatCode() ?? NumberFormat::FORMAT_GENERAL
2856 106
                );
2857
            }
2858
        }
2859
2860 166
        return $returnValue;
2861
    }
2862
2863
    /**
2864
     * Create array from a range of cells.
2865
     *
2866
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
2867
     * @param bool $calculateFormulas Should formulas be calculated?
2868
     * @param bool $formatData Should formatting be applied to cell values?
2869
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2870
     *                             True - Return rows and columns indexed by their actual row and column IDs
2871
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2872
     *                            True - Don't return values for rows/columns that are defined as hidden.
2873
     */
2874 139
    public function rangeToArray(
2875
        string $range,
2876
        mixed $nullValue = null,
2877
        bool $calculateFormulas = true,
2878
        bool $formatData = true,
2879
        bool $returnCellRef = false,
2880
        bool $ignoreHidden = false,
2881
        bool $reduceArrays = false
2882
    ): array {
2883 139
        $returnValue = [];
2884
2885
        // Loop through rows
2886 139
        foreach ($this->rangeToArrayYieldRows($range, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays) as $rowRef => $rowArray) {
2887 139
            $returnValue[$rowRef] = $rowArray;
2888
        }
2889
2890
        // Return
2891 139
        return $returnValue;
2892
    }
2893
2894
    /**
2895
     * Create array from a range of cells, yielding each row in turn.
2896
     *
2897
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
2898
     * @param bool $calculateFormulas Should formulas be calculated?
2899
     * @param bool $formatData Should formatting be applied to cell values?
2900
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2901
     *                             True - Return rows and columns indexed by their actual row and column IDs
2902
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2903
     *                            True - Don't return values for rows/columns that are defined as hidden.
2904
     *
2905
     * @return Generator<array>
2906
     */
2907 166
    public function rangeToArrayYieldRows(
2908
        string $range,
2909
        mixed $nullValue = null,
2910
        bool $calculateFormulas = true,
2911
        bool $formatData = true,
2912
        bool $returnCellRef = false,
2913
        bool $ignoreHidden = false,
2914
        bool $reduceArrays = false
2915
    ) {
2916 166
        $range = Validations::validateCellOrCellRange($range);
2917
2918
        //    Identify the range that we need to extract from the worksheet
2919 166
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
2920 166
        $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]);
2921 166
        $minRow = $rangeStart[1];
2922 166
        $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]);
2923 166
        $maxRow = $rangeEnd[1];
2924 166
        $minColInt = $rangeStart[0];
2925 166
        $maxColInt = $rangeEnd[0];
2926
2927 166
        ++$maxCol;
2928
        /** @var array<string, bool> */
2929 166
        $hiddenColumns = [];
2930 166
        $nullRow = $this->buildNullRow($nullValue, $minCol, $maxCol, $returnCellRef, $ignoreHidden, $hiddenColumns);
2931 166
        $hideColumns = !empty($hiddenColumns);
2932
2933 166
        $keys = $this->cellCollection->getSortedCoordinatesInt();
2934 166
        $keyIndex = 0;
2935 166
        $keysCount = count($keys);
2936
        // Loop through rows
2937 166
        for ($row = $minRow; $row <= $maxRow; ++$row) {
2938 166
            if (($ignoreHidden === true) && ($this->isRowVisible($row) === false)) {
2939 4
                continue;
2940
            }
2941 166
            $rowRef = $returnCellRef ? $row : ($row - $minRow);
2942 166
            $returnValue = $nullRow;
2943
2944 166
            $index = ($row - 1) * AddressRange::MAX_COLUMN_INT + 1;
2945 166
            $indexPlus = $index + AddressRange::MAX_COLUMN_INT - 1;
2946 166
            while ($keyIndex < $keysCount && $keys[$keyIndex] < $index) {
2947 49
                ++$keyIndex;
2948
            }
2949 166
            while ($keyIndex < $keysCount && $keys[$keyIndex] <= $indexPlus) {
2950 166
                $key = $keys[$keyIndex];
2951 166
                $thisRow = intdiv($key - 1, AddressRange::MAX_COLUMN_INT) + 1;
2952 166
                $thisCol = ($key % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT;
2953 166
                if ($thisCol >= $minColInt && $thisCol <= $maxColInt) {
2954 166
                    $col = Coordinate::stringFromColumnIndex($thisCol);
2955 166
                    if ($hideColumns === false || !isset($hiddenColumns[$col])) {
2956 166
                        $columnRef = $returnCellRef ? $col : ($thisCol - $minColInt);
2957 166
                        $cell = $this->cellCollection->get("{$col}{$thisRow}");
2958 166
                        if ($cell !== null) {
2959 166
                            $value = $this->cellToArray($cell, $calculateFormulas, $formatData, $nullValue);
2960 166
                            if ($reduceArrays) {
2961 21
                                while (is_array($value)) {
2962 18
                                    $value = array_shift($value);
2963
                                }
2964
                            }
2965 166
                            if ($value !== $nullValue) {
2966 166
                                $returnValue[$columnRef] = $value;
2967
                            }
2968
                        }
2969
                    }
2970
                }
2971 166
                ++$keyIndex;
2972
            }
2973
2974 166
            yield $rowRef => $returnValue;
2975
        }
2976
    }
2977
2978
    /**
2979
     * Prepare a row data filled with null values to deduplicate the memory areas for empty rows.
2980
     *
2981
     * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
2982
     * @param string $minCol Start column of the range
2983
     * @param string $maxCol End column of the range
2984
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2985
     *                              True - Return rows and columns indexed by their actual row and column IDs
2986
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2987
     *                             True - Don't return values for rows/columns that are defined as hidden.
2988
     * @param array<string, bool> $hiddenColumns
2989
     */
2990 166
    private function buildNullRow(
2991
        mixed $nullValue,
2992
        string $minCol,
2993
        string $maxCol,
2994
        bool $returnCellRef,
2995
        bool $ignoreHidden,
2996
        array &$hiddenColumns
2997
    ): array {
2998 166
        $nullRow = [];
2999 166
        $c = -1;
3000 166
        for ($col = $minCol; $col !== $maxCol; ++$col) {
3001 166
            if ($ignoreHidden === true && $this->columnDimensionExists($col) && $this->getColumnDimension($col)->getVisible() === false) {
3002 2
                $hiddenColumns[$col] = true;
3003
            } else {
3004 166
                $columnRef = $returnCellRef ? $col : ++$c;
3005 166
                $nullRow[$columnRef] = $nullValue;
3006
            }
3007
        }
3008
3009 166
        return $nullRow;
3010
    }
3011
3012 17
    private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName
3013
    {
3014 17
        $namedRange = DefinedName::resolveName($definedName, $this);
3015 17
        if ($namedRange === null) {
3016 6
            if ($returnNullIfInvalid) {
3017 5
                return null;
3018
            }
3019
3020 1
            throw new Exception('Named Range ' . $definedName . ' does not exist.');
3021
        }
3022
3023 11
        if ($namedRange->isFormula()) {
3024
            if ($returnNullIfInvalid) {
3025
                return null;
3026
            }
3027
3028
            throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.');
3029
        }
3030
3031 11
        if ($namedRange->getLocalOnly()) {
3032 2
            $worksheet = $namedRange->getWorksheet();
3033 2
            if ($worksheet === null || $this->hash !== $worksheet->getHashInt()) {
3034
                if ($returnNullIfInvalid) {
3035
                    return null;
3036
                }
3037
3038
                throw new Exception(
3039
                    'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle()
3040
                );
3041
            }
3042
        }
3043
3044 11
        return $namedRange;
3045
    }
3046
3047
    /**
3048
     * Create array from a range of cells.
3049
     *
3050
     * @param string $definedName The Named Range that should be returned
3051
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3052
     * @param bool $calculateFormulas Should formulas be calculated?
3053
     * @param bool $formatData Should formatting be applied to cell values?
3054
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3055
     *                             True - Return rows and columns indexed by their actual row and column IDs
3056
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3057
     *                            True - Don't return values for rows/columns that are defined as hidden.
3058
     */
3059 2
    public function namedRangeToArray(
3060
        string $definedName,
3061
        mixed $nullValue = null,
3062
        bool $calculateFormulas = true,
3063
        bool $formatData = true,
3064
        bool $returnCellRef = false,
3065
        bool $ignoreHidden = false,
3066
        bool $reduceArrays = false
3067
    ): array {
3068 2
        $retVal = [];
3069 2
        $namedRange = $this->validateNamedRange($definedName);
3070 1
        if ($namedRange !== null) {
3071 1
            $cellRange = ltrim(substr($namedRange->getValue(), (int) strrpos($namedRange->getValue(), '!')), '!');
3072 1
            $cellRange = str_replace('$', '', $cellRange);
3073 1
            $workSheet = $namedRange->getWorksheet();
3074 1
            if ($workSheet !== null) {
3075 1
                $retVal = $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays);
3076
            }
3077
        }
3078
3079 1
        return $retVal;
3080
    }
3081
3082
    /**
3083
     * Create array from worksheet.
3084
     *
3085
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3086
     * @param bool $calculateFormulas Should formulas be calculated?
3087
     * @param bool $formatData Should formatting be applied to cell values?
3088
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3089
     *                             True - Return rows and columns indexed by their actual row and column IDs
3090
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3091
     *                            True - Don't return values for rows/columns that are defined as hidden.
3092
     */
3093 72
    public function toArray(
3094
        mixed $nullValue = null,
3095
        bool $calculateFormulas = true,
3096
        bool $formatData = true,
3097
        bool $returnCellRef = false,
3098
        bool $ignoreHidden = false,
3099
        bool $reduceArrays = false
3100
    ): array {
3101
        // Garbage collect...
3102 72
        $this->garbageCollect();
3103 72
        $this->calculateArrays($calculateFormulas);
3104
3105
        //    Identify the range that we need to extract from the worksheet
3106 72
        $maxCol = $this->getHighestColumn();
3107 72
        $maxRow = $this->getHighestRow();
3108
3109
        // Return
3110 72
        return $this->rangeToArray("A1:{$maxCol}{$maxRow}", $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays);
3111
    }
3112
3113
    /**
3114
     * Get row iterator.
3115
     *
3116
     * @param int $startRow The row number at which to start iterating
3117
     * @param ?int $endRow The row number at which to stop iterating
3118
     */
3119 86
    public function getRowIterator(int $startRow = 1, ?int $endRow = null): RowIterator
3120
    {
3121 86
        return new RowIterator($this, $startRow, $endRow);
3122
    }
3123
3124
    /**
3125
     * Get column iterator.
3126
     *
3127
     * @param string $startColumn The column address at which to start iterating
3128
     * @param ?string $endColumn The column address at which to stop iterating
3129
     */
3130 25
    public function getColumnIterator(string $startColumn = 'A', ?string $endColumn = null): ColumnIterator
3131
    {
3132 25
        return new ColumnIterator($this, $startColumn, $endColumn);
3133
    }
3134
3135
    /**
3136
     * Run PhpSpreadsheet garbage collector.
3137
     *
3138
     * @return $this
3139
     */
3140 1097
    public function garbageCollect(): static
3141
    {
3142
        // Flush cache
3143 1097
        $this->cellCollection->get('A1');
3144
3145
        // Lookup highest column and highest row if cells are cleaned
3146 1097
        $colRow = $this->cellCollection->getHighestRowAndColumn();
3147 1097
        $highestRow = $colRow['row'];
3148 1097
        $highestColumn = Coordinate::columnIndexFromString($colRow['column']);
3149
3150
        // Loop through column dimensions
3151 1097
        foreach ($this->columnDimensions as $dimension) {
3152 152
            $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex()));
3153
        }
3154
3155
        // Loop through row dimensions
3156 1097
        foreach ($this->rowDimensions as $dimension) {
3157 94
            $highestRow = max($highestRow, $dimension->getRowIndex());
3158
        }
3159
3160
        // Cache values
3161 1097
        if ($highestColumn < 1) {
3162
            $this->cachedHighestColumn = 1;
3163
        } else {
3164 1097
            $this->cachedHighestColumn = $highestColumn;
3165
        }
3166 1097
        $this->cachedHighestRow = $highestRow;
3167
3168
        // Return
3169 1097
        return $this;
3170
    }
3171
3172
    /**
3173
     * @deprecated 3.5.0 use getHashInt instead.
3174
     */
3175
    public function getHashCode(): string
3176
    {
3177
        return (string) $this->hash;
3178
    }
3179
3180 10408
    public function getHashInt(): int
3181
    {
3182 10408
        return $this->hash;
3183
    }
3184
3185
    /**
3186
     * Extract worksheet title from range.
3187
     *
3188
     * Example: extractSheetTitle("testSheet!A1") ==> 'A1'
3189
     * Example: extractSheetTitle("testSheet!A1:C3") ==> 'A1:C3'
3190
     * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1'];
3191
     * Example: extractSheetTitle("'testSheet 1'!A1:C3", true) ==> ['testSheet 1', 'A1:C3'];
3192
     * Example: extractSheetTitle("A1", true) ==> ['', 'A1'];
3193
     * Example: extractSheetTitle("A1:C3", true) ==> ['', 'A1:C3']
3194
     *
3195
     * @param ?string $range Range to extract title from
3196
     * @param bool $returnRange Return range? (see example)
3197
     *
3198
     * @return ($range is non-empty-string ? ($returnRange is true ? array{0: string, 1: string} : string) : ($returnRange is true ? array{0: null, 1: null} : null))
3199
     */
3200 10294
    public static function extractSheetTitle(?string $range, bool $returnRange = false): array|null|string
3201
    {
3202 10294
        if (empty($range)) {
3203 13
            return $returnRange ? [null, null] : null;
3204
        }
3205
3206
        // Sheet title included?
3207 10292
        if (($sep = strrpos($range, '!')) === false) {
3208 10266
            return $returnRange ? ['', $range] : '';
3209
        }
3210
3211 1329
        if ($returnRange) {
3212 1329
            return [substr($range, 0, $sep), substr($range, $sep + 1)];
3213
        }
3214
3215 7
        return substr($range, $sep + 1);
3216
    }
3217
3218
    /**
3219
     * Get hyperlink.
3220
     *
3221
     * @param string $cellCoordinate Cell coordinate to get hyperlink for, eg: 'A1'
3222
     */
3223 90
    public function getHyperlink(string $cellCoordinate): Hyperlink
3224
    {
3225
        // return hyperlink if we already have one
3226 90
        if (isset($this->hyperlinkCollection[$cellCoordinate])) {
3227 42
            return $this->hyperlinkCollection[$cellCoordinate];
3228
        }
3229
3230
        // else create hyperlink
3231 90
        $this->hyperlinkCollection[$cellCoordinate] = new Hyperlink();
3232
3233 90
        return $this->hyperlinkCollection[$cellCoordinate];
3234
    }
3235
3236
    /**
3237
     * Set hyperlink.
3238
     *
3239
     * @param string $cellCoordinate Cell coordinate to insert hyperlink, eg: 'A1'
3240
     *
3241
     * @return $this
3242
     */
3243 42
    public function setHyperlink(string $cellCoordinate, ?Hyperlink $hyperlink = null): static
3244
    {
3245 42
        if ($hyperlink === null) {
3246 41
            unset($this->hyperlinkCollection[$cellCoordinate]);
3247
        } else {
3248 21
            $this->hyperlinkCollection[$cellCoordinate] = $hyperlink;
3249
        }
3250
3251 42
        return $this;
3252
    }
3253
3254
    /**
3255
     * Hyperlink at a specific coordinate exists?
3256
     *
3257
     * @param string $coordinate eg: 'A1'
3258
     */
3259 530
    public function hyperlinkExists(string $coordinate): bool
3260
    {
3261 530
        return isset($this->hyperlinkCollection[$coordinate]);
3262
    }
3263
3264
    /**
3265
     * Get collection of hyperlinks.
3266
     *
3267
     * @return Hyperlink[]
3268
     */
3269 545
    public function getHyperlinkCollection(): array
3270
    {
3271 545
        return $this->hyperlinkCollection;
3272
    }
3273
3274
    /**
3275
     * Get data validation.
3276
     *
3277
     * @param string $cellCoordinate Cell coordinate to get data validation for, eg: 'A1'
3278
     */
3279 34
    public function getDataValidation(string $cellCoordinate): DataValidation
3280
    {
3281
        // return data validation if we already have one
3282 34
        if (isset($this->dataValidationCollection[$cellCoordinate])) {
3283 25
            return $this->dataValidationCollection[$cellCoordinate];
3284
        }
3285
3286
        // or if cell is part of a data validation range
3287 27
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
3288 12
            $keyParts = explode(' ', $key);
3289 12
            foreach ($keyParts as $keyPart) {
3290 12
                if ($keyPart === $cellCoordinate) {
3291 1
                    return $dataValidation;
3292
                }
3293 12
                if (str_contains($keyPart, ':')) {
3294 9
                    if (Coordinate::coordinateIsInsideRange($keyPart, $cellCoordinate)) {
3295 9
                        return $dataValidation;
3296
                    }
3297
                }
3298
            }
3299
        }
3300
3301
        // else create data validation
3302 19
        $dataValidation = new DataValidation();
3303 19
        $dataValidation->setSqref($cellCoordinate);
3304 19
        $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
3305
3306 19
        return $dataValidation;
3307
    }
3308
3309
    /**
3310
     * Set data validation.
3311
     *
3312
     * @param string $cellCoordinate Cell coordinate to insert data validation, eg: 'A1'
3313
     *
3314
     * @return $this
3315
     */
3316 74
    public function setDataValidation(string $cellCoordinate, ?DataValidation $dataValidation = null): static
3317
    {
3318 74
        if ($dataValidation === null) {
3319 46
            unset($this->dataValidationCollection[$cellCoordinate]);
3320
        } else {
3321 35
            $dataValidation->setSqref($cellCoordinate);
3322 35
            $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
3323
        }
3324
3325 74
        return $this;
3326
    }
3327
3328
    /**
3329
     * Data validation at a specific coordinate exists?
3330
     *
3331
     * @param string $coordinate eg: 'A1'
3332
     */
3333 24
    public function dataValidationExists(string $coordinate): bool
3334
    {
3335 24
        if (isset($this->dataValidationCollection[$coordinate])) {
3336 22
            return true;
3337
        }
3338 8
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
3339 7
            $keyParts = explode(' ', $key);
3340 7
            foreach ($keyParts as $keyPart) {
3341 7
                if ($keyPart === $coordinate) {
3342 1
                    return true;
3343
                }
3344 7
                if (str_contains($keyPart, ':')) {
3345 2
                    if (Coordinate::coordinateIsInsideRange($keyPart, $coordinate)) {
3346 2
                        return true;
3347
                    }
3348
                }
3349
            }
3350
        }
3351
3352 6
        return false;
3353
    }
3354
3355
    /**
3356
     * Get collection of data validations.
3357
     *
3358
     * @return DataValidation[]
3359
     */
3360 546
    public function getDataValidationCollection(): array
3361
    {
3362 546
        $collectionCells = [];
3363 546
        $collectionRanges = [];
3364 546
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
3365 24
            if (preg_match('/[: ]/', $key) === 1) {
3366 14
                $collectionRanges[$key] = $dataValidation;
3367
            } else {
3368 19
                $collectionCells[$key] = $dataValidation;
3369
            }
3370
        }
3371
3372 546
        return array_merge($collectionCells, $collectionRanges);
3373
    }
3374
3375
    /**
3376
     * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet.
3377
     *
3378
     * @return string Adjusted range value
3379
     */
3380
    public function shrinkRangeToFit(string $range): string
3381
    {
3382
        $maxCol = $this->getHighestColumn();
3383
        $maxRow = $this->getHighestRow();
3384
        $maxCol = Coordinate::columnIndexFromString($maxCol);
3385
3386
        $rangeBlocks = explode(' ', $range);
3387
        foreach ($rangeBlocks as &$rangeSet) {
3388
            $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet);
3389
3390
            if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) {
3391
                $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol);
3392
            }
3393
            if ($rangeBoundaries[0][1] > $maxRow) {
3394
                $rangeBoundaries[0][1] = $maxRow;
3395
            }
3396
            if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) {
3397
                $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol);
3398
            }
3399
            if ($rangeBoundaries[1][1] > $maxRow) {
3400
                $rangeBoundaries[1][1] = $maxRow;
3401
            }
3402
            $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1];
3403
        }
3404
        unset($rangeSet);
3405
3406
        return implode(' ', $rangeBlocks);
3407
    }
3408
3409
    /**
3410
     * Get tab color.
3411
     */
3412 23
    public function getTabColor(): Color
3413
    {
3414 23
        if ($this->tabColor === null) {
3415 23
            $this->tabColor = new Color();
3416
        }
3417
3418 23
        return $this->tabColor;
3419
    }
3420
3421
    /**
3422
     * Reset tab color.
3423
     *
3424
     * @return $this
3425
     */
3426 1
    public function resetTabColor(): static
3427
    {
3428 1
        $this->tabColor = null;
3429
3430 1
        return $this;
3431
    }
3432
3433
    /**
3434
     * Tab color set?
3435
     */
3436 469
    public function isTabColorSet(): bool
3437
    {
3438 469
        return $this->tabColor !== null;
3439
    }
3440
3441
    /**
3442
     * Copy worksheet (!= clone!).
3443
     */
3444
    public function copy(): static
3445
    {
3446
        return clone $this;
3447
    }
3448
3449
    /**
3450
     * Returns a boolean true if the specified row contains no cells. By default, this means that no cell records
3451
     *          exist in the collection for this row. false will be returned otherwise.
3452
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3453
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3454
     *                  cells, then the row will be considered empty.
3455
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3456
     *                  string value cells, then the row will be considered empty.
3457
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3458
     *                  If the only cells in the collection are null value or empty string value cells, then the row
3459
     *                  will be considered empty.
3460
     *
3461
     * @param int $definitionOfEmptyFlags
3462
     *              Possible Flag Values are:
3463
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3464
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3465
     */
3466 9
    public function isEmptyRow(int $rowId, int $definitionOfEmptyFlags = 0): bool
3467
    {
3468
        try {
3469 9
            $iterator = new RowIterator($this, $rowId, $rowId);
3470 8
            $iterator->seek($rowId);
3471 8
            $row = $iterator->current();
3472 1
        } catch (Exception) {
3473 1
            return true;
3474
        }
3475
3476 8
        return $row->isEmpty($definitionOfEmptyFlags);
3477
    }
3478
3479
    /**
3480
     * Returns a boolean true if the specified column contains no cells. By default, this means that no cell records
3481
     *          exist in the collection for this column. false will be returned otherwise.
3482
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3483
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3484
     *                  cells, then the column will be considered empty.
3485
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3486
     *                  string value cells, then the column will be considered empty.
3487
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3488
     *                  If the only cells in the collection are null value or empty string value cells, then the column
3489
     *                  will be considered empty.
3490
     *
3491
     * @param int $definitionOfEmptyFlags
3492
     *              Possible Flag Values are:
3493
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3494
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3495
     */
3496 9
    public function isEmptyColumn(string $columnId, int $definitionOfEmptyFlags = 0): bool
3497
    {
3498
        try {
3499 9
            $iterator = new ColumnIterator($this, $columnId, $columnId);
3500 8
            $iterator->seek($columnId);
3501 8
            $column = $iterator->current();
3502 1
        } catch (Exception) {
3503 1
            return true;
3504
        }
3505
3506 8
        return $column->isEmpty($definitionOfEmptyFlags);
3507
    }
3508
3509
    /**
3510
     * Implement PHP __clone to create a deep clone, not just a shallow copy.
3511
     */
3512 15
    public function __clone()
3513
    {
3514
        // @phpstan-ignore-next-line
3515 15
        foreach ($this as $key => $val) {
3516 15
            if ($key == 'parent') {
3517 15
                continue;
3518
            }
3519
3520 15
            if (is_object($val) || (is_array($val))) {
3521 15
                if ($key == 'cellCollection') {
3522 15
                    $newCollection = $this->cellCollection->cloneCellCollection($this);
3523 15
                    $this->cellCollection = $newCollection;
3524 15
                } elseif ($key == 'drawingCollection') {
3525 15
                    $currentCollection = $this->drawingCollection;
3526 15
                    $this->drawingCollection = new ArrayObject();
3527 15
                    foreach ($currentCollection as $item) {
3528 4
                        $newDrawing = clone $item;
3529 4
                        $newDrawing->setWorksheet($this);
3530
                    }
3531 15
                } elseif ($key == 'tableCollection') {
3532 15
                    $currentCollection = $this->tableCollection;
3533 15
                    $this->tableCollection = new ArrayObject();
3534 15
                    foreach ($currentCollection as $item) {
3535 1
                        $newTable = clone $item;
3536 1
                        $newTable->setName($item->getName() . 'clone');
3537 1
                        $this->addTable($newTable);
3538
                    }
3539 15
                } elseif ($key == 'chartCollection') {
3540 15
                    $currentCollection = $this->chartCollection;
3541 15
                    $this->chartCollection = new ArrayObject();
3542 15
                    foreach ($currentCollection as $item) {
3543 5
                        $newChart = clone $item;
3544 5
                        $this->addChart($newChart);
3545
                    }
3546 15
                } elseif (($key == 'autoFilter') && ($this->autoFilter instanceof AutoFilter)) {
3547 15
                    $newAutoFilter = clone $this->autoFilter;
3548 15
                    $this->autoFilter = $newAutoFilter;
3549 15
                    $this->autoFilter->setParent($this);
3550
                } else {
3551 15
                    $this->{$key} = unserialize(serialize($val));
3552
                }
3553
            }
3554
        }
3555 15
        $this->hash = spl_object_id($this);
3556
    }
3557
3558
    /**
3559
     * Define the code name of the sheet.
3560
     *
3561
     * @param string $codeName Same rule as Title minus space not allowed (but, like Excel, change
3562
     *                       silently space to underscore)
3563
     * @param bool $validate False to skip validation of new title. WARNING: This should only be set
3564
     *                       at parse time (by Readers), where titles can be assumed to be valid.
3565
     *
3566
     * @return $this
3567
     */
3568 10446
    public function setCodeName(string $codeName, bool $validate = true): static
3569
    {
3570
        // Is this a 'rename' or not?
3571 10446
        if ($this->getCodeName() == $codeName) {
3572
            return $this;
3573
        }
3574
3575 10446
        if ($validate) {
3576 10446
            $codeName = str_replace(' ', '_', $codeName); //Excel does this automatically without flinching, we are doing the same
3577
3578
            // Syntax check
3579
            // throw an exception if not valid
3580 10446
            self::checkSheetCodeName($codeName);
3581
3582
            // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_'
3583
3584 10446
            if ($this->parent !== null) {
3585
                // Is there already such sheet name?
3586 10407
                if ($this->parent->sheetCodeNameExists($codeName)) {
3587
                    // Use name, but append with lowest possible integer
3588
3589 673
                    if (Shared\StringHelper::countCharacters($codeName) > 29) {
3590
                        $codeName = Shared\StringHelper::substring($codeName, 0, 29);
3591
                    }
3592 673
                    $i = 1;
3593 673
                    while ($this->getParentOrThrow()->sheetCodeNameExists($codeName . '_' . $i)) {
3594 275
                        ++$i;
3595 275
                        if ($i == 10) {
3596 2
                            if (Shared\StringHelper::countCharacters($codeName) > 28) {
3597
                                $codeName = Shared\StringHelper::substring($codeName, 0, 28);
3598
                            }
3599 275
                        } elseif ($i == 100) {
3600
                            if (Shared\StringHelper::countCharacters($codeName) > 27) {
3601
                                $codeName = Shared\StringHelper::substring($codeName, 0, 27);
3602
                            }
3603
                        }
3604
                    }
3605
3606 673
                    $codeName .= '_' . $i; // ok, we have a valid name
3607
                }
3608
            }
3609
        }
3610
3611 10446
        $this->codeName = $codeName;
3612
3613 10446
        return $this;
3614
    }
3615
3616
    /**
3617
     * Return the code name of the sheet.
3618
     */
3619 10446
    public function getCodeName(): ?string
3620
    {
3621 10446
        return $this->codeName;
3622
    }
3623
3624
    /**
3625
     * Sheet has a code name ?
3626
     */
3627 2
    public function hasCodeName(): bool
3628
    {
3629 2
        return $this->codeName !== null;
3630
    }
3631
3632 4
    public static function nameRequiresQuotes(string $sheetName): bool
3633
    {
3634 4
        return preg_match(self::SHEET_NAME_REQUIRES_NO_QUOTES, $sheetName) !== 1;
3635
    }
3636
3637 119
    public function isRowVisible(int $row): bool
3638
    {
3639 119
        return !$this->rowDimensionExists($row) || $this->getRowDimension($row)->getVisible();
3640
    }
3641
3642
    /**
3643
     * Same as Cell->isLocked, but without creating cell if it doesn't exist.
3644
     */
3645 1
    public function isCellLocked(string $coordinate): bool
3646
    {
3647 1
        if ($this->getProtection()->getsheet() !== true) {
3648 1
            return false;
3649
        }
3650 1
        if ($this->cellExists($coordinate)) {
3651 1
            return $this->getCell($coordinate)->isLocked();
3652
        }
3653 1
        $spreadsheet = $this->parent;
3654 1
        $xfIndex = $this->getXfIndex($coordinate);
3655 1
        if ($spreadsheet === null || $xfIndex === null) {
3656 1
            return true;
3657
        }
3658
3659
        return $spreadsheet->getCellXfByIndex($xfIndex)->getProtection()->getLocked() !== StyleProtection::PROTECTION_UNPROTECTED;
3660
    }
3661
3662
    /**
3663
     * Same as Cell->isHiddenOnFormulaBar, but without creating cell if it doesn't exist.
3664
     */
3665 1
    public function isCellHiddenOnFormulaBar(string $coordinate): bool
3666
    {
3667 1
        if ($this->cellExists($coordinate)) {
3668 1
            return $this->getCell($coordinate)->isHiddenOnFormulaBar();
3669
        }
3670
3671
        // cell doesn't exist, therefore isn't a formula,
3672
        // therefore isn't hidden on formula bar.
3673 1
        return false;
3674
    }
3675
3676 1
    private function getXfIndex(string $coordinate): ?int
3677
    {
3678 1
        [$column, $row] = Coordinate::coordinateFromString($coordinate);
3679 1
        $row = (int) $row;
3680 1
        $xfIndex = null;
3681 1
        if ($this->rowDimensionExists($row)) {
3682
            $xfIndex = $this->getRowDimension($row)->getXfIndex();
3683
        }
3684 1
        if ($xfIndex === null && $this->ColumnDimensionExists($column)) {
3685
            $xfIndex = $this->getColumnDimension($column)->getXfIndex();
3686
        }
3687
3688 1
        return $xfIndex;
3689
    }
3690
3691
    private string $backgroundImage = '';
3692
3693
    private string $backgroundMime = '';
3694
3695
    private string $backgroundExtension = '';
3696
3697 931
    public function getBackgroundImage(): string
3698
    {
3699 931
        return $this->backgroundImage;
3700
    }
3701
3702 370
    public function getBackgroundMime(): string
3703
    {
3704 370
        return $this->backgroundMime;
3705
    }
3706
3707 370
    public function getBackgroundExtension(): string
3708
    {
3709 370
        return $this->backgroundExtension;
3710
    }
3711
3712
    /**
3713
     * Set background image.
3714
     * Used on read/write for Xlsx.
3715
     * Used on write for Html.
3716
     *
3717
     * @param string $backgroundImage Image represented as a string, e.g. results of file_get_contents
3718
     */
3719 4
    public function setBackgroundImage(string $backgroundImage): self
3720
    {
3721 4
        $imageArray = getimagesizefromstring($backgroundImage) ?: ['mime' => ''];
3722 4
        $mime = $imageArray['mime'];
3723 4
        if ($mime !== '') {
3724 3
            $extension = explode('/', $mime);
3725 3
            $extension = $extension[1];
3726 3
            $this->backgroundImage = $backgroundImage;
3727 3
            $this->backgroundMime = $mime;
3728 3
            $this->backgroundExtension = $extension;
3729
        }
3730
3731 4
        return $this;
3732
    }
3733
3734
    /**
3735
     * Copy cells, adjusting relative cell references in formulas.
3736
     * Acts similarly to Excel "fill handle" feature.
3737
     *
3738
     * @param string $fromCell Single source cell, e.g. C3
3739
     * @param string $toCells Single cell or cell range, e.g. C4 or C4:C10
3740
     * @param bool $copyStyle Copy styles as well as values, defaults to true
3741
     */
3742 1
    public function copyCells(string $fromCell, string $toCells, bool $copyStyle = true): void
3743
    {
3744 1
        $toArray = Coordinate::extractAllCellReferencesInRange($toCells);
3745 1
        $valueString = $this->getCell($fromCell)->getValueString();
3746 1
        $style = $this->getStyle($fromCell)->exportArray();
3747 1
        $fromIndexes = Coordinate::indexesFromString($fromCell);
3748 1
        $referenceHelper = ReferenceHelper::getInstance();
3749 1
        foreach ($toArray as $destination) {
3750 1
            if ($destination !== $fromCell) {
3751 1
                $toIndexes = Coordinate::indexesFromString($destination);
3752 1
                $this->getCell($destination)->setValue($referenceHelper->updateFormulaReferences($valueString, 'A1', $toIndexes[0] - $fromIndexes[0], $toIndexes[1] - $fromIndexes[1]));
3753 1
                if ($copyStyle) {
3754 1
                    $this->getCell($destination)->getStyle()->applyFromArray($style);
3755
                }
3756
            }
3757
        }
3758
    }
3759
3760 1078
    public function calculateArrays(bool $preCalculateFormulas = true): void
3761
    {
3762 1078
        if ($preCalculateFormulas && Calculation::getInstance($this->parent)->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY) {
3763 41
            $keys = $this->cellCollection->getCoordinates();
3764 41
            foreach ($keys as $key) {
3765 41
                if ($this->getCell($key)->getDataType() === DataType::TYPE_FORMULA) {
3766 41
                    if (preg_match(self::FUNCTION_LIKE_GROUPBY, $this->getCell($key)->getValue()) !== 1) {
3767 41
                        $this->getCell($key)->getCalculatedValue();
3768
                    }
3769
                }
3770
            }
3771
        }
3772
    }
3773
3774 2
    public function isCellInSpillRange(string $coordinate): bool
3775
    {
3776 2
        if (Calculation::getInstance($this->parent)->getInstanceArrayReturnType() !== Calculation::RETURN_ARRAY_AS_ARRAY) {
3777 1
            return false;
3778
        }
3779 1
        $this->calculateArrays();
3780 1
        $keys = $this->cellCollection->getCoordinates();
3781 1
        foreach ($keys as $key) {
3782 1
            $attributes = $this->getCell($key)->getFormulaAttributes();
3783 1
            if (isset($attributes['ref'])) {
3784 1
                if (Coordinate::coordinateIsInsideRange($attributes['ref'], $coordinate)) {
3785
                    // false for first cell in range, true otherwise
3786 1
                    return $coordinate !== $key;
3787
                }
3788
            }
3789
        }
3790
3791 1
        return false;
3792
    }
3793
3794 2
    public function applyStylesFromArray(string $coordinate, array $styleArray): bool
3795
    {
3796 2
        $spreadsheet = $this->parent;
3797 2
        if ($spreadsheet === null) {
3798 1
            return false;
3799
        }
3800 1
        $activeSheetIndex = $spreadsheet->getActiveSheetIndex();
3801 1
        $originalSelected = $this->selectedCells;
3802 1
        $this->getStyle($coordinate)->applyFromArray($styleArray);
3803 1
        $this->setSelectedCells($originalSelected);
3804 1
        if ($activeSheetIndex >= 0) {
3805 1
            $spreadsheet->setActiveSheetIndex($activeSheetIndex);
3806
        }
3807
3808 1
        return true;
3809
    }
3810
}
3811