Passed
Push — master ( d813d7...2661ad )
by
unknown
23:01 queued 12:33
created

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