Failed Conditions
Pull Request — master (#4314)
by Owen
11:20
created

Worksheet::getXfIndex()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 4

Importance

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