Passed
Pull Request — master (#4465)
by Owen
16:39 queued 03:15
created

Worksheet::setPageSetup()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Worksheet;
4
5
use ArrayObject;
6
use Generator;
7
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
8
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
9
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
10
use PhpOffice\PhpSpreadsheet\Cell\Cell;
11
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
12
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
13
use PhpOffice\PhpSpreadsheet\Cell\DataType;
14
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
15
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
16
use PhpOffice\PhpSpreadsheet\Cell\IValueBinder;
17
use PhpOffice\PhpSpreadsheet\Chart\Chart;
18
use PhpOffice\PhpSpreadsheet\Collection\Cells;
19
use PhpOffice\PhpSpreadsheet\Collection\CellsFactory;
20
use PhpOffice\PhpSpreadsheet\Comment;
21
use PhpOffice\PhpSpreadsheet\DefinedName;
22
use PhpOffice\PhpSpreadsheet\Exception;
23
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
24
use PhpOffice\PhpSpreadsheet\RichText\RichText;
25
use PhpOffice\PhpSpreadsheet\Shared;
26
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
27
use PhpOffice\PhpSpreadsheet\Spreadsheet;
28
use PhpOffice\PhpSpreadsheet\Style\Alignment;
29
use PhpOffice\PhpSpreadsheet\Style\Color;
30
use PhpOffice\PhpSpreadsheet\Style\Conditional;
31
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
32
use PhpOffice\PhpSpreadsheet\Style\Protection as StyleProtection;
33
use PhpOffice\PhpSpreadsheet\Style\Style;
34
35
class Worksheet
36
{
37
    // Break types
38
    public const BREAK_NONE = 0;
39
    public const BREAK_ROW = 1;
40
    public const BREAK_COLUMN = 2;
41
    // Maximum column for row break
42
    public const BREAK_ROW_MAX_COLUMN = 16383;
43
44
    // Sheet state
45
    public const SHEETSTATE_VISIBLE = 'visible';
46
    public const SHEETSTATE_HIDDEN = 'hidden';
47
    public const SHEETSTATE_VERYHIDDEN = 'veryHidden';
48
49
    public const MERGE_CELL_CONTENT_EMPTY = 'empty';
50
    public const MERGE_CELL_CONTENT_HIDE = 'hide';
51
    public const MERGE_CELL_CONTENT_MERGE = 'merge';
52
53
    public const FUNCTION_LIKE_GROUPBY = '/\b(groupby|_xleta)\b/i'; // weird new syntax
54
55
    protected const SHEET_NAME_REQUIRES_NO_QUOTES = '/^[_\p{L}][_\p{L}\p{N}]*$/mui';
56
57
    /**
58
     * Maximum 31 characters allowed for sheet title.
59
     *
60
     * @var int
61
     */
62
    const SHEET_TITLE_MAXIMUM_LENGTH = 31;
63
64
    /**
65
     * Invalid characters in sheet title.
66
     */
67
    private const INVALID_CHARACTERS = ['*', ':', '/', '\\', '?', '[', ']'];
68
69
    /**
70
     * Parent spreadsheet.
71
     */
72
    private ?Spreadsheet $parent = null;
73
74
    /**
75
     * Collection of cells.
76
     */
77
    private Cells $cellCollection;
78
79
    /**
80
     * Collection of row dimensions.
81
     *
82
     * @var RowDimension[]
83
     */
84
    private array $rowDimensions = [];
85
86
    /**
87
     * Default row dimension.
88
     */
89
    private RowDimension $defaultRowDimension;
90
91
    /**
92
     * Collection of column dimensions.
93
     *
94
     * @var ColumnDimension[]
95
     */
96
    private array $columnDimensions = [];
97
98
    /**
99
     * Default column dimension.
100
     */
101
    private ColumnDimension $defaultColumnDimension;
102
103
    /**
104
     * Collection of drawings.
105
     *
106
     * @var ArrayObject<int, BaseDrawing>
107
     */
108
    private ArrayObject $drawingCollection;
109
110
    /**
111
     * Collection of Chart objects.
112
     *
113
     * @var ArrayObject<int, Chart>
114
     */
115
    private ArrayObject $chartCollection;
116
117
    /**
118
     * Collection of Table objects.
119
     *
120
     * @var ArrayObject<int, Table>
121
     */
122
    private ArrayObject $tableCollection;
123
124
    /**
125
     * Worksheet title.
126
     */
127
    private string $title = '';
128
129
    /**
130
     * Sheet state.
131
     */
132
    private string $sheetState;
133
134
    /**
135
     * Page setup.
136
     */
137
    private PageSetup $pageSetup;
138
139
    /**
140
     * Page margins.
141
     */
142
    private PageMargins $pageMargins;
143
144
    /**
145
     * Page header/footer.
146
     */
147
    private HeaderFooter $headerFooter;
148
149
    /**
150
     * Sheet view.
151
     */
152
    private SheetView $sheetView;
153
154
    /**
155
     * Protection.
156
     */
157
    private Protection $protection;
158
159
    /**
160
     * Conditional styles. Indexed by cell coordinate, e.g. 'A1'.
161
     *
162
     * @var Conditional[][]
163
     */
164
    private array $conditionalStylesCollection = [];
165
166
    /**
167
     * Collection of row breaks.
168
     *
169
     * @var PageBreak[]
170
     */
171
    private array $rowBreaks = [];
172
173
    /**
174
     * Collection of column breaks.
175
     *
176
     * @var PageBreak[]
177
     */
178
    private array $columnBreaks = [];
179
180
    /**
181
     * Collection of merged cell ranges.
182
     *
183
     * @var string[]
184
     */
185
    private array $mergeCells = [];
186
187
    /**
188
     * Collection of protected cell ranges.
189
     *
190
     * @var ProtectedRange[]
191
     */
192
    private array $protectedCells = [];
193
194
    /**
195
     * Autofilter Range and selection.
196
     */
197
    private AutoFilter $autoFilter;
198
199
    /**
200
     * Freeze pane.
201
     */
202
    private ?string $freezePane = null;
203
204
    /**
205
     * Default position of the right bottom pane.
206
     */
207
    private ?string $topLeftCell = null;
208
209
    private string $paneTopLeftCell = '';
210
211
    private string $activePane = '';
212
213
    private int $xSplit = 0;
214
215
    private int $ySplit = 0;
216
217
    private string $paneState = '';
218
219
    /**
220
     * Properties of the 4 panes.
221
     *
222
     * @var (null|Pane)[]
223
     */
224
    private array $panes = [
225
        'bottomRight' => null,
226
        'bottomLeft' => null,
227
        'topRight' => null,
228
        'topLeft' => null,
229
    ];
230
231
    /**
232
     * Show gridlines?
233
     */
234
    private bool $showGridlines = true;
235
236
    /**
237
     * Print gridlines?
238
     */
239
    private bool $printGridlines = false;
240
241
    /**
242
     * Show row and column headers?
243
     */
244
    private bool $showRowColHeaders = true;
245
246
    /**
247
     * Show summary below? (Row/Column outline).
248
     */
249
    private bool $showSummaryBelow = true;
250
251
    /**
252
     * Show summary right? (Row/Column outline).
253
     */
254
    private bool $showSummaryRight = true;
255
256
    /**
257
     * Collection of comments.
258
     *
259
     * @var Comment[]
260
     */
261
    private array $comments = [];
262
263
    /**
264
     * Active cell. (Only one!).
265
     */
266
    private string $activeCell = 'A1';
267
268
    /**
269
     * Selected cells.
270
     */
271
    private string $selectedCells = 'A1';
272
273
    /**
274
     * Cached highest column.
275
     */
276
    private int $cachedHighestColumn = 1;
277
278
    /**
279
     * Cached highest row.
280
     */
281
    private int $cachedHighestRow = 1;
282
283
    /**
284
     * Right-to-left?
285
     */
286
    private bool $rightToLeft = false;
287
288
    /**
289
     * Hyperlinks. Indexed by cell coordinate, e.g. 'A1'.
290
     */
291
    private array $hyperlinkCollection = [];
292
293
    /**
294
     * Data validation objects. Indexed by cell coordinate, e.g. 'A1'.
295
     * Index can include ranges, and multiple cells/ranges.
296
     */
297
    private array $dataValidationCollection = [];
298
299
    /**
300
     * Tab color.
301
     */
302
    private ?Color $tabColor = null;
303
304
    /**
305
     * Hash.
306
     */
307
    private int $hash;
308
309
    /**
310
     * CodeName.
311
     */
312
    private ?string $codeName = null;
313
314
    /**
315
     * Create a new worksheet.
316
     */
317 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
        $startRow = $row;
2396 41
        $endRow = $startRow + $numberOfRows - 1;
2397 41
        $removeKeys = [];
2398 41
        foreach ($this->mergeCells as $key => $value) {
2399
            if (preg_match('/^[a-z]{1,3}(\d+)/i', $key, $matches) === 1) {
2400 41
                $startMergeInt = (int) $matches[1];
2401 41
                if ($startMergeInt >= $startRow && $startMergeInt <= $endRow) {
2402 37
                    $removeKeys[] = $key;
2403 37
                }
2404
            }
2405
        }
2406
        foreach ($removeKeys as $key) {
2407 41
            unset($this->mergeCells[$key]);
2408 41
        }
2409 41
2410 37
        $holdRowDimensions = $this->removeRowDimensions($row, $numberOfRows);
2411 37
        $highestRow = $this->getHighestDataRow();
2412
        $removedRowsCounter = 0;
2413
2414 41
        for ($r = 0; $r < $numberOfRows; ++$r) {
2415
            if ($row + $r <= $highestRow) {
2416 41
                $this->cellCollection->removeRow($row + $r);
2417
                ++$removedRowsCounter;
2418
            }
2419 41
        }
2420
2421 41
        $objReferenceHelper = ReferenceHelper::getInstance();
2422 41
        $objReferenceHelper->insertNewBefore('A' . ($row + $numberOfRows), 0, -$numberOfRows, $this);
2423 41
        for ($r = 0; $r < $removedRowsCounter; ++$r) {
2424 4
            $this->cellCollection->removeRow($highestRow);
2425 4
            --$highestRow;
2426 3
        }
2427 4
2428 4
        $this->rowDimensions = $holdRowDimensions;
2429 4
2430 4
        return $this;
2431 4
    }
2432
2433
    private function removeRowDimensions(int $row, int $numberOfRows): array
2434
    {
2435 41
        $highRow = $row + $numberOfRows - 1;
2436
        $holdRowDimensions = [];
2437
        foreach ($this->rowDimensions as $rowDimension) {
2438
            $num = $rowDimension->getRowIndex();
2439
            if ($num < $row) {
2440
                $holdRowDimensions[$num] = $rowDimension;
2441
            } elseif ($num > $highRow) {
2442
                $num -= $numberOfRows;
2443
                $cloneDimension = clone $rowDimension;
2444
                $cloneDimension->setRowIndex($num);
2445
                $holdRowDimensions[$num] = $cloneDimension;
2446 34
            }
2447
        }
2448 34
2449 1
        return $holdRowDimensions;
2450
    }
2451
2452 33
    /**
2453 33
     * Remove a column, updating all possible related data.
2454 33
     *
2455
     * @param string $column Remove columns starting with this column name, eg: 'A'
2456 33
     * @param int $numberOfColumns Number of columns to remove
2457
     *
2458 33
     * @return $this
2459 33
     */
2460 33
    public function removeColumn(string $column, int $numberOfColumns = 1): static
2461
    {
2462 33
        if (is_numeric($column)) {
2463
            throw new Exception('Column references should not be numeric.');
2464 33
        }
2465 2
        $startColumnInt = Coordinate::columnIndexFromString($column);
2466
        $endColumnInt = $startColumnInt + $numberOfColumns - 1;
2467
        $removeKeys = [];
2468 31
        foreach ($this->mergeCells as $key => $value) {
2469
            if (preg_match('/^[a-z]{1,3}/i', $key, $matches) === 1) {
2470 31
                $startMergeInt = Coordinate::columnIndexFromString($matches[0]);
2471 31
                if ($startMergeInt >= $startColumnInt && $startMergeInt <= $endColumnInt) {
2472 31
                    $removeKeys[] = $key;
2473
                }
2474
            }
2475 31
        }
2476
        foreach ($removeKeys as $key) {
2477 31
            unset($this->mergeCells[$key]);
2478
        }
2479
2480 33
        $highestColumn = $this->getHighestDataColumn();
2481
        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
2482 33
        $pColumnIndex = Coordinate::columnIndexFromString($column);
2483 33
2484 33
        $holdColumnDimensions = $this->removeColumnDimensions($pColumnIndex, $numberOfColumns);
2485 18
2486 18
        $column = Coordinate::stringFromColumnIndex($pColumnIndex + $numberOfColumns);
2487 18
        $objReferenceHelper = ReferenceHelper::getInstance();
2488 18
        $objReferenceHelper->insertNewBefore($column . '1', -$numberOfColumns, 0, $this);
2489 18
2490 18
        $this->columnDimensions = $holdColumnDimensions;
2491 18
2492 18
        if ($pColumnIndex > $highestColumnIndex) {
2493 18
            return $this;
2494
        }
2495
2496
        $maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1;
2497 33
2498
        for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $numberOfColumns); $c < $n; ++$c) {
2499
            $this->cellCollection->removeColumn($highestColumn);
2500
            $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1);
