Failed Conditions
Push — master ( 8e3417...f52ae2 )
by
unknown
18:26 queued 07:14
created

Worksheet::getFreezePane()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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