Worksheet::setCellValueExplicit()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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