2501
        }
2502
2503
        $this->garbageCollect();
2504
2505
        return $this;
2506
    }
2507
2508 2
    private function removeColumnDimensions(int $pColumnIndex, int $numberOfColumns): array
2509
    {
2510 2
        $highCol = $pColumnIndex + $numberOfColumns - 1;
2511 1
        $holdColumnDimensions = [];
2512
        foreach ($this->columnDimensions as $columnDimension) {
2513
            $num = $columnDimension->getColumnNumeric();
2514 1
            if ($num < $pColumnIndex) {
2515
                $str = $columnDimension->getColumnIndex();
2516
                $holdColumnDimensions[$str] = $columnDimension;
2517
            } elseif ($num > $highCol) {
2518
                $cloneDimension = clone $columnDimension;
2519
                $cloneDimension->setColumnNumeric($num - $numberOfColumns);
2520 1008
                $str = $cloneDimension->getColumnIndex();
2521
                $holdColumnDimensions[$str] = $cloneDimension;
2522 1008
            }
2523
        }
2524
2525
        return $holdColumnDimensions;
2526
    }
2527
2528
    /**
2529
     * Remove a column, updating all possible related data.
2530
     *
2531
     * @param int $columnIndex Remove starting with this column Index (numeric column coordinate)
2532 832
     * @param int $numColumns Number of columns to remove
2533
     *
2534 832
     * @return $this
2535
     */
2536 832
    public function removeColumnByIndex(int $columnIndex, int $numColumns = 1): static
2537
    {
2538
        if ($columnIndex >= 1) {
2539
            return $this->removeColumn(Coordinate::stringFromColumnIndex($columnIndex), $numColumns);
2540
        }
2541
2542 1014
        throw new Exception('Columns to be deleted should at least start from column A (1)');
2543
    }
2544 1014
2545
    /**
2546
     * Show gridlines?
2547
     */
2548
    public function getShowGridlines(): bool
2549
    {
2550
        return $this->showGridlines;
2551
    }
2552
2553
    /**
2554 569
     * Set show gridlines.
2555
     *
2556 569
     * @param bool $showGridLines Show gridlines (true/false)
2557
     *
2558 569
     * @return $this
2559
     */
2560
    public function setShowGridlines(bool $showGridLines): self
2561
    {
2562
        $this->showGridlines = $showGridLines;
2563
2564 482
        return $this;
2565
    }
2566 482
2567
    /**
2568
     * Print gridlines?
2569
     */
2570
    public function getPrintGridlines(): bool
2571
    {
2572
        return $this->printGridlines;
2573
    }
2574
2575
    /**
2576 373
     * Set print gridlines.
2577
     *
2578 373
     * @param bool $printGridLines Print gridlines (true/false)
2579
     *
2580 373
     * @return $this
2581
     */
2582
    public function setPrintGridlines(bool $printGridLines): self
2583
    {
2584
        $this->printGridlines = $printGridLines;
2585
2586 483
        return $this;
2587
    }
