Worksheet::removeRow()   A
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

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