2588 483
2589
    /**
2590
     * Show row and column headers?
2591
     */
2592
    public function getShowRowColHeaders(): bool
2593
    {
2594
        return $this->showRowColHeaders;
2595
    }
2596
2597
    /**
2598 381
     * Set show row and column headers.
2599
     *
2600 381
     * @param bool $showRowColHeaders Show row and column headers (true/false)
2601
     *
2602 381
     * @return $this
2603
     */
2604
    public function setShowRowColHeaders(bool $showRowColHeaders): self
2605
    {
2606
        $this->showRowColHeaders = $showRowColHeaders;
2607
2608 483
        return $this;
2609
    }
2610 483
2611
    /**
2612
     * Show summary below? (Row/Column outlining).
2613
     */
2614
    public function getShowSummaryBelow(): bool
2615
    {
2616
        return $this->showSummaryBelow;
2617
    }
2618
2619
    /**
2620 381
     * Set show summary below.
2621
     *
2622 381
     * @param bool $showSummaryBelow Show summary below (true/false)
2623
     *
2624 381
     * @return $this
2625
     */
2626
    public function setShowSummaryBelow(bool $showSummaryBelow): self
2627
    {
2628
        $this->showSummaryBelow = $showSummaryBelow;
2629
2630
        return $this;
2631
    }
2632 1039
2633
    /**
2634 1039
     * Show summary right? (Row/Column outlining).
2635
     */
2636
    public function getShowSummaryRight(): bool
2637
    {
2638
        return $this->showSummaryRight;
2639
    }
2640
2641
    /**
2642
     * Set show summary right.
2643
     *
2644 96
     * @param bool $showSummaryRight Show summary right (true/false)
2645
     *
2646 96
     * @return $this
2647
     */
2648 96
    public function setShowSummaryRight(bool $showSummaryRight): self
2649
    {
2650
        $this->showSummaryRight = $showSummaryRight;
2651
2652
        return $this;
2653
    }
2654
2655
    /**
2656
     * Get comments.
2657
     *
2658
     * @return Comment[]
2659 46
     */
2660
    public function getComments(): array
2661 46
    {
2662
        return $this->comments;
2663 46
    }
2664 1
2665 45
    /**
2666 1
     * Set comments array for the entire sheet.
2667 44
     *
2668 1
     * @param Comment[] $comments
2669
     *
2670
     * @return $this
2671 43
     */
2672 2
    public function setComments(array $comments): self
2673
    {
2674
        $this->comments = $comments;
2675 43
2676
        return $this;
2677
    }
2678
2679
    /**
2680
     * Remove comment from cell.
2681
     *
2682
     * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5';
2683
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2684 110
     *
2685
     * @return $this
2686 110
     */
2687
    public function removeComment(CellAddress|string|array $cellCoordinate): self
2688 110
    {
2689 1
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate));
2690 109
2691 1
        if (Coordinate::coordinateIsRange($cellAddress)) {
2692 108
            throw new Exception('Cell coordinate string can not be a range of cells.');
2693 1
        } elseif (str_contains($cellAddress, '$')) {
2694
            throw new Exception('Cell coordinate string must not be absolute.');
2695
        } elseif ($cellAddress == '') {
2696
            throw new Exception('Cell coordinate can not be zero-length string.');
2697 107
        }
2698 74
        // Check if we have a comment for this cell and delete it
2699
        if (isset($this->comments[$cellAddress])) {
2700
            unset($this->comments[$cellAddress]);
2701
        }
2702 107
2703 107
        return $this;
2704 107
    }
2705
2706
    /**
2707 107
     * Get comment for cell.
2708
     *
2709
     * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5';
2710
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2711
     */
2712
    public function getComment(CellAddress|string|array $cellCoordinate, bool $attachNew = true): Comment
2713
    {
2714
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate));
2715 10185
2716
        if (Coordinate::coordinateIsRange($cellAddress)) {
2717 10185
            throw new Exception('Cell coordinate string can not be a range of cells.');
2718
        } elseif (str_contains($cellAddress, '$')) {
2719
            throw new Exception('Cell coordinate string must not be absolute.');
2720
        } elseif ($cellAddress == '') {
2721
            throw new Exception('Cell coordinate can not be zero-length string.');
2722
        }
2723 10230
2724
        // Check if we already have a comment for this cell.
2725 10230
        if (isset($this->comments[$cellAddress])) {
2726
            return $this->comments[$cellAddress];
2727
        }
2728
2729
        // If not, create a new comment.
2730
        $newComment = new Comment();
2731
        if ($attachNew) {
2732
            $this->comments[$cellAddress] = $newComment;
2733
        }
2734
2735 38
        return $newComment;
2736
    }
2737 38
2738
    /**
2739
     * Get active cell.
2740
     *
2741
     * @return string Example: 'A1'
2742
     */
2743
    public function getActiveCell(): string
2744
    {
2745
        return $this->activeCell;
2746
    }
2747
2748
    /**
2749 10202
     * Get selected cells.
2750
     */
2751 10202
    public function getSelectedCells(): string
2752 10202
    {
2753
        return $this->selectedCells;
2754 10202
    }
2755
2756 10202
    /**
2757 498
     * Selected cell.
2758 498
     *
2759
     * @param string $coordinate Cell (i.e. A1)
2760 10171
     *
2761
     * @return $this
2762 10202
     */
2763 10202
    public function setSelectedCell(string $coordinate): static
2764
    {
2765 10202
        return $this->setSelectedCells($coordinate);
2766
    }
2767
2768 10203
    /**
2769
     * Select a range of cells.
2770 10203
     *
2771 47
     * @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'
2772 47
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
2773 47
     *              or a CellAddress or AddressRange object.
2774 26
     *
2775 23
     * @return $this
2776 3
     */
2777 21
    public function setSelectedCells(AddressRange|CellAddress|int|string|array $coordinate): static
2778 21
    {
2779
        if (is_string($coordinate)) {
2780 10
            $coordinate = Validations::definedNameToCoordinate($coordinate, $this);
2781
        }
2782 47
        $coordinate = Validations::validateCellOrCellRange($coordinate);
2783 47
2784
        if (Coordinate::coordinateIsRange($coordinate)) {
2785
            [$first] = Coordinate::splitRange($coordinate);
2786
            $this->activeCell = $first[0];
2787
        } else {
2788
            $this->activeCell = $coordinate;
2789
        }
2790 482
        $this->selectedCells = $coordinate;
2791
        $this->setSelectedCellsActivePane();
2792 482
2793
        return $this;
2794
    }
2795
2796
    private function setSelectedCellsActivePane(): void
2797
    {
2798
        if (!empty($this->freezePane)) {
2799
            $coordinateC = Coordinate::indexesFromString($this->freezePane);
2800
            $coordinateT = Coordinate::indexesFromString($this->activeCell);
2801
            if ($coordinateC[0] === 1) {
2802 134
                $activePane = ($coordinateT[1] <= $coordinateC[1]) ? 'topLeft' : 'bottomLeft';
2803
            } elseif ($coordinateC[1] === 1) {
2804 134
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight';
2805
            } elseif ($coordinateT[1] <= $coordinateC[1]) {
2806 134
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight';
2807
            } else {
2808
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'bottomLeft' : 'bottomRight';
2809
            }
2810
            $this->setActivePane($activePane);
2811
            $this->panes[$activePane] = new Pane($activePane, $this->selectedCells, $this->activeCell);
2812
        }
2813
    }
2814
2815
    /**
2816
     * Get right-to-left.
2817
     */
2818
    public function getRightToLeft(): bool
2819 755
    {
2820
        return $this->rightToLeft;
2821
    }
2822 755
2823 42
    /**
2824
     * Set right-to-left.
2825
     *
2826
     * @param bool $value Right-to-left true/false
2827 755
     *
2828
     * @return $this
2829
     */
2830 755
    public function setRightToLeft(bool $value): static
2831 356
    {
2832 356
        $this->rightToLeft = $value;
2833 356
2834 356
        return $this;
2835
    }
2836 356
2837
    /**
2838 356
     * Fill worksheet from values in array.
2839
     *
2840 356
     * @param array $source Source array
2841
     * @param mixed $nullValue Value in source array that stands for blank cell
2842
     * @param string $startCell Insert array starting from this cell address as the top left coordinate
2843 400
     * @param bool $strictNullComparison Apply strict comparison when testing for null values in the array
2844 400
     *
2845 400
     * @return $this
2846 399
     */
2847
    public function fromArray(array $source, mixed $nullValue = null, string $startCell = 'A1', bool $strictNullComparison = false): static
2848 393
    {
2849
        //    Convert a 1-D array to 2-D (for ease of looping)
2850 399
        if (!is_array(end($source))) {
2851
            $source = [$source];
2852 400
        }
2853
2854
        // start coordinate
2855
        [$startColumn, $startRow] = Coordinate::coordinateFromString($startCell);
2856 755
2857
        // Loop through $source
2858
        if ($strictNullComparison) {
2859
            foreach ($source as $rowData) {
2860
                $currentColumn = $startColumn;
2861
                foreach ($rowData as $cellValue) {
2862
                    if ($cellValue !== $nullValue) {
2863
                        // Set cell value
2864
                        $this->getCell($currentColumn . $startRow)->setValue($cellValue);
2865 175
                    }
2866
                    ++$currentColumn;
2867 175
                }
2868
                ++$startRow;
2869 175
            }
2870 175
        } else {
2871 4
            foreach ($source as $rowData) {
2872
                $currentColumn = $startColumn;
2873 175
                foreach ($rowData as $cellValue) {
2874
                    if ($cellValue != $nullValue) {
2875
                        // Set cell value
2876 175
                        $this->getCell($currentColumn . $startRow)->setValue($cellValue);
2877 114
                    }
2878
                    ++$currentColumn;
2879 114
                }
2880 114
                ++$startRow;
2881 114
            }
2882 114
        }
2883 114
2884
        return $this;
2885
    }
2886
2887 175
    /**
2888
     * @param null|bool|float|int|RichText|string $nullValue value to use when null
2889
     *
2890
     * @throws Exception
2891
     * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
2892
     */
2893
    protected function cellToArray(Cell $cell, bool $calculateFormulas, bool $formatData, mixed $nullValue): mixed
2894
    {
2895
        $returnValue = $nullValue;
2896
2897
        if ($cell->getValue() !== null) {
2898
            if ($cell->getValue() instanceof RichText) {
2899
                $returnValue = $cell->getValue()->getPlainText();
2900
            } else {
2901
                $returnValue = ($calculateFormulas) ? $cell->getCalculatedValue() : $cell->getValue();
2902
            }
2903 146
2904
            if ($formatData) {
2905
                $style = $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex());
2906
                /** @var null|bool|float|int|RichText|string */
2907
                $returnValuex = $returnValue;
2908
                $returnValue = NumberFormat::toFormattedString(
2909
                    $returnValuex,
2910
                    $style->getNumberFormat()->getFormatCode() ?? NumberFormat::FORMAT_GENERAL
2911
                );
2912 146
            }
2913
        }
2914
2915 146
        return $returnValue;
2916 146
    }
2917
2918
    /**
2919
     * Create array from a range of cells.
2920 146
     *
2921
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
2922
     * @param bool $calculateFormulas Should formulas be calculated?
2923
     * @param bool $formatData Should formatting be applied to cell values?
2924
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2925
     *                             True - Return rows and columns indexed by their actual row and column IDs
2926
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2927
     *                            True - Don't return values for rows/columns that are defined as hidden.
2928
     *
2929
     * @return mixed[][]
2930
     */
2931
    public function rangeToArray(
2932
        string $range,
2933
        mixed $nullValue = null,
2934 2
        bool $calculateFormulas = true,
2935
        bool $formatData = true,
2936
        bool $returnCellRef = false,
2937
        bool $ignoreHidden = false,
2938
        bool $reduceArrays = false
2939
    ): array {
2940
        $returnValue = [];
2941
2942
        // Loop through rows
2943 2
        foreach ($this->rangeToArrayYieldRows($range, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays) as $rowRef => $rowArray) {
2944
            $returnValue[$rowRef] = $rowArray;
2945 2
        }
2946 2
2947
        // Return
2948 2
        return $returnValue;
2949 2
    }
2950
2951
    /**
2952
     * Create array from a multiple ranges of cells. (such as A1:A3,A15,B17:C17).
2953
     *
2954 2
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
2955
     * @param bool $calculateFormulas Should formulas be calculated?
2956
     * @param bool $formatData Should formatting be applied to cell values?
2957
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2958
     *                             True - Return rows and columns indexed by their actual row and column IDs
2959
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2960
     *                            True - Don't return values for rows/columns that are defined as hidden.
2961
     */
2962
    public function rangesToArray(
2963
        string $ranges,
2964
        mixed $nullValue = null,
2965
        bool $calculateFormulas = true,
2966
        bool $formatData = true,
2967
        bool $returnCellRef = false,
2968
        bool $ignoreHidden = false,
2969
        bool $reduceArrays = false
2970 175
    ): array {
2971
        $returnValue = [];
2972
2973
        $parts = explode(',', $ranges);
2974
        foreach ($parts as $part) {
2975
            // Loop through rows
2976
            foreach ($this->rangeToArrayYieldRows($part, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays) as $rowRef => $rowArray) {
2977
                $returnValue[$rowRef] = $rowArray;
2978
            }
2979 175
        }
2980
2981
        // Return
2982 175
        return $returnValue;
2983 175
    }
2984 175
2985 175
    /**
2986 175
     * Create array from a range of cells, yielding each row in turn.
2987 175
     *
2988 175
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
2989
     * @param bool $calculateFormulas Should formulas be calculated?
2990 175
     * @param bool $formatData Should formatting be applied to cell values?
2991
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2992 175
     *                             True - Return rows and columns indexed by their actual row and column IDs
2993 175
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2994 175
     *                            True - Don't return values for rows/columns that are defined as hidden.
2995
     *
2996 175
     * @return Generator<array>
2997 175
     */
2998 175
    public function rangeToArrayYieldRows(
2999
        string $range,
3000 175
        mixed $nullValue = null,
3001 175
        bool $calculateFormulas = true,
3002 4
        bool $formatData = true,
3003
        bool $returnCellRef = false,
3004 175
        bool $ignoreHidden = false,
3005 175
        bool $reduceArrays = false
3006
    ) {
3007 175
        $range = Validations::validateCellOrCellRange($range);
3008 175
3009 175
        //    Identify the range that we need to extract from the worksheet
3010 51
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
3011
        $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]);
3012 175
        $minRow = $rangeStart[1];
3013 175
        $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]);
3014 175
        $maxRow = $rangeEnd[1];
3015 175
        $minColInt = $rangeStart[0];
3016 175
        $maxColInt = $rangeEnd[0];
3017 175
3018 175
        ++$maxCol;
3019 175
        /** @var array<string, bool> */
3020 175
        $hiddenColumns = [];
3021 175
        $nullRow = $this->buildNullRow($nullValue, $minCol, $maxCol, $returnCellRef, $ignoreHidden, $hiddenColumns);
3022 175
        $hideColumns = !empty($hiddenColumns);
3023 175
3024 21
        $keys = $this->cellCollection->getSortedCoordinatesInt();
3025 19
        $keyIndex = 0;
3026
        $keysCount = count($keys);
3027
        // Loop through rows
3028 175
        for ($row = $minRow; $row <= $maxRow; ++$row) {
3029 175
            if (($ignoreHidden === true) && ($this->isRowVisible($row) === false)) {
3030
                continue;
3031
            }
3032
            $rowRef = $returnCellRef ? $row : ($row - $minRow);
3033
            $returnValue = $nullRow;
3034 175
3035
            $index = ($row - 1) * AddressRange::MAX_COLUMN_INT + 1;
3036
            $indexPlus = $index + AddressRange::MAX_COLUMN_INT - 1;
3037 175
            while ($keyIndex < $keysCount && $keys[$keyIndex] < $index) {
3038
                ++$keyIndex;
3039
            }
3040
            while ($keyIndex < $keysCount && $keys[$keyIndex] <= $indexPlus) {
3041
                $key = $keys[$keyIndex];
3042
                $thisRow = intdiv($key - 1, AddressRange::MAX_COLUMN_INT) + 1;
3043
                $thisCol = ($key % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT;
3044
                if ($thisCol >= $minColInt && $thisCol <= $maxColInt) {
3045
                    $col = Coordinate::stringFromColumnIndex($thisCol);
3046
                    if ($hideColumns === false || !isset($hiddenColumns[$col])) {
3047
                        $columnRef = $returnCellRef ? $col : ($thisCol - $minColInt);
3048
                        $cell = $this->cellCollection->get("{$col}{$thisRow}");
3049
                        if ($cell !== null) {
3050
                            $value = $this->cellToArray($cell, $calculateFormulas, $formatData, $nullValue);
3051
                            if ($reduceArrays) {
3052
                                while (is_array($value)) {
3053 175
                                    $value = array_shift($value);
3054
                                }
3055
                            }
3056
                            if ($value !== $nullValue) {
3057
                                $returnValue[$columnRef] = $value;
3058
                            }
3059
                        }
3060
                    }
3061 175
                }
3062 175
                ++$keyIndex;
3063 175
            }
3064 175
3065 2
            yield $rowRef => $returnValue;
3066
        }
3067 175
    }
3068 175
3069
    /**
3070
     * Prepare a row data filled with null values to deduplicate the memory areas for empty rows.
3071
     *
3072 175
     * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
3073
     * @param string $minCol Start column of the range
3074
     * @param string $maxCol End column of the range
3075 19
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3076
     *                              True - Return rows and columns indexed by their actual row and column IDs
3077 19
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3078 19
     *                             True - Don't return values for rows/columns that are defined as hidden.
3079 6
     * @param array<string, bool> $hiddenColumns
3080 5
     */
3081
    private function buildNullRow(
3082
        mixed $nullValue,
3083 1
        string $minCol,
3084
        string $maxCol,
3085
        bool $returnCellRef,
3086 13
        bool $ignoreHidden,
3087
        array &$hiddenColumns
3088
    ): array {
3089
        $nullRow = [];
3090
        $c = -1;
3091
        for ($col = $minCol; $col !== $maxCol; ++$col) {
3092
            if ($ignoreHidden === true && $this->columnDimensionExists($col) && $this->getColumnDimension($col)->getVisible() === false) {
3093
                $hiddenColumns[$col] = true; // @phpstan-ignore-line
3094 13
            } else {
3095 2
                $columnRef = $returnCellRef ? $col : ++$c;
3096 2
                $nullRow[$columnRef] = $nullValue;
3097
            }
3098
        }
3099
3100
        return $nullRow;
3101
    }
3102
3103
    private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName
3104
    {
3105
        $namedRange = DefinedName::resolveName($definedName, $this);
3106
        if ($namedRange === null) {
3107 13
            if ($returnNullIfInvalid) {
3108
                return null;
3109
            }
3110
3111
            throw new Exception('Named Range ' . $definedName . ' does not exist.');
3112
        }
3113
3114
        if ($namedRange->isFormula()) {
3115
            if ($returnNullIfInvalid) {
3116
                return null;
3117
            }
3118
3119
            throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.');
3120
        }
3121
3122
        if ($namedRange->getLocalOnly()) {
3123
            $worksheet = $namedRange->getWorksheet();
3124 2
            if ($worksheet === null || $this->hash !== $worksheet->getHashInt()) {
3125
                if ($returnNullIfInvalid) {
3126
                    return null;
3127
                }
3128
3129
                throw new Exception(
3130
                    'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle()
3131
                );
3132
            }
3133 2
        }
3134 2
3135 1
        return $namedRange;
3136 1
    }
3137 1
3138 1
    /**
3139 1
     * Create array from a range of cells.
3140 1
     *
3141
     * @param string $definedName The Named Range that should be returned
3142
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3143
     * @param bool $calculateFormulas Should formulas be calculated?
3144 1
     * @param bool $formatData Should formatting be applied to cell values?
3145
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3146
     *                             True - Return rows and columns indexed by their actual row and column IDs
3147
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3148
     *                            True - Don't return values for rows/columns that are defined as hidden.
3149
     *
3150
     * @return mixed[][]
3151
     */
3152
    public function namedRangeToArray(
3153
        string $definedName,
3154
        mixed $nullValue = null,
3155
        bool $calculateFormulas = true,
3156
        bool $formatData = true,
3157
        bool $returnCellRef = false,
3158
        bool $ignoreHidden = false,
3159
        bool $reduceArrays = false
3160 79
    ): array {
3161
        $retVal = [];
3162
        $namedRange = $this->validateNamedRange($definedName);
3163
        if ($namedRange !== null) {
3164
            $cellRange = ltrim(substr($namedRange->getValue(), (int) strrpos($namedRange->getValue(), '!')), '!');
3165
            $cellRange = str_replace('$', '', $cellRange);
3166
            $workSheet = $namedRange->getWorksheet();
3167
            if ($workSheet !== null) {
3168
                $retVal = $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays);
3169 79
            }
3170 79
        }
3171
3172
        return $retVal;
3173 79
    }
3174 79
3175
    /**
3176
     * Create array from worksheet.
3177 79
     *
3178
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3179
     * @param bool $calculateFormulas Should formulas be calculated?
3180
     * @param bool $formatData Should formatting be applied to cell values?
3181
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3182
     *                             True - Return rows and columns indexed by their actual row and column IDs
3183
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3184
     *                            True - Don't return values for rows/columns that are defined as hidden.
3185
     *
3186 86
     * @return mixed[][]
3187
     */
3188 86
    public function toArray(
3189
        mixed $nullValue = null,
3190
        bool $calculateFormulas = true,
3191
        bool $formatData = true,
3192
        bool $returnCellRef = false,
3193
        bool $ignoreHidden = false,
3194
        bool $reduceArrays = false
3195
    ): array {
3196
        // Garbage collect...
3197 25
        $this->garbageCollect();
3198
        $this->calculateArrays($calculateFormulas);
3199 25
3200
        //    Identify the range that we need to extract from the worksheet
3201
        $maxCol = $this->getHighestColumn();
3202
        $maxRow = $this->getHighestRow();
3203
3204
        // Return
3205
        return $this->rangeToArray("A1:{$maxCol}{$maxRow}", $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays);
3206
    }
3207 1128
3208
    /**
3209
     * Get row iterator.
3210 1128
     *
3211
     * @param int $startRow The row number at which to start iterating
3212
     * @param ?int $endRow The row number at which to stop iterating
3213 1128
     */
3214 1128
    public function getRowIterator(int $startRow = 1, ?int $endRow = null): RowIterator
3215 1128
    {
3216
        return new RowIterator($this, $startRow, $endRow);
3217
    }
3218 1128
3219 162
    /**
3220
     * Get column iterator.
3221
     *
3222
     * @param string $startColumn The column address at which to start iterating
3223 1128
     * @param ?string $endColumn The column address at which to stop iterating
3224 103
     */
3225
    public function getColumnIterator(string $startColumn = 'A', ?string $endColumn = null): ColumnIterator
3226
    {
3227
        return new ColumnIterator($this, $startColumn, $endColumn);
3228 1128
    }
3229
3230
    /**
3231 1128
     * Run PhpSpreadsheet garbage collector.
3232
     *
3233 1128
     * @return $this
3234
     */
3235
    public function garbageCollect(): static
3236 1128
    {
3237
        // Flush cache
3238
        $this->cellCollection->get('A1');
3239 10524
3240
        // Lookup highest column and highest row if cells are cleaned
3241 10524
        $colRow = $this->cellCollection->getHighestRowAndColumn();
3242
        $highestRow = $colRow['row'];
3243
        $highestColumn = Coordinate::columnIndexFromString($colRow['column']);
3244
3245
        // Loop through column dimensions
3246
        foreach ($this->columnDimensions as $dimension) {
3247
            $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex()));
3248
        }
3249
3250
        // Loop through row dimensions
3251
        foreach ($this->rowDimensions as $dimension) {
3252
            $highestRow = max($highestRow, $dimension->getRowIndex());
3253
        }
3254
3255
        // Cache values
3256
        if ($highestColumn < 1) {
3257
            $this->cachedHighestColumn = 1;
3258
        } else {
3259 10406
            $this->cachedHighestColumn = $highestColumn;
3260
        }
3261 10406
        $this->cachedHighestRow = $highestRow;
3262 13
3263
        // Return
3264
        return $this;
3265
    }
3266 10404
3267 10378
    public function getHashInt(): int
3268
    {
3269
        return $this->hash;
3270 1355
    }
3271 1355
3272 1355
    /**
3273 1296
     * Extract worksheet title from range.
3274
     *
3275
     * Example: extractSheetTitle("testSheet!A1") ==> 'A1'
3276 1355
     * Example: extractSheetTitle("testSheet!A1:C3") ==> 'A1:C3'
3277
     * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1'];
3278
     * Example: extractSheetTitle("'testSheet 1'!A1:C3", true) ==> ['testSheet 1', 'A1:C3'];
3279 7
     * Example: extractSheetTitle("A1", true) ==> ['', 'A1'];
3280
     * Example: extractSheetTitle("A1:C3", true) ==> ['', 'A1:C3']
3281
     *
3282 1310
     * @param ?string $range Range to extract title from
3283
     * @param bool $returnRange Return range? (see example)
3284 1310
     *
3285 1310
     * @return ($range is non-empty-string ? ($returnRange is true ? array{0: string, 1: string} : string) : ($returnRange is true ? array{0: null, 1: null} : null))
3286 1238
     */
3287
    public static function extractSheetTitle(?string $range, bool $returnRange = false, bool $unapostrophize = false): array|null|string
3288
    {
3289 1310
        if (empty($range)) {
3290
            return $returnRange ? [null, null] : null;
3291
        }
3292
3293
        // Sheet title included?
3294
        if (($sep = strrpos($range, '!')) === false) {
3295
            return $returnRange ? ['', $range] : '';
3296
        }
3297 93
3298
        if ($returnRange) {
3299
            $title = substr($range, 0, $sep);
3300 93
            if ($unapostrophize) {
3301 45
                $title = self::unApostrophizeTitle($title);
3302
            }
3303
3304
            return [$title, substr($range, $sep + 1)];
3305 93
        }
3306
3307 93
        return substr($range, $sep + 1);
3308
    }
3309
3310
    public static function unApostrophizeTitle(?string $title): string
3311
    {
3312
        $title ??= '';
3313
        if ($title[0] === "'" && substr($title, -1) === "'") {
3314
            $title = str_replace("''", "'", substr($title, 1, -1));
3315
        }
3316
3317 44
        return $title;
3318
    }
3319 44
3320 43
    /**
3321
     * Get hyperlink.
3322 21
     *
3323
     * @param string $cellCoordinate Cell coordinate to get hyperlink for, eg: 'A1'
3324
     */
3325 44
    public function getHyperlink(string $cellCoordinate): Hyperlink
3326
    {
3327
        // return hyperlink if we already have one
3328
        if (isset($this->hyperlinkCollection[$cellCoordinate])) {
3329
            return $this->hyperlinkCollection[$cellCoordinate];
3330
        }
3331
3332
        // else create hyperlink
3333 541
        $this->hyperlinkCollection[$cellCoordinate] = new Hyperlink();
3334
3335 541
        return $this->hyperlinkCollection[$cellCoordinate];
3336
    }
3337
3338
    /**
3339
     * Set hyperlink.
3340
     *
3341
     * @param string $cellCoordinate Cell coordinate to insert hyperlink, eg: 'A1'
3342
     *
3343 562
     * @return $this
3344
     */
3345 562
    public function setHyperlink(string $cellCoordinate, ?Hyperlink $hyperlink = null): static
3346
    {
3347
        if ($hyperlink === null) {
3348
            unset($this->hyperlinkCollection[$cellCoordinate]);
3349
        } else {
3350
            $this->hyperlinkCollection[$cellCoordinate] = $hyperlink;
3351
        }
3352
3353 35
        return $this;
3354
    }
3355
3356 35
    /**
3357 26
     * Hyperlink at a specific coordinate exists?
3358
     *
3359
     * @param string $coordinate eg: 'A1'
3360
     */
3361 28
    public function hyperlinkExists(string $coordinate): bool
3362 12
    {
3363 12
        return isset($this->hyperlinkCollection[$coordinate]);
3364 12
    }
3365 1
3366
    /**
3367 12
     * Get collection of hyperlinks.
3368 9
     *
3369 9
     * @return Hyperlink[]
3370
     */
3371
    public function getHyperlinkCollection(): array
3372
    {
3373
        return $this->hyperlinkCollection;
3374
    }
3375
3376 20
    /**
3377 20
     * Get data validation.
3378 20
     *
3379
     * @param string $cellCoordinate Cell coordinate to get data validation for, eg: 'A1'
3380 20
     */
3381
    public function getDataValidation(string $cellCoordinate): DataValidation
3382
    {
3383
        // return data validation if we already have one
3384
        if (isset($this->dataValidationCollection[$cellCoordinate])) {
3385
            return $this->dataValidationCollection[$cellCoordinate];
3386
        }
3387
3388
        // or if cell is part of a data validation range
3389
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
3390 79
            $keyParts = explode(' ', $key);
3391
            foreach ($keyParts as $keyPart) {
3392 79
                if ($keyPart === $cellCoordinate) {
3393 48
                    return $dataValidation;
3394
                }
3395 38
                if (str_contains($keyPart, ':')) {
3396 38
                    if (Coordinate::coordinateIsInsideRange($keyPart, $cellCoordinate)) {
3397
                        return $dataValidation;
3398
                    }
3399 79
                }
3400
            }
3401
        }
3402
3403
        // else create data validation
3404
        $dataValidation = new DataValidation();
3405
        $dataValidation->setSqref($cellCoordinate);
3406
        $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
3407 25
3408
        return $dataValidation;
3409 25
    }
3410 23
3411
    /**
3412 8
     * Set data validation.
3413 7
     *
3414 7
     * @param string $cellCoordinate Cell coordinate to insert data validation, eg: 'A1'
3415 7
     *
3416 1
     * @return $this
3417
     */
3418 7
    public function setDataValidation(string $cellCoordinate, ?DataValidation $dataValidation = null): static
3419 2
    {
3420 2
        if ($dataValidation === null) {
3421
            unset($this->dataValidationCollection[$cellCoordinate]);
3422
        } else {
3423
            $dataValidation->setSqref($cellCoordinate);
3424
            $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
3425
        }
3426 6
3427
        return $this;
3428
    }
3429
3430
    /**
3431
     * Data validation at a specific coordinate exists?
3432
     *
3433
     * @param string $coordinate eg: 'A1'
3434 563
     */
3435
    public function dataValidationExists(string $coordinate): bool
3436 563
    {
3437 563
        if (isset($this->dataValidationCollection[$coordinate])) {
3438 563
            return true;
3439 27
        }
3440 15
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
3441
            $keyParts = explode(' ', $key);
3442 22
            foreach ($keyParts as $keyPart) {
3443
                if ($keyPart === $coordinate) {
3444
                    return true;
3445
                }
3446 563
                if (str_contains($keyPart, ':')) {
3447
                    if (Coordinate::coordinateIsInsideRange($keyPart, $coordinate)) {
3448
                        return true;
3449
                    }
3450
                }
3451
            }
3452
        }
3453
3454
        return false;
3455
    }
3456
3457
    /**
3458
     * Get collection of data validations.
3459
     *
3460
     * @return DataValidation[]
3461
     */
3462
    public function getDataValidationCollection(): array
3463
    {
3464
        $collectionCells = [];
3465
        $collectionRanges = [];
3466
        foreach ($this->dataValidationCollection as $key => $dataValidation) {
3467
            if (preg_match('/[: ]/', $key) === 1) {
3468
                $collectionRanges[$key] = $dataValidation;
3469
            } else {
3470
                $collectionCells[$key] = $dataValidation;
3471
            }
3472
        }
3473
3474
        return array_merge($collectionCells, $collectionRanges);
3475
    }
3476
3477
    /**
3478
     * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet.
3479
     *
3480
     * @return string Adjusted range value
3481
     */
3482
    public function shrinkRangeToFit(string $range): string
3483
    {
3484
        $maxCol = $this->getHighestColumn();
3485
        $maxRow = $this->getHighestRow();
3486 23
        $maxCol = Coordinate::columnIndexFromString($maxCol);
3487
3488 23
        $rangeBlocks = explode(' ', $range);
3489 23
        foreach ($rangeBlocks as &$rangeSet) {
3490
            $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet);
3491
3492 23
            if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) {
3493
                $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol);
3494
            }
3495
            if ($rangeBoundaries[0][1] > $maxRow) {
3496
                $rangeBoundaries[0][1] = $maxRow;
3497
            }
3498
            if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) {
3499
                $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol);
3500 1
            }
3501
            if ($rangeBoundaries[1][1] > $maxRow) {
3502 1
                $rangeBoundaries[1][1] = $maxRow;
3503
            }
3504 1
            $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1];
3505
        }
3506
        unset($rangeSet);
3507
3508
        return implode(' ', $rangeBlocks);
3509
    }
3510 484
3511
    /**
3512 484
     * Get tab color.
3513
     */
3514
    public function getTabColor(): Color
3515
    {
3516
        if ($this->tabColor === null) {
3517
            $this->tabColor = new Color();
3518
        }
3519
3520
        return $this->tabColor;
3521
    }
3522
3523
    /**
3524
     * Reset tab color.
3525
     *
3526
     * @return $this
3527
     */
3528
    public function resetTabColor(): static
3529
    {
3530
        $this->tabColor = null;
3531
3532
        return $this;
3533
    }
3534
3535
    /**
3536
     * Tab color set?
3537
     */
3538
    public function isTabColorSet(): bool
3539
    {
3540 9
        return $this->tabColor !== null;
3541
    }
3542
3543 9
    /**
3544 8
     * Copy worksheet (!= clone!).
3545 8
     */
3546 1
    public function copy(): static
3547 1
    {
3548
        return clone $this;
3549
    }
3550 8
3551
    /**
3552
     * Returns a boolean true if the specified row contains no cells. By default, this means that no cell records
3553
     *          exist in the collection for this row. false will be returned otherwise.
3554
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3555
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3556
     *                  cells, then the row will be considered empty.
3557
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3558
     *                  string value cells, then the row will be considered empty.
3559
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3560
     *                  If the only cells in the collection are null value or empty string value cells, then the row
3561
     *                  will be considered empty.
3562
     *
3563
     * @param int $definitionOfEmptyFlags
3564
     *              Possible Flag Values are:
3565
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3566
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3567
     */
3568
    public function isEmptyRow(int $rowId, int $definitionOfEmptyFlags = 0): bool
3569
    {
3570 9
        try {
3571
            $iterator = new RowIterator($this, $rowId, $rowId);
3572
            $iterator->seek($rowId);
3573 9
            $row = $iterator->current();
3574 8
        } catch (Exception) {
3575 8
            return true;
3576 1
        }
3577 1
3578
        return $row->isEmpty($definitionOfEmptyFlags);
3579
    }
3580 8
3581
    /**
3582
     * Returns a boolean true if the specified column contains no cells. By default, this means that no cell records
3583
     *          exist in the collection for this column. false will be returned otherwise.
3584
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3585
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3586 20
     *                  cells, then the column will be considered empty.
3587
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3588 20
     *                  string value cells, then the column will be considered empty.
3589 20
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3590 20
     *                  If the only cells in the collection are null value or empty string value cells, then the column
3591
     *                  will be considered empty.
3592
     *
3593 20
     * @param int $definitionOfEmptyFlags
3594 20
     *              Possible Flag Values are:
3595 20
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3596 20
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3597 20
     */
3598 20
    public function isEmptyColumn(string $columnId, int $definitionOfEmptyFlags = 0): bool
3599 20
    {
3600 20
        try {
3601 4
            $iterator = new ColumnIterator($this, $columnId, $columnId);
3602 4
            $iterator->seek($columnId);
3603
            $column = $iterator->current();
3604 20
        } catch (Exception) {
3605 20
            return true;
3606 20
        }
3607 20
3608 1
        return $column->isEmpty($definitionOfEmptyFlags);
3609 1
    }
3610 1
3611
    /**
3612 20
     * Implement PHP __clone to create a deep clone, not just a shallow copy.
3613 20
     */
3614 20
    public function __clone()
3615 20
    {
3616 5
        foreach (get_object_vars($this) as $key => $val) {
3617 5
            if ($key == 'parent') {
3618
                continue;
3619 20
            }
3620 20
3621 20
            if (is_object($val) || (is_array($val))) {
3622 20
                if ($key === 'cellCollection') {
3623
                    $newCollection = $this->cellCollection->cloneCellCollection($this);
3624 20
                    $this->cellCollection = $newCollection;
3625
                } elseif ($key === 'drawingCollection') {
3626
                    $currentCollection = $this->drawingCollection;
3627
                    $this->drawingCollection = new ArrayObject();
3628 20
                    foreach ($currentCollection as $item) {
3629
                        $newDrawing = clone $item;
3630
                        $newDrawing->setWorksheet($this);
3631
                    }
3632
                } elseif ($key === 'tableCollection') {
3633
                    $currentCollection = $this->tableCollection;
3634
                    $this->tableCollection = new ArrayObject();
3635
                    foreach ($currentCollection as $item) {
3636
                        $newTable = clone $item;
3637
                        $newTable->setName($item->getName() . 'clone');
3638
                        $this->addTable($newTable);
3639
                    }
3640
                } elseif ($key === 'chartCollection') {
3641 10561
                    $currentCollection = $this->chartCollection;
3642
                    $this->chartCollection = new ArrayObject();
3643
                    foreach ($currentCollection as $item) {
3644 10561
                        $newChart = clone $item;
3645
                        $this->addChart($newChart);
3646
                    }
3647
                } elseif ($key === 'autoFilter') {
3648 10561
                    $newAutoFilter = clone $this->autoFilter;
3649 10561
                    $this->autoFilter = $newAutoFilter;
3650
                    $this->autoFilter->setParent($this);
3651
                } else {
3652
                    $this->{$key} = unserialize(serialize($val));
3653 10561
                }
3654
            }
3655
        }
3656
        $this->hash = spl_object_id($this);
3657 10561
    }
3658
3659 10522
    /**
3660
     * Define the code name of the sheet.
3661
     *
3662 683
     * @param string $codeName Same rule as Title minus space not allowed (but, like Excel, change
3663
     *                       silently space to underscore)
3664
     * @param bool $validate False to skip validation of new title. WARNING: This should only be set
3665 683
     *                       at parse time (by Readers), where titles can be assumed to be valid.
3666 683
     *
3667 278
     * @return $this
3668 278
     */
3669 2
    public function setCodeName(string $codeName, bool $validate = true): static
3670
    {
3671
        // Is this a 'rename' or not?
3672 278
        if ($this->getCodeName() == $codeName) {
3673
            return $this;
3674
        }
3675
3676
        if ($validate) {
3677
            $codeName = str_replace(' ', '_', $codeName); //Excel does this automatically without flinching, we are doing the same
3678
3679 683
            // Syntax check
3680
            // throw an exception if not valid
3681
            self::checkSheetCodeName($codeName);
3682
3683
            // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_'
3684 10561
3685
            if ($this->parent !== null) {
3686 10561
                // Is there already such sheet name?
3687
                if ($this->parent->sheetCodeNameExists($codeName)) {
3688
                    // Use name, but append with lowest possible integer
3689
3690
                    if (StringHelper::countCharacters($codeName) > 29) {
3691
                        $codeName = StringHelper::substring($codeName, 0, 29);
3692 10561
                    }
3693
                    $i = 1;
3694 10561
                    while ($this->getParentOrThrow()->sheetCodeNameExists($codeName . '_' . $i)) {
3695
                        ++$i;
3696
                        if ($i == 10) {
3697
                            if (StringHelper::countCharacters($codeName) > 28) {
3698
                                $codeName = StringHelper::substring($codeName, 0, 28);
3699
                            }
3700 2
                        } elseif ($i == 100) {
3701
                            if (StringHelper::countCharacters($codeName) > 27) {
3702 2
                                $codeName = StringHelper::substring($codeName, 0, 27);
3703
                            }
3704
                        }
3705 4
                    }
3706
3707 4
                    $codeName .= '_' . $i; // ok, we have a valid name
3708
                }
3709
            }
3710 119
        }
3711
3712 119
        $this->codeName = $codeName;
3713
3714
        return $this;
3715
    }
3716
3717
    /**
3718 1
     * Return the code name of the sheet.
3719
     */
3720 1
    public function getCodeName(): ?string
3721 1
    {
3722
        return $this->codeName;
3723 1
    }
3724 1
3725
    /**
3726 1
     * Sheet has a code name ?
3727 1
     */
3728 1
    public function hasCodeName(): bool
3729 1
    {
3730
        return $this->codeName !== null;
3731
    }
3732
3733
    public static function nameRequiresQuotes(string $sheetName): bool
3734
    {
3735
        return preg_match(self::SHEET_NAME_REQUIRES_NO_QUOTES, $sheetName) !== 1;
3736
    }
3737
3738 1
    public function isRowVisible(int $row): bool
3739
    {
3740 1
        return !$this->rowDimensionExists($row) || $this->getRowDimension($row)->getVisible();
3741 1
    }
3742
3743
    /**
3744
     * Same as Cell->isLocked, but without creating cell if it doesn't exist.
3745
     */
3746 1
    public function isCellLocked(string $coordinate): bool
3747
    {
3748
        if ($this->getProtection()->getsheet() !== true) {
3749 1
            return false;
3750
        }
3751 1
        if ($this->cellExists($coordinate)) {
3752 1
            return $this->getCell($coordinate)->isLocked();
3753 1
        }
3754 1
        $spreadsheet = $this->parent;
3755
        $xfIndex = $this->getXfIndex($coordinate);
3756
        if ($spreadsheet === null || $xfIndex === null) {
3757 1
            return true;
3758
        }
3759
3760
        return $spreadsheet->getCellXfByIndex($xfIndex)->getProtection()->getLocked() !== StyleProtection::PROTECTION_UNPROTECTED;
3761 1
    }
3762
3763
    /**
3764
     * Same as Cell->isHiddenOnFormulaBar, but without creating cell if it doesn't exist.
3765
     */
3766
    public function isCellHiddenOnFormulaBar(string $coordinate): bool
3767
    {
3768
        if ($this->cellExists($coordinate)) {
3769
            return $this->getCell($coordinate)->isHiddenOnFormulaBar();
3770 954
        }
3771
3772 954
        // cell doesn't exist, therefore isn't a formula,
3773
        // therefore isn't hidden on formula bar.
3774
        return false;
3775 378
    }
3776
3777 378
    private function getXfIndex(string $coordinate): ?int
3778
    {
3779
        [$column, $row] = Coordinate::coordinateFromString($coordinate);
3780 378
        $row = (int) $row;
3781
        $xfIndex = null;
3782 378
        if ($this->rowDimensionExists($row)) {
3783
            $xfIndex = $this->getRowDimension($row)->getXfIndex();
3784
        }
3785
        if ($xfIndex === null && $this->ColumnDimensionExists($column)) {
3786
            $xfIndex = $this->getColumnDimension($column)->getXfIndex();
3787
        }
3788
3789
        return $xfIndex;
3790
    }
3791
3792 4
    private string $backgroundImage = '';
3793
3794 4
    private string $backgroundMime = '';
3795 4
3796 4
    private string $backgroundExtension = '';
3797 3
3798 3
    public function getBackgroundImage(): string
3799 3
    {
3800 3
        return $this->backgroundImage;
3801 3
    }
3802
3803
    public function getBackgroundMime(): string
3804 4
    {
3805
        return $this->backgroundMime;
3806
    }
3807
3808
    public function getBackgroundExtension(): string
3809
    {
3810
        return $this->backgroundExtension;
3811
    }
3812
3813
    /**
3814
     * Set background image.
3815 1
     * Used on read/write for Xlsx.
3816
     * Used on write for Html.
3817 1
     *
3818 1
     * @param string $backgroundImage Image represented as a string, e.g. results of file_get_contents
3819
     */
3820 1
    public function setBackgroundImage(string $backgroundImage): self
3821 1
    {
3822 1
        $imageArray = getimagesizefromstring($backgroundImage) ?: ['mime' => ''];
3823 1
        $mime = $imageArray['mime'];
3824 1
        if ($mime !== '') {
3825 1
            $extension = explode('/', $mime);
3826 1
            $extension = $extension[1];
3827 1
            $this->backgroundImage = $backgroundImage;
3828 1
            $this->backgroundMime = $mime;
3829
            $this->backgroundExtension = $extension;
3830
        }
3831
3832
        return $this;
3833
    }
3834 1108
3835
    /**
3836 1108
     * Copy cells, adjusting relative cell references in formulas.
3837 42
     * Acts similarly to Excel "fill handle" feature.
3838 42
     *
3839 42
     * @param string $fromCell Single source cell, e.g. C3
3840 42
     * @param string $toCells Single cell or cell range, e.g. C4 or C4:C10
3841 42
     * @param bool $copyStyle Copy styles as well as values, defaults to true
3842
     */
3843
    public function copyCells(string $fromCell, string $toCells, bool $copyStyle = true): void
3844
    {
3845
        $toArray = Coordinate::extractAllCellReferencesInRange($toCells);
3846
        $valueString = $this->getCell($fromCell)->getValueString();
3847
        /** @var mixed[][] */
3848 2
        $style = $this->getStyle($fromCell)->exportArray();
3849
        $fromIndexes = Coordinate::indexesFromString($fromCell);
3850 2
        $referenceHelper = ReferenceHelper::getInstance();
3851 1
        foreach ($toArray as $destination) {
3852
            if ($destination !== $fromCell) {
3853 1
                $toIndexes = Coordinate::indexesFromString($destination);
3854 1
                $this->getCell($destination)->setValue($referenceHelper->updateFormulaReferences($valueString, 'A1', $toIndexes[0] - $fromIndexes[0], $toIndexes[1] - $fromIndexes[1]));
3855 1
                if ($copyStyle) {
3856 1
                    $this->getCell($destination)->getStyle()->applyFromArray($style);
3857 1
                }
3858 1
            }
3859
        }
3860 1
    }
3861
3862
    public function calculateArrays(bool $preCalculateFormulas = true): void
3863
    {
3864
        if ($preCalculateFormulas && Calculation::getInstance($this->parent)->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY) {
3865 1
            $keys = $this->cellCollection->getCoordinates();
3866
            foreach ($keys as $key) {
3867
                if ($this->getCell($key)->getDataType() === DataType::TYPE_FORMULA) {
3868
                    if (preg_match(self::FUNCTION_LIKE_GROUPBY, $this->getCell($key)->getValueString()) !== 1) {
3869 2
                        $this->getCell($key)->getCalculatedValue();
3870
                    }
3871 2
                }
3872 2
            }
3873 1
        }
3874
    }
3875 1
3876 1
    public function isCellInSpillRange(string $coordinate): bool
3877 1
    {
3878 1
        if (Calculation::getInstance($this->parent)->getInstanceArrayReturnType() !== Calculation::RETURN_ARRAY_AS_ARRAY) {
3879 1
            return false;
3880 1
        }
3881
        $this->calculateArrays();
3882
        $keys = $this->cellCollection->getCoordinates();
3883 1
        foreach ($keys as $key) {
3884
            $attributes = $this->getCell($key)->getFormulaAttributes();
3885
            if (isset($attributes['ref'])) {
3886
                if (Coordinate::coordinateIsInsideRange($attributes['ref'], $coordinate)) {
3887
                    // false for first cell in range, true otherwise
3888
                    return $coordinate !== $key;
3889
                }
3890
            }
3891
        }
3892
3893
        return false;
3894
    }
3895
3896
    /** @param mixed[][] $styleArray */
3897
    public function applyStylesFromArray(string $coordinate, array $styleArray): bool
3898
    {
3899
        $spreadsheet = $this->parent;
3900
        if ($spreadsheet === null) {
3901
            return false;
3902
        }
3903
        $activeSheetIndex = $spreadsheet->getActiveSheetIndex();
3904
        $originalSelected = $this->selectedCells;
3905
        $this->getStyle($coordinate)->applyFromArray($styleArray);
3906
        $this->setSelectedCells($originalSelected);
3907
        if ($activeSheetIndex >= 0) {
3908
            $spreadsheet->setActiveSheetIndex($activeSheetIndex);
3909
        }
3910
3911
        return true;
3912
    }
3913
}
3914