Passed
Pull Request — master (#4317)
by Owen
14:50
created

Worksheet::getRowStyle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 4
rs 10
ccs 2
cts 2
cp 1
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Worksheet;
4
5
use ArrayObject;
6
use Generator;
7
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
8
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
9
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
10
use PhpOffice\PhpSpreadsheet\Cell\Cell;
11
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
12
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
13
use PhpOffice\PhpSpreadsheet\Cell\DataType;
14
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
15
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
16
use PhpOffice\PhpSpreadsheet\Cell\IValueBinder;
17
use PhpOffice\PhpSpreadsheet\Chart\Chart;
18
use PhpOffice\PhpSpreadsheet\Collection\Cells;
19
use PhpOffice\PhpSpreadsheet\Collection\CellsFactory;
20
use PhpOffice\PhpSpreadsheet\Comment;
21
use PhpOffice\PhpSpreadsheet\DefinedName;
22
use PhpOffice\PhpSpreadsheet\Exception;
23
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
24
use PhpOffice\PhpSpreadsheet\RichText\RichText;
25
use PhpOffice\PhpSpreadsheet\Shared;
26
use PhpOffice\PhpSpreadsheet\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 getRowStyle(int $row): ?Style
1339
    {
1340
        return $this->parent?->getCellXfByIndexOrNull(
1341 34
            ($this->rowDimensions[$row] ?? null)?->getXfIndex()
1342
        );
1343 34
    }
1344
1345
    public function rowDimensionExists(int $row): bool
1346
    {
1347
        return isset($this->rowDimensions[$row]);
1348
    }
1349
1350
    public function columnDimensionExists(string $column): bool
1351 615
    {
1352
        return isset($this->columnDimensions[$column]);
1353
    }
1354 615
1355
    /**
1356
     * Get column dimension at a specific column.
1357 615
     *
1358 615
     * @param string $column String index of the column eg: 'A'
1359
     */
1360 615
    public function getColumnDimension(string $column): ColumnDimension
1361 615
    {
1362 435
        // Uppercase coordinate
1363
        $column = strtoupper($column);
1364
1365
        // Fetch dimensions
1366 615
        if (!isset($this->columnDimensions[$column])) {
1367
            $this->columnDimensions[$column] = new ColumnDimension($column);
1368
1369
            $columnIndex = Coordinate::columnIndexFromString($column);
1370
            if ($this->cachedHighestColumn < $columnIndex) {
1371
                $this->cachedHighestColumn = $columnIndex;
1372
            }
1373
        }
1374 97
1375
        return $this->columnDimensions[$column];
1376 97
    }
1377
1378
    /**
1379
     * Get column dimension at a specific column by using numeric cell coordinates.
1380
     *
1381
     * @param int $columnIndex Numeric column coordinate of the cell
1382
     */
1383
    public function getColumnDimensionByColumn(int $columnIndex): ColumnDimension
1384 1
    {
1385
        return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex));
1386 1
    }
1387
1388
    public function getColumnStyle(string $column): ?Style
1389
    {
1390
        return $this->parent?->getCellXfByIndexOrNull(
1391
            ($this->columnDimensions[$column] ?? null)?->getXfIndex()
1392
        );
1393
    }
1394
1395
    /**
1396
     * Get styles.
1397 10000
     *
1398
     * @return Style[]
1399 10000
     */
1400
    public function getStyles(): array
1401
    {
1402 10000
        return $this->styles;
1403
    }
1404
1405 10000
    /**
1406
     * Get style for cell.
1407 10000
     *
1408
     * @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
1409
     *              A simple string containing a cell address like 'A1' or a cell range like 'A1:E10'
1410
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1411
     *              or a CellAddress or AddressRange object.
1412
     */
1413
    public function getStyle(AddressRange|CellAddress|int|string|array $cellCoordinate): Style
1414
    {
1415
        $cellCoordinate = Validations::validateCellOrCellRange($cellCoordinate);
1416
1417
        // set this sheet as active
1418
        $this->getParentOrThrow()->setActiveSheetIndex($this->getParentOrThrow()->getIndex($this));
1419
1420
        // set cell coordinate as active
1421 236
        $this->setSelectedCells($cellCoordinate);
1422
1423 236
        return $this->getParentOrThrow()->getCellXfSupervisor();
1424 236
    }
1425 47
1426
    /**
1427
     * Get conditional styles for a cell.
1428 214
     *
1429 214
     * @param string $coordinate eg: 'A1' or 'A1:A3'.
1430 201
     *          If a single cell is referenced, then the array of conditional styles will be returned if the cell is
1431 201
     *               included in a conditional style range.
1432 201
     *          If a range of cells is specified, then the styles will only be returned if the range matches the entire
1433 194
     *               range of the conditional.
1434
     *
1435
     * @return Conditional[]
1436
     */
1437
    public function getConditionalStyles(string $coordinate): array
1438 43
    {
1439
        $coordinate = strtoupper($coordinate);
1440
        if (str_contains($coordinate, ':')) {
1441 180
            return $this->conditionalStylesCollection[$coordinate] ?? [];
1442
        }
1443 180
1444 180
        $cell = $this->getCell($coordinate);
1445 180
        foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) {
1446 180
            $cellBlocks = explode(',', Coordinate::resolveUnionAndIntersection($conditionalRange));
1447 180
            foreach ($cellBlocks as $cellBlock) {
1448 180
                if ($cell->isInRange($cellBlock)) {
1449 179
                    return $this->conditionalStylesCollection[$conditionalRange];
1450
                }
1451
            }
1452
        }
1453
1454 3
        return [];
1455
    }
1456
1457
    public function getConditionalRange(string $coordinate): ?string
1458
    {
1459
        $coordinate = strtoupper($coordinate);
1460
        $cell = $this->getCell($coordinate);
1461
        foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) {
1462
            $cellBlocks = explode(',', Coordinate::resolveUnionAndIntersection($conditionalRange));
1463
            foreach ($cellBlocks as $cellBlock) {
1464
                if ($cell->isInRange($cellBlock)) {
1465
                    return $conditionalRange;
1466 22
                }
1467
            }
1468 22
        }
1469 22
1470 11
        return null;
1471
    }
1472
1473 11
    /**
1474 11
     * Do conditional styles exist for this cell?
1475 11
     *
1476 7
     * @param string $coordinate eg: 'A1' or 'A1:A3'.
1477
     *          If a single cell is specified, then this method will return true if that cell is included in a
1478
     *               conditional style range.
1479
     *          If a range of cells is specified, then true will only be returned if the range matches the entire
1480 4
     *               range of the conditional.
1481
     */
1482
    public function conditionalStylesExists(string $coordinate): bool
1483
    {
1484
        $coordinate = strtoupper($coordinate);
1485
        if (str_contains($coordinate, ':')) {
1486
            return isset($this->conditionalStylesCollection[$coordinate]);
1487
        }
1488
1489
        $cell = $this->getCell($coordinate);
1490 42
        foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) {
1491
            if ($cell->isInRange($conditionalRange)) {
1492 42
                return true;
1493
            }
1494 42
        }
1495
1496
        return false;
1497
    }
1498
1499
    /**
1500 540
     * Removes conditional styles for a cell.
1501
     *
1502 540
     * @param string $coordinate eg: 'A1'
1503
     *
1504
     * @return $this
1505
     */
1506
    public function removeConditionalStyles(string $coordinate): static
1507
    {
1508
        unset($this->conditionalStylesCollection[strtoupper($coordinate)]);
1509
1510
        return $this;
1511
    }
1512
1513 303
    /**
1514
     * Get collection of conditional styles.
1515 303
     */
1516
    public function getConditionalStylesCollection(): array
1517 303
    {
1518
        return $this->conditionalStylesCollection;
1519
    }
1520
1521
    /**
1522
     * Set conditional styles.
1523
     *
1524
     * @param string $coordinate eg: 'A1'
1525
     * @param Conditional[] $styles
1526
     *
1527
     * @return $this
1528
     */
1529
    public function setConditionalStyles(string $coordinate, array $styles): static
1530 2
    {
1531
        $this->conditionalStylesCollection[strtoupper($coordinate)] = $styles;
1532
1533 2
        return $this;
1534 2
    }
1535
1536 1
    /**
1537
     * Duplicate cell style to a range of cells.
1538
     *
1539 2
     * Please note that this will overwrite existing cell styles for cells in range!
1540 2
     *
1541
     * @param Style $style Cell style to duplicate
1542
     * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
1543
     *
1544 2
     * @return $this
1545
     */
1546
    public function duplicateStyle(Style $style, string $range): static
1547 2
    {
1548
        // Add the style to the workbook if necessary
1549
        $workbook = $this->getParentOrThrow();
1550
        if ($existingStyle = $workbook->getCellXfByHashCode($style->getHashCode())) {
1551
            // there is already such cell Xf in our collection
1552
            $xfIndex = $existingStyle->getIndex();
1553
        } else {
1554 2
            // we don't have such a cell Xf, need to add
1555 2
            $workbook->addCellXf($style);
1556 2
            $xfIndex = $style->getIndex();
1557
        }
1558
1559
        // Calculate range outer borders
1560 2
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range);
1561
1562
        // Make sure we can loop upwards on rows and columns
1563
        if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
1564
            $tmp = $rangeStart;
1565
            $rangeStart = $rangeEnd;
1566
            $rangeEnd = $tmp;
1567
        }
1568
1569
        // Loop through cells and apply styles
1570
        for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
1571
            for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
1572
                $this->getCell(Coordinate::stringFromColumnIndex($col) . $row)->setXfIndex($xfIndex);
1573 18
            }
1574
        }
1575 18
1576 18
        return $this;
1577
    }
1578
1579
    /**
1580
     * Duplicate conditional style to a range of cells.
1581
     *
1582 18
     * Please note that this will overwrite existing cell styles for cells in range!
1583
     *
1584
     * @param Conditional[] $styles Cell style to duplicate
1585 18
     * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
1586
     *
1587
     * @return $this
1588
     */
1589
    public function duplicateConditionalStyle(array $styles, string $range = ''): static
1590
    {
1591
        foreach ($styles as $cellStyle) {
1592 18
            if (!($cellStyle instanceof Conditional)) {
1593 18
                throw new Exception('Style is not a conditional style');
1594 18
            }
1595
        }
1596
1597
        // Calculate range outer borders
1598 18
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range);
1599
1600
        // Make sure we can loop upwards on rows and columns
1601
        if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
1602
            $tmp = $rangeStart;
1603
            $rangeStart = $rangeEnd;
1604
            $rangeEnd = $tmp;
1605
        }
1606
1607
        // Loop through cells and apply styles
1608
        for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
1609
            for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
1610 29
                $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $styles);
1611
            }
1612 29
        }
1613
1614 29
        return $this;
1615 7
    }
1616 29
1617 21
    /**
1618 17
     * Set break on a cell.
1619 17
     *
1620
     * @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
1621
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
1622 29
     * @param int $break Break type (type of Worksheet::BREAK_*)
1623
     *
1624
     * @return $this
1625
     */
1626
    public function setBreak(CellAddress|string|array $coordinate, int $break, int $max = -1): static
1627
    {
1628
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
1629
1630 612
        if ($break === self::BREAK_NONE) {
1631
            unset($this->rowBreaks[$cellAddress], $this->columnBreaks[$cellAddress]);
1632 612
        } elseif ($break === self::BREAK_ROW) {
1633
            $this->rowBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max);
1634 612
        } elseif ($break === self::BREAK_COLUMN) {
1635 612
            $this->columnBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max);
1636 612
        }
1637 10
1638
        return $this;
1639
    }
1640 612
1641 612
    /**
1642 612
     * Get breaks.
1643 8
     *
1644
     * @return int[]
1645
     */
1646 612
    public function getBreaks(): array
1647
    {
1648
        $breaks = [];
1649
        /** @var callable $compareFunction */
1650
        $compareFunction = [self::class, 'compareRowBreaks'];
1651
        uksort($this->rowBreaks, $compareFunction);
1652
        foreach ($this->rowBreaks as $break) {
1653
            $breaks[$break->getCoordinate()] = self::BREAK_ROW;
1654 465
        }
1655
        /** @var callable $compareFunction */
1656
        $compareFunction = [self::class, 'compareColumnBreaks'];
1657 465
        uksort($this->columnBreaks, $compareFunction);
1658 465
        foreach ($this->columnBreaks as $break) {
1659
            $breaks[$break->getCoordinate()] = self::BREAK_COLUMN;
1660 465
        }
1661
1662
        return $breaks;
1663 9
    }
1664
1665 9
    /**
1666 9
     * Get row breaks.
1667
     *
1668 9
     * @return PageBreak[]
1669
     */
1670
    public function getRowBreaks(): array
1671 5
    {
1672
        /** @var callable $compareFunction */
1673 5
        $compareFunction = [self::class, 'compareRowBreaks'];
1674 5
        uksort($this->rowBreaks, $compareFunction);
1675
1676 5
        return $this->rowBreaks;
1677
    }
1678
1679
    protected static function compareRowBreaks(string $coordinate1, string $coordinate2): int
1680
    {
1681
        $row1 = Coordinate::indexesFromString($coordinate1)[1];
1682
        $row2 = Coordinate::indexesFromString($coordinate2)[1];
1683
1684 464
        return $row1 - $row2;
1685
    }
1686
1687 464
    protected static function compareColumnBreaks(string $coordinate1, string $coordinate2): int
1688 464
    {
1689
        $column1 = Coordinate::indexesFromString($coordinate1)[0];
1690 464
        $column2 = Coordinate::indexesFromString($coordinate2)[0];
1691
1692
        return $column1 - $column2;
1693
    }
1694
1695
    /**
1696
     * Get column breaks.
1697
     *
1698
     * @return PageBreak[]
1699
     */
1700
    public function getColumnBreaks(): array
1701
    {
1702
        /** @var callable $compareFunction */
1703
        $compareFunction = [self::class, 'compareColumnBreaks'];
1704
        uksort($this->columnBreaks, $compareFunction);
1705
1706
        return $this->columnBreaks;
1707 161
    }
1708
1709 161
    /**
1710
     * Set merge on a cell range.
1711 160
     *
1712 1
     * @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'
1713
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1714
     *              or an AddressRange.
1715 160
     * @param string $behaviour How the merged cells should behave.
1716 1
     *               Possible values are:
1717
     *                   MERGE_CELL_CONTENT_EMPTY - Empty the content of the hidden cells
1718
     *                   MERGE_CELL_CONTENT_HIDE - Keep the content of the hidden cells
1719 159
     *                   MERGE_CELL_CONTENT_MERGE - Move the content of the hidden cells into the first cell
1720 159
     *
1721 159
     * @return $this
1722 159
     */
1723 159
    public function mergeCells(AddressRange|string|array $range, string $behaviour = self::MERGE_CELL_CONTENT_EMPTY): static
1724 159
    {
1725 159
        $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range));
1726 159
1727 159
        if (!str_contains($range, ':')) {
1728
            $range .= ":{$range}";
1729 159
        }
1730 30
1731
        if (preg_match('/^([A-Z]+)(\\d+):([A-Z]+)(\\d+)$/', $range, $matches) !== 1) {
1732
            throw new Exception('Merge must be on a valid range of cells.');
1733
        }
1734 152
1735 152
        $this->mergeCells[$range] = $range;
1736 31
        $firstRow = (int) $matches[2];
1737
        $lastRow = (int) $matches[4];
1738
        $firstColumn = $matches[1];
1739 152
        $lastColumn = $matches[3];
1740
        $firstColumnIndex = Coordinate::columnIndexFromString($firstColumn);
1741 50
        $lastColumnIndex = Coordinate::columnIndexFromString($lastColumn);
1742 12
        $numberRows = $lastRow - $firstRow;
1743
        $numberColumns = $lastColumnIndex - $firstColumnIndex;
1744 38
1745
        if ($numberRows === 1 && $numberColumns === 1) {
1746
            return $this;
1747
        }
1748 152
1749
        // create upper left cell if it does not already exist
1750
        $upperLeft = "{$firstColumn}{$firstRow}";
1751 12
        if (!$this->cellExists($upperLeft)) {
1752
            $this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL);
1753 12
        }
1754
1755 12
        if ($behaviour !== self::MERGE_CELL_CONTENT_HIDE) {
1756
            // Blank out the rest of the cells in the range (if they exist)
1757 12
            if ($numberRows > $numberColumns) {
1758 12
                $this->clearMergeCellsByColumn($firstColumn, $lastColumn, $firstRow, $lastRow, $upperLeft, $behaviour);
1759 12
            } else {
1760 12
                $this->clearMergeCellsByRow($firstColumn, $lastColumnIndex, $firstRow, $lastRow, $upperLeft, $behaviour);
1761 12
            }
1762 12
        }
1763 12
1764 7
        return $this;
1765
    }
1766 12
1767
    private function clearMergeCellsByColumn(string $firstColumn, string $lastColumn, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void
1768
    {
1769
        $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE)
1770
            ? [$this->getCell($upperLeft)->getFormattedValue()]
1771 12
            : [];
1772
1773
        foreach ($this->getColumnIterator($firstColumn, $lastColumn) as $column) {
1774
            $iterator = $column->getCellIterator($firstRow);
1775
            $iterator->setIterateOnlyExistingCells(true);
1776 38
            foreach ($iterator as $cell) {
1777
                if ($cell !== null) {
1778 38
                    $row = $cell->getRow();
1779 4
                    if ($row > $lastRow) {
1780 34
                        break;
1781
                    }
1782 38
                    $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue);
1783 38
                }
1784 38
            }
1785 38
        }
1786 38
1787 38
        if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
1788 38
            $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING);
1789 38
        }
1790 8
    }
1791
1792 38
    private function clearMergeCellsByRow(string $firstColumn, int $lastColumnIndex, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void
1793
    {
1794
        $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE)
1795
            ? [$this->getCell($upperLeft)->getFormattedValue()]
1796
            : [];
1797 38
1798 4
        foreach ($this->getRowIterator($firstRow, $lastRow) as $row) {
1799
            $iterator = $row->getCellIterator($firstColumn);
1800
            $iterator->setIterateOnlyExistingCells(true);
1801
            foreach ($iterator as $cell) {
1802 50
                if ($cell !== null) {
1803
                    $column = $cell->getColumn();
1804 50
                    $columnIndex = Coordinate::columnIndexFromString($column);
1805 22
                    if ($columnIndex > $lastColumnIndex) {
1806 22
                        break;
1807 4
                    }
1808 4
                    $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue);
1809 4
                }
1810
            }
1811
        }
1812 22
1813
        if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
1814
            $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING);
1815 50
        }
1816
    }
1817
1818
    public function mergeCellBehaviour(Cell $cell, string $upperLeft, string $behaviour, array $leftCellValue): array
1819
    {
1820
        if ($cell->getCoordinate() !== $upperLeft) {
1821
            Calculation::getInstance($cell->getWorksheet()->getParentOrThrow())->flushInstance();
1822
            if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) {
1823
                $cellValue = $cell->getFormattedValue();
1824
                if ($cellValue !== '') {
1825
                    $leftCellValue[] = $cellValue;
1826
                }
1827 23
            }
1828
            $cell->setValueExplicit(null, DataType::TYPE_NULL);
1829 23
        }
1830
1831 23
        return $leftCellValue;
1832 22
    }
1833 22
1834
    /**
1835
     * Remove merge on a cell range.
1836
     *
1837
     * @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'
1838 1
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1839
     *              or an AddressRange.
1840
     *
1841 22
     * @return $this
1842
     */
1843
    public function unmergeCells(AddressRange|string|array $range): static
1844
    {
1845
        $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range));
1846
1847
        if (str_contains($range, ':')) {
1848
            if (isset($this->mergeCells[$range])) {
1849 1099
                unset($this->mergeCells[$range]);
1850
            } else {
1851 1099
                throw new Exception('Cell range ' . $range . ' not known as merged.');
1852
            }
1853
        } else {
1854
            throw new Exception('Merge can only be removed from a range of cells.');
1855
        }
1856
1857
        return $this;
1858
    }
1859
1860
    /**
1861
     * Get merge cells array.
1862 91
     *
1863
     * @return string[]
1864 91
     */
1865
    public function getMergeCells(): array
1866 91
    {
1867
        return $this->mergeCells;
1868
    }
1869
1870
    /**
1871
     * Set merge cells array for the entire sheet. Use instead mergeCells() to merge
1872
     * a single cell range.
1873
     *
1874
     * @param string[] $mergeCells
1875
     *
1876
     * @return $this
1877
     */
1878
    public function setMergeCells(array $mergeCells): static
1879
    {
1880 24
        $this->mergeCells = $mergeCells;
1881
1882 24
        return $this;
1883
    }
1884 24
1885 24
    /**
1886
     * Set protection on a cell or cell range.
1887 24
     *
1888
     * @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'
1889 24
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1890
     *              or a CellAddress or AddressRange object.
1891
     * @param string $password Password to unlock the protection
1892
     * @param bool $alreadyHashed If the password has already been hashed, set this to true
1893
     *
1894
     * @return $this
1895
     */
1896
    public function protectCells(AddressRange|CellAddress|int|string|array $range, string $password = '', bool $alreadyHashed = false, string $name = '', string $securityDescriptor = ''): static
1897
    {
1898
        $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range));
1899
1900
        if (!$alreadyHashed && $password !== '') {
1901 20
            $password = Shared\PasswordHasher::hashPassword($password);
1902
        }
1903 20
        $this->protectedCells[$range] = new ProtectedRange($range, $password, $name, $securityDescriptor);
1904
1905 20
        return $this;
1906 19
    }
1907
1908 1
    /**
1909
     * Remove protection on a cell or cell range.
1910
     *
1911 19
     * @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'
1912
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1913
     *              or a CellAddress or AddressRange object.
1914
     *
1915
     * @return $this
1916
     */
1917
    public function unprotectCells(AddressRange|CellAddress|int|string|array $range): static
1918
    {
1919
        $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range));
1920
1921
        if (isset($this->protectedCells[$range])) {
1922 92
            unset($this->protectedCells[$range]);
1923
        } else {
1924 92
            throw new Exception('Cell range ' . $range . ' not known as protected.');
1925 92
        }
1926 18
1927
        return $this;
1928
    }
1929 92
1930
    /**
1931
     * Get password for protected cells.
1932
     *
1933
     * @return string[]
1934
     *
1935
     * @deprecated 2.0.1 use getProtectedCellRanges instead
1936
     * @see Worksheet::getProtectedCellRanges()
1937 464
     */
1938
    public function getProtectedCells(): array
1939 464
    {
1940
        $array = [];
1941
        foreach ($this->protectedCells as $key => $protectedRange) {
1942
            $array[$key] = $protectedRange->getPassword();
1943
        }
1944
1945 729
        return $array;
1946
    }
1947 729
1948
    /**
1949
     * Get protected cells.
1950
     *
1951
     * @return ProtectedRange[]
1952
     */
1953
    public function getProtectedCellRanges(): array
1954
    {
1955
        return $this->protectedCells;
1956
    }
1957
1958
    /**
1959
     * Get Autofilter.
1960 17
     */
1961
    public function getAutoFilter(): AutoFilter
1962 17
    {
1963
        return $this->autoFilter;
1964
    }
1965 17
1966
    /**
1967 17
     * Set AutoFilter.
1968
     *
1969
     * @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|AutoFilter|string $autoFilterOrRange
1970 17
     *            A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility
1971
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
1972
     *              or an AddressRange.
1973
     *
1974
     * @return $this
1975
     */
1976 1
    public function setAutoFilter(AddressRange|string|array|AutoFilter $autoFilterOrRange): static
1977
    {
1978 1
        if (is_object($autoFilterOrRange) && ($autoFilterOrRange instanceof AutoFilter)) {
1979
            $this->autoFilter = $autoFilterOrRange;
1980 1
        } else {
1981
            $cellRange = Functions::trimSheetFromCellReference(Validations::validateCellRange($autoFilterOrRange));
1982
1983
            $this->autoFilter->setRange($cellRange);
1984
        }
1985
1986
        return $this;
1987
    }
1988 10009
1989
    /**
1990 10009
     * Remove autofilter.
1991
     */
1992
    public function removeAutoFilter(): self
1993
    {
1994
        $this->autoFilter->setRange('');
1995
1996
        return $this;
1997
    }
1998 97
1999
    /**
2000 97
     * Get collection of Tables.
2001 97
     *
2002
     * @return ArrayObject<int, Table>
2003 97
     */
2004
    public function getTableCollection(): ArrayObject
2005
    {
2006
        return $this->tableCollection;
2007
    }
2008
2009 1
    /**
2010
     * Add Table.
2011 1
     *
2012
     * @return $this
2013 1
     */
2014
    public function addTable(Table $table): self
2015 1
    {
2016
        $table->setWorksheet($this);
2017
        $this->tableCollection[] = $table;
2018 1
2019
        return $this;
2020
    }
2021
2022
    /**
2023
     * @return string[] array of Table names
2024
     */
2025
    public function getTableNames(): array
2026 91
    {
2027
        $tableNames = [];
2028 91
2029
        foreach ($this->tableCollection as $table) {
2030 91
            /** @var Table $table */
2031
            $tableNames[] = $table->getName();
2032
        }
2033
2034
        return $tableNames;
2035
    }
2036
2037
    /**
2038 92
     * @param string $name the table name to search
2039
     *
2040 92
     * @return null|Table The table from the tables collection, or null if not found
2041 92
     */
2042
    public function getTableByName(string $name): ?Table
2043 62
    {
2044 61
        $tableIndex = $this->getTableIndexByName($name);
2045
2046
        return ($tableIndex === null) ? null : $this->tableCollection[$tableIndex];
2047
    }
2048 36
2049
    /**
2050
     * @param string $name the table name to search
2051
     *
2052
     * @return null|int The index of the located table in the tables collection, or null if not found
2053
     */
2054
    protected function getTableIndexByName(string $name): ?int
2055
    {
2056
        $name = Shared\StringHelper::strToUpper($name);
2057
        foreach ($this->tableCollection as $index => $table) {
2058 1
            /** @var Table $table */
2059
            if (Shared\StringHelper::strToUpper($table->getName()) === $name) {
2060 1
                return $index;
2061
            }
2062 1
        }
2063 1
2064
        return null;
2065
    }
2066 1
2067
    /**
2068
     * Remove Table by name.
2069
     *
2070
     * @param string $name Table name
2071
     *
2072 1
     * @return $this
2073
     */
2074 1
    public function removeTableByName(string $name): self
2075
    {
2076 1
        $tableIndex = $this->getTableIndexByName($name);
2077
2078
        if ($tableIndex !== null) {
2079
            unset($this->tableCollection[$tableIndex]);
2080
        }
2081
2082 236
        return $this;
2083
    }
2084 236
2085
    /**
2086
     * Remove collection of Tables.
2087
     */
2088
    public function removeTableCollection(): self
2089
    {
2090
        $this->tableCollection = new ArrayObject();
2091
2092
        return $this;
2093
    }
2094
2095
    /**
2096
     * Get Freeze Pane.
2097
     */
2098
    public function getFreezePane(): ?string
2099
    {
2100
        return $this->freezePane;
2101
    }
2102
2103
    /**
2104
     * Freeze Pane.
2105 49
     *
2106
     * Examples:
2107 49
     *
2108 49
     *     - A2 will freeze the rows above cell A2 (i.e row 1)
2109 49
     *     - B1 will freeze the columns to the left of cell B1 (i.e column A)
2110 49
     *     - B2 will freeze the rows above and to the left of cell B2 (i.e row 1 and column A)
2111 49
     *
2112 49
     * @param null|array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
2113 49
     *            or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2114 49
     *        Passing a null value for this argument will clear any existing freeze pane for this worksheet.
2115 1
     * @param null|array{0: int, 1: int}|CellAddress|string $topLeftCell default position of the right bottom pane
2116 49
     *            Coordinate of the cell as a string, eg: 'C5'; or as an array of [$columnIndex, $row] (e.g. [3, 5]),
2117 1
     *            or a CellAddress object.
2118
     *
2119 48
     * @return $this
2120 37
     */
2121 36
    public function freezePane(null|CellAddress|string|array $coordinate, null|CellAddress|string|array $topLeftCell = null, bool $frozenSplit = false): static
2122
    {
2123 48
        $this->panes = [
2124 36
            'bottomRight' => null,
2125 36
            'bottomLeft' => null,
2126
            'topRight' => null,
2127
            'topLeft' => null,
2128 48
        ];
2129 48
        $cellAddress = ($coordinate !== null)
2130
            ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate))
2131 48
            : null;
2132 48
        if ($cellAddress !== null && Coordinate::coordinateIsRange($cellAddress)) {
2133 48
            throw new Exception('Freeze pane can not be set on a range of cells.');
2134 1
        }
2135 1
        $topLeftCell = ($topLeftCell !== null)
2136 1
            ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($topLeftCell))
2137
            : null;
2138 48
2139 48
        if ($cellAddress !== null && $topLeftCell === null) {
2140 48
            $coordinate = Coordinate::coordinateFromString($cellAddress);
2141 48
            $topLeftCell = $coordinate[0] . $coordinate[1];
2142 47
        }
2143 47
2144
        $topLeftCell = "$topLeftCell";
2145 1
        $this->paneTopLeftCell = $topLeftCell;
2146 1
2147 1
        $this->freezePane = $cellAddress;
2148
        $this->topLeftCell = $topLeftCell;
2149
        if ($cellAddress === null) {
2150
            $this->paneState = '';
2151 48
            $this->xSplit = $this->ySplit = 0;
2152
            $this->activePane = '';
2153
        } else {
2154 47
            $coordinates = Coordinate::indexesFromString($cellAddress);
2155
            $this->xSplit = $coordinates[0] - 1;
2156 47
            $this->ySplit = $coordinates[1] - 1;
2157
            if ($this->xSplit > 0 || $this->ySplit > 0) {
2158 47
                $this->paneState = $frozenSplit ? self::PANE_FROZENSPLIT : self::PANE_FROZEN;
2159
                $this->setSelectedCellsActivePane();
2160
            } else {
2161
                $this->paneState = '';
2162
                $this->freezePane = null;
2163
                $this->activePane = '';
2164
            }
2165
        }
2166 1
2167
        return $this;
2168 1
    }
2169
2170
    public function setTopLeftCell(string $topLeftCell): self
2171
    {
2172
        $this->topLeftCell = $topLeftCell;
2173
2174 415
        return $this;
2175
    }
2176 415
2177
    /**
2178
     * Unfreeze Pane.
2179 11
     *
2180
     * @return $this
2181 11
     */
2182
    public function unfreezePane(): static
2183
    {
2184 26
        return $this->freezePane(null);
2185
    }
2186 26
2187
    /**
2188 26
     * Get the default position of the right bottom pane.
2189
     */
2190
    public function getTopLeftCell(): ?string
2191 403
    {
2192
        return $this->topLeftCell;
2193 403
    }
2194
2195
    public function getPaneTopLeftCell(): string
2196 2
    {
2197
        return $this->paneTopLeftCell;
2198 2
    }
2199
2200
    public function setPaneTopLeftCell(string $paneTopLeftCell): self
2201 35
    {
2202
        $this->paneTopLeftCell = $paneTopLeftCell;
2203 35
2204 35
        return $this;
2205
    }
2206
2207 35
    public function usesPanes(): bool
2208
    {
2209
        return $this->xSplit > 0 || $this->ySplit > 0;
2210
    }
2211 3
2212
    public function getPane(string $position): ?Pane
2213 3
    {
2214
        return $this->panes[$position] ?? null;
2215
    }
2216 14
2217
    public function setPane(string $position, ?Pane $pane): self
2218 14
    {
2219
        if (array_key_exists($position, $this->panes)) {
2220
            $this->panes[$position] = $pane;
2221 48
        }
2222
2223 48
        return $this;
2224
    }
2225 48
2226
    /** @return (null|Pane)[] */
2227
    public function getPanes(): array
2228 11
    {
2229
        return $this->panes;
2230 11
    }
2231
2232
    public function getActivePane(): string
2233 11
    {
2234
        return $this->activePane;
2235 11
    }
2236 11
2237 1
    public function setActivePane(string $activePane): self
2238
    {
2239
        $this->activePane = array_key_exists($activePane, $this->panes) ? $activePane : '';
2240 11
2241
        return $this;
2242
    }
2243 11
2244
    public function getXSplit(): int
2245 11
    {
2246
        return $this->xSplit;
2247
    }
2248 26
2249
    public function setXSplit(int $xSplit): self
2250 26
    {
2251 26
        $this->xSplit = $xSplit;
2252 1
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
2253
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
2254
        }
2255 26
2256
        return $this;
2257
    }
2258 21
2259
    public function getYSplit(): int
2260 21
    {
2261
        return $this->ySplit;
2262
    }
2263
2264
    public function setYSplit(int $ySplit): self
2265
    {
2266
        $this->ySplit = $ySplit;
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 getPaneState(): string
2275 3
    {
2276
        return $this->paneState;
2277
    }
2278 26
2279
    public const PANE_FROZEN = 'frozen';
2280
    public const PANE_FROZENSPLIT = 'frozenSplit';
2281
    public const PANE_SPLIT = 'split';
2282
    private const VALIDPANESTATE = [self::PANE_FROZEN, self::PANE_SPLIT, self::PANE_FROZENSPLIT];
2283
    private const VALIDFROZENSTATE = [self::PANE_FROZEN, self::PANE_FROZENSPLIT];
2284
2285
    public function setPaneState(string $paneState): self
2286
    {
2287
        $this->paneState = in_array($paneState, self::VALIDPANESTATE, true) ? $paneState : '';
2288
        if (in_array($this->paneState, self::VALIDFROZENSTATE, true)) {
2289 37
            $this->freezePane([$this->xSplit + 1, $this->ySplit + 1], $this->topLeftCell, $this->paneState === self::PANE_FROZENSPLIT);
2290
        } else {
2291 37
            $this->freezePane = null;
2292 36
        }
2293 36
2294
        return $this;
2295 1
    }
2296
2297
    /**
2298 36
     * Insert a new row, updating all possible related data.
2299
     *
2300
     * @param int $before Insert before this row number
2301
     * @param int $numberOfRows Number of new rows to insert
2302
     *
2303
     * @return $this
2304
     */
2305
    public function insertNewRowBefore(int $before, int $numberOfRows = 1): static
2306
    {
2307
        if ($before >= 1) {
2308
            $objReferenceHelper = ReferenceHelper::getInstance();
2309 43
            $objReferenceHelper->insertNewBefore('A' . $before, 0, $numberOfRows, $this);
2310
        } else {
2311 43
            throw new Exception('Rows can only be inserted before at least row 1.');
2312 42
        }
2313 42
2314
        return $this;
2315 1
    }
2316
2317
    /**
2318 42
     * Insert a new column, updating all possible related data.
2319
     *
2320
     * @param string $before Insert before this column Name, eg: 'A'
2321
     * @param int $numberOfColumns Number of new columns to insert
2322
     *
2323
     * @return $this
2324
     */
2325
    public function insertNewColumnBefore(string $before, int $numberOfColumns = 1): static
2326
    {
2327
        if (!is_numeric($before)) {
2328
            $objReferenceHelper = ReferenceHelper::getInstance();
2329 2
            $objReferenceHelper->insertNewBefore($before . '1', $numberOfColumns, 0, $this);
2330
        } else {
2331 2
            throw new Exception('Column references should not be numeric.');
2332 1
        }
2333
2334
        return $this;
2335 1
    }
2336
2337
    /**
2338
     * Insert a new column, updating all possible related data.
2339
     *
2340
     * @param int $beforeColumnIndex Insert before this column ID (numeric column coordinate of the cell)
2341
     * @param int $numberOfColumns Number of new columns to insert
2342
     *
2343
     * @return $this
2344
     */
2345
    public function insertNewColumnBeforeByIndex(int $beforeColumnIndex, int $numberOfColumns = 1): static
2346 41
    {
2347
        if ($beforeColumnIndex >= 1) {
2348 41
            return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $numberOfColumns);
2349 1
        }
2350
2351
        throw new Exception('Columns can only be inserted before at least column A (1).');
2352 40
    }
2353 40
2354 40
    /**
2355
     * Delete a row, updating all possible related data.
2356 40
     *
2357 40
     * @param int $row Remove rows, starting with this row number
2358 36
     * @param int $numberOfRows Number of rows to remove
2359 36
     *
2360
     * @return $this
2361
     */
2362
    public function removeRow(int $row, int $numberOfRows = 1): static
2363 40
    {
2364 40
        if ($row < 1) {
2365 40
            throw new Exception('Rows to be deleted should at least start from row 1.');
2366 36
        }
2367 36
2368
        $holdRowDimensions = $this->removeRowDimensions($row, $numberOfRows);
2369
        $highestRow = $this->getHighestDataRow();
2370 40
        $removedRowsCounter = 0;
2371
2372 40
        for ($r = 0; $r < $numberOfRows; ++$r) {
2373
            if ($row + $r <= $highestRow) {
2374
                $this->cellCollection->removeRow($row + $r);
2375 40
                ++$removedRowsCounter;
2376
            }
2377 40
        }
2378 40
2379 40
        $objReferenceHelper = ReferenceHelper::getInstance();
2380 4
        $objReferenceHelper->insertNewBefore('A' . ($row + $numberOfRows), 0, -$numberOfRows, $this);
2381 4
        for ($r = 0; $r < $removedRowsCounter; ++$r) {
2382 3
            $this->cellCollection->removeRow($highestRow);
2383 4
            --$highestRow;
2384 4
        }
2385 4
2386 4
        $this->rowDimensions = $holdRowDimensions;
2387 4
2388
        return $this;
2389
    }
2390
2391 40
    private function removeRowDimensions(int $row, int $numberOfRows): array
2392
    {
2393
        $highRow = $row + $numberOfRows - 1;
2394
        $holdRowDimensions = [];
2395
        foreach ($this->rowDimensions as $rowDimension) {
2396
            $num = $rowDimension->getRowIndex();
2397
            if ($num < $row) {
2398
                $holdRowDimensions[$num] = $rowDimension;
2399
            } elseif ($num > $highRow) {
2400
                $num -= $numberOfRows;
2401
                $cloneDimension = clone $rowDimension;
2402 33
                $cloneDimension->setRowIndex($num);
2403
                $holdRowDimensions[$num] = $cloneDimension;
2404 33
            }
2405 1
        }
2406
2407
        return $holdRowDimensions;
2408 32
    }
2409 32
2410 32
    /**
2411
     * Remove a column, updating all possible related data.
2412 32
     *
2413
     * @param string $column Remove columns starting with this column name, eg: 'A'
2414 32
     * @param int $numberOfColumns Number of columns to remove
2415 32
     *
2416 32
     * @return $this
2417
     */
2418 32
    public function removeColumn(string $column, int $numberOfColumns = 1): static
2419
    {
2420 32
        if (is_numeric($column)) {
2421 2
            throw new Exception('Column references should not be numeric.');
2422
        }
2423
2424 30
        $highestColumn = $this->getHighestDataColumn();
2425
        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
2426 30
        $pColumnIndex = Coordinate::columnIndexFromString($column);
2427 30
2428 30
        $holdColumnDimensions = $this->removeColumnDimensions($pColumnIndex, $numberOfColumns);
2429
2430
        $column = Coordinate::stringFromColumnIndex($pColumnIndex + $numberOfColumns);
2431 30
        $objReferenceHelper = ReferenceHelper::getInstance();
2432
        $objReferenceHelper->insertNewBefore($column . '1', -$numberOfColumns, 0, $this);
2433 30
2434
        $this->columnDimensions = $holdColumnDimensions;
2435
2436 32
        if ($pColumnIndex > $highestColumnIndex) {
2437
            return $this;
2438 32
        }
2439 32
2440 32
        $maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1;
2441 18
2442 18
        for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $numberOfColumns); $c < $n; ++$c) {
2443 18
            $this->cellCollection->removeColumn($highestColumn);
2444 18
            $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1);
2445 18
        }
2446 18
2447 18
        $this->garbageCollect();
2448 18
2449 18
        return $this;
2450
    }
2451
2452
    private function removeColumnDimensions(int $pColumnIndex, int $numberOfColumns): array
2453 32
    {
2454
        $highCol = $pColumnIndex + $numberOfColumns - 1;
2455
        $holdColumnDimensions = [];
2456
        foreach ($this->columnDimensions as $columnDimension) {
2457
            $num = $columnDimension->getColumnNumeric();
2458
            if ($num < $pColumnIndex) {
2459
                $str = $columnDimension->getColumnIndex();
2460
                $holdColumnDimensions[$str] = $columnDimension;
2461
            } elseif ($num > $highCol) {
2462
                $cloneDimension = clone $columnDimension;
2463
                $cloneDimension->setColumnNumeric($num - $numberOfColumns);
2464 2
                $str = $cloneDimension->getColumnIndex();
2465
                $holdColumnDimensions[$str] = $cloneDimension;
2466 2
            }
2467 1
        }
2468
2469
        return $holdColumnDimensions;
2470 1
    }
2471
2472
    /**
2473
     * Remove a column, updating all possible related data.
2474
     *
2475
     * @param int $columnIndex Remove starting with this column Index (numeric column coordinate)
2476 969
     * @param int $numColumns Number of columns to remove
2477
     *
2478 969
     * @return $this
2479
     */
2480
    public function removeColumnByIndex(int $columnIndex, int $numColumns = 1): static
2481
    {
2482
        if ($columnIndex >= 1) {
2483
            return $this->removeColumn(Coordinate::stringFromColumnIndex($columnIndex), $numColumns);
2484
        }
2485
2486
        throw new Exception('Columns to be deleted should at least start from column A (1)');
2487
    }
2488 812
2489
    /**
2490 812
     * Show gridlines?
2491
     */
2492 812
    public function getShowGridlines(): bool
2493
    {
2494
        return $this->showGridlines;
2495
    }
2496
2497
    /**
2498 974
     * Set show gridlines.
2499
     *
2500 974
     * @param bool $showGridLines Show gridlines (true/false)
2501
     *
2502
     * @return $this
2503
     */
2504
    public function setShowGridlines(bool $showGridLines): self
2505
    {
2506
        $this->showGridlines = $showGridLines;
2507
2508
        return $this;
2509
    }
2510 562
2511
    /**
2512 562
     * Print gridlines?
2513
     */
2514 562
    public function getPrintGridlines(): bool
2515
    {
2516
        return $this->printGridlines;
2517
    }
2518
2519
    /**
2520 461
     * Set print gridlines.
2521
     *
2522 461
     * @param bool $printGridLines Print gridlines (true/false)
2523
     *
2524
     * @return $this
2525
     */
2526
    public function setPrintGridlines(bool $printGridLines): self
2527
    {
2528
        $this->printGridlines = $printGridLines;
2529
2530
        return $this;
2531
    }
2532 353
2533
    /**
2534 353
     * Show row and column headers?
2535
     */
2536 353
    public function getShowRowColHeaders(): bool
2537
    {
2538
        return $this->showRowColHeaders;
2539
    }
2540
2541
    /**
2542 462
     * Set show row and column headers.
2543
     *
2544 462
     * @param bool $showRowColHeaders Show row and column headers (true/false)
2545
     *
2546
     * @return $this
2547
     */
2548
    public function setShowRowColHeaders(bool $showRowColHeaders): self
2549
    {
2550
        $this->showRowColHeaders = $showRowColHeaders;
2551
2552
        return $this;
2553
    }
2554 358
2555
    /**
2556 358
     * Show summary below? (Row/Column outlining).
2557
     */
2558 358
    public function getShowSummaryBelow(): bool
2559
    {
2560
        return $this->showSummaryBelow;
2561
    }
2562
2563
    /**
2564 462
     * Set show summary below.
2565
     *
2566 462
     * @param bool $showSummaryBelow Show summary below (true/false)
2567
     *
2568
     * @return $this
2569
     */
2570
    public function setShowSummaryBelow(bool $showSummaryBelow): self
2571
    {
2572
        $this->showSummaryBelow = $showSummaryBelow;
2573
2574
        return $this;
2575
    }
2576 358
2577
    /**
2578 358
     * Show summary right? (Row/Column outlining).
2579
     */
2580 358
    public function getShowSummaryRight(): bool
2581
    {
2582
        return $this->showSummaryRight;
2583
    }
2584
2585
    /**
2586
     * Set show summary right.
2587
     *
2588 1002
     * @param bool $showSummaryRight Show summary right (true/false)
2589
     *
2590 1002
     * @return $this
2591
     */
2592
    public function setShowSummaryRight(bool $showSummaryRight): self
2593
    {
2594
        $this->showSummaryRight = $showSummaryRight;
2595
2596
        return $this;
2597
    }
2598
2599
    /**
2600 91
     * Get comments.
2601
     *
2602 91
     * @return Comment[]
2603
     */
2604 91
    public function getComments(): array
2605
    {
2606
        return $this->comments;
2607
    }
2608
2609
    /**
2610
     * Set comments array for the entire sheet.
2611
     *
2612
     * @param Comment[] $comments
2613
     *
2614
     * @return $this
2615 44
     */
2616
    public function setComments(array $comments): self
2617 44
    {
2618
        $this->comments = $comments;
2619 44
2620 1
        return $this;
2621 43
    }
2622 1
2623 42
    /**
2624 1
     * Remove comment from cell.
2625
     *
2626
     * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5';
2627 41
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2628 2
     *
2629
     * @return $this
2630
     */
2631 41
    public function removeComment(CellAddress|string|array $cellCoordinate): self
2632
    {
2633
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate));
2634
2635
        if (Coordinate::coordinateIsRange($cellAddress)) {
2636
            throw new Exception('Cell coordinate string can not be a range of cells.');
2637
        } elseif (str_contains($cellAddress, '$')) {
2638
            throw new Exception('Cell coordinate string must not be absolute.');
2639
        } elseif ($cellAddress == '') {
2640 108
            throw new Exception('Cell coordinate can not be zero-length string.');
2641
        }
2642 108
        // Check if we have a comment for this cell and delete it
2643
        if (isset($this->comments[$cellAddress])) {
2644 108
            unset($this->comments[$cellAddress]);
2645 1
        }
2646 107
2647 1
        return $this;
2648 106
    }
2649 1
2650
    /**
2651
     * Get comment for cell.
2652
     *
2653 105
     * @param array{0: int, 1: int}|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5';
2654 72
     *               or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
2655
     */
2656
    public function getComment(CellAddress|string|array $cellCoordinate, bool $attachNew = true): Comment
2657
    {
2658 105
        $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate));
2659 105
2660 105
        if (Coordinate::coordinateIsRange($cellAddress)) {
2661
            throw new Exception('Cell coordinate string can not be a range of cells.');
2662
        } elseif (str_contains($cellAddress, '$')) {
2663 105
            throw new Exception('Cell coordinate string must not be absolute.');
2664
        } elseif ($cellAddress == '') {
2665
            throw new Exception('Cell coordinate can not be zero-length string.');
2666
        }
2667
2668
        // Check if we already have a comment for this cell.
2669
        if (isset($this->comments[$cellAddress])) {
2670
            return $this->comments[$cellAddress];
2671 10048
        }
2672
2673 10048
        // If not, create a new comment.
2674
        $newComment = new Comment();
2675
        if ($attachNew) {
2676
            $this->comments[$cellAddress] = $newComment;
2677
        }
2678
2679 10088
        return $newComment;
2680
    }
2681 10088
2682
    /**
2683
     * Get active cell.
2684
     *
2685
     * @return string Example: 'A1'
2686
     */
2687
    public function getActiveCell(): string
2688
    {
2689
        return $this->activeCell;
2690
    }
2691 36
2692
    /**
2693 36
     * Get selected cells.
2694
     */
2695
    public function getSelectedCells(): string
2696
    {
2697
        return $this->selectedCells;
2698
    }
2699
2700
    /**
2701
     * Selected cell.
2702
     *
2703
     * @param string $coordinate Cell (i.e. A1)
2704
     *
2705 10067
     * @return $this
2706
     */
2707 10067
    public function setSelectedCell(string $coordinate): static
2708 10067
    {
2709
        return $this->setSelectedCells($coordinate);
2710 10067
    }
2711
2712 10067
    /**
2713 475
     * Select a range of cells.
2714 475
     *
2715
     * @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'
2716 10038
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
2717
     *              or a CellAddress or AddressRange object.
2718 10067
     *
2719 10067
     * @return $this
2720
     */
2721 10067
    public function setSelectedCells(AddressRange|CellAddress|int|string|array $coordinate): static
2722
    {
2723
        if (is_string($coordinate)) {
2724 10068
            $coordinate = Validations::definedNameToCoordinate($coordinate, $this);
2725
        }
2726 10068
        $coordinate = Validations::validateCellOrCellRange($coordinate);
2727 47
2728 47
        if (Coordinate::coordinateIsRange($coordinate)) {
2729 47
            [$first] = Coordinate::splitRange($coordinate);
2730 26
            $this->activeCell = $first[0];
2731 23
        } else {
2732 3
            $this->activeCell = $coordinate;
2733 21
        }
2734 21
        $this->selectedCells = $coordinate;
2735
        $this->setSelectedCellsActivePane();
2736 10
2737
        return $this;
2738 47
    }
2739 47
2740
    private function setSelectedCellsActivePane(): void
2741
    {
2742
        if (!empty($this->freezePane)) {
2743
            $coordinateC = Coordinate::indexesFromString($this->freezePane);
2744
            $coordinateT = Coordinate::indexesFromString($this->activeCell);
2745
            if ($coordinateC[0] === 1) {
2746 461
                $activePane = ($coordinateT[1] <= $coordinateC[1]) ? 'topLeft' : 'bottomLeft';
2747
            } elseif ($coordinateC[1] === 1) {
2748 461
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight';
2749
            } elseif ($coordinateT[1] <= $coordinateC[1]) {
2750
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'topLeft' : 'topRight';
2751
            } else {
2752
                $activePane = ($coordinateT[0] <= $coordinateC[0]) ? 'bottomLeft' : 'bottomRight';
2753
            }
2754
            $this->setActivePane($activePane);
2755
            $this->panes[$activePane] = new Pane($activePane, $this->selectedCells, $this->activeCell);
2756
        }
2757
    }
2758 127
2759
    /**
2760 127
     * Get right-to-left.
2761
     */
2762 127
    public function getRightToLeft(): bool
2763
    {
2764
        return $this->rightToLeft;
2765
    }
2766
2767
    /**
2768
     * Set right-to-left.
2769
     *
2770
     * @param bool $value Right-to-left true/false
2771
     *
2772
     * @return $this
2773
     */
2774
    public function setRightToLeft(bool $value): static
2775 740
    {
2776
        $this->rightToLeft = $value;
2777
2778 740
        return $this;
2779 42
    }
2780
2781
    /**
2782
     * Fill worksheet from values in array.
2783 740
     *
2784
     * @param array $source Source array
2785
     * @param mixed $nullValue Value in source array that stands for blank cell
2786 740
     * @param string $startCell Insert array starting from this cell address as the top left coordinate
2787 344
     * @param bool $strictNullComparison Apply strict comparison when testing for null values in the array
2788 344
     *
2789 344
     * @return $this
2790 344
     */
2791
    public function fromArray(array $source, mixed $nullValue = null, string $startCell = 'A1', bool $strictNullComparison = false): static
2792 344
    {
2793
        //    Convert a 1-D array to 2-D (for ease of looping)
2794 344
        if (!is_array(end($source))) {
2795
            $source = [$source];
2796 344
        }
2797
2798
        // start coordinate
2799 397
        [$startColumn, $startRow] = Coordinate::coordinateFromString($startCell);
2800 397
2801 397
        // Loop through $source
2802 396
        if ($strictNullComparison) {
2803
            foreach ($source as $rowData) {
2804 390
                $currentColumn = $startColumn;
2805
                foreach ($rowData as $cellValue) {
2806 396
                    if ($cellValue !== $nullValue) {
2807
                        // Set cell value
2808 397
                        $this->getCell($currentColumn . $startRow)->setValue($cellValue);
2809
                    }
2810
                    ++$currentColumn;
2811
                }
2812 740
                ++$startRow;
2813
            }
2814
        } else {
2815
            foreach ($source as $rowData) {
2816
                $currentColumn = $startColumn;
2817
                foreach ($rowData as $cellValue) {
2818
                    if ($cellValue != $nullValue) {
2819
                        // Set cell value
2820
                        $this->getCell($currentColumn . $startRow)->setValue($cellValue);
2821 165
                    }
2822
                    ++$currentColumn;
2823 165
                }
2824
                ++$startRow;
2825 165
            }
2826 165
        }
2827 4
2828
        return $this;
2829 165
    }
2830
2831
    /**
2832 165
     * @param null|bool|float|int|RichText|string $nullValue value to use when null
2833 105
     *
2834
     * @throws Exception
2835 105
     * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
2836 105
     */
2837 105
    protected function cellToArray(Cell $cell, bool $calculateFormulas, bool $formatData, mixed $nullValue): mixed
2838 105
    {
2839 105
        $returnValue = $nullValue;
2840
2841
        if ($cell->getValue() !== null) {
2842
            if ($cell->getValue() instanceof RichText) {
2843 165
                $returnValue = $cell->getValue()->getPlainText();
2844
            } else {
2845
                $returnValue = ($calculateFormulas) ? $cell->getCalculatedValue() : $cell->getValue();
2846
            }
2847
2848
            if ($formatData) {
2849
                $style = $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex());
2850
                /** @var null|bool|float|int|RichText|string */
2851
                $returnValuex = $returnValue;
2852
                $returnValue = NumberFormat::toFormattedString(
2853
                    $returnValuex,
2854
                    $style->getNumberFormat()->getFormatCode() ?? NumberFormat::FORMAT_GENERAL
2855
                );
2856
            }
2857 138
        }
2858
2859
        return $returnValue;
2860
    }
2861
2862
    /**
2863
     * Create array from a range of cells.
2864
     *
2865
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
2866 138
     * @param bool $calculateFormulas Should formulas be calculated?
2867
     * @param bool $formatData Should formatting be applied to cell values?
2868
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2869 138
     *                             True - Return rows and columns indexed by their actual row and column IDs
2870 138
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2871
     *                            True - Don't return values for rows/columns that are defined as hidden.
2872
     */
2873
    public function rangeToArray(
2874 138
        string $range,
2875
        mixed $nullValue = null,
2876
        bool $calculateFormulas = true,
2877
        bool $formatData = true,
2878
        bool $returnCellRef = false,
2879
        bool $ignoreHidden = false,
2880
        bool $reduceArrays = false
2881
    ): array {
2882
        $returnValue = [];
2883
2884
        // Loop through rows
2885
        foreach ($this->rangeToArrayYieldRows($range, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays) as $rowRef => $rowArray) {
2886
            $returnValue[$rowRef] = $rowArray;
2887
        }
2888
2889
        // Return
2890 165
        return $returnValue;
2891
    }
2892
2893
    /**
2894
     * Create array from a range of cells, yielding each row in turn.
2895
     *
2896
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
2897
     * @param bool $calculateFormulas Should formulas be calculated?
2898
     * @param bool $formatData Should formatting be applied to cell values?
2899 165
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2900
     *                             True - Return rows and columns indexed by their actual row and column IDs
2901
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2902 165
     *                            True - Don't return values for rows/columns that are defined as hidden.
2903 165
     *
2904 165
     * @return Generator<array>
2905 165
     */
2906 165
    public function rangeToArrayYieldRows(
2907 165
        string $range,
2908 165
        mixed $nullValue = null,
2909
        bool $calculateFormulas = true,
2910 165
        bool $formatData = true,
2911
        bool $returnCellRef = false,
2912 165
        bool $ignoreHidden = false,
2913 165
        bool $reduceArrays = false
2914 165
    ) {
2915
        $range = Validations::validateCellOrCellRange($range);
2916 165
2917 165
        //    Identify the range that we need to extract from the worksheet
2918 165
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
2919
        $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]);
2920 165
        $minRow = $rangeStart[1];
2921 165
        $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]);
2922 4
        $maxRow = $rangeEnd[1];
2923
        $minColInt = $rangeStart[0];
2924 165
        $maxColInt = $rangeEnd[0];
2925 165
2926
        ++$maxCol;
2927 165
        /** @var array<string, bool> */
2928 165
        $hiddenColumns = [];
2929 165
        $nullRow = $this->buildNullRow($nullValue, $minCol, $maxCol, $returnCellRef, $ignoreHidden, $hiddenColumns);
2930 48
        $hideColumns = !empty($hiddenColumns);
2931
2932 165
        $keys = $this->cellCollection->getSortedCoordinatesInt();
2933 165
        $keyIndex = 0;
2934 165
        $keysCount = count($keys);
2935 165
        // Loop through rows
2936 165
        for ($row = $minRow; $row <= $maxRow; ++$row) {
2937 165
            if (($ignoreHidden === true) && ($this->isRowVisible($row) === false)) {
2938 165
                continue;
2939 165
            }
2940 165
            $rowRef = $returnCellRef ? $row : ($row - $minRow);
2941 165
            $returnValue = $nullRow;
2942 165
2943 165
            $index = ($row - 1) * AddressRange::MAX_COLUMN_INT + 1;
2944 21
            $indexPlus = $index + AddressRange::MAX_COLUMN_INT - 1;
2945 18
            while ($keyIndex < $keysCount && $keys[$keyIndex] < $index) {
2946
                ++$keyIndex;
2947
            }
2948 165
            while ($keyIndex < $keysCount && $keys[$keyIndex] <= $indexPlus) {
2949 165
                $key = $keys[$keyIndex];
2950
                $thisRow = intdiv($key - 1, AddressRange::MAX_COLUMN_INT) + 1;
2951
                $thisCol = ($key % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT;
2952
                if ($thisCol >= $minColInt && $thisCol <= $maxColInt) {
2953
                    $col = Coordinate::stringFromColumnIndex($thisCol);
2954 165
                    if ($hideColumns === false || !isset($hiddenColumns[$col])) {
2955
                        $columnRef = $returnCellRef ? $col : ($thisCol - $minColInt);
2956
                        $cell = $this->cellCollection->get("{$col}{$thisRow}");
2957 165
                        if ($cell !== null) {
2958
                            $value = $this->cellToArray($cell, $calculateFormulas, $formatData, $nullValue);
2959
                            if ($reduceArrays) {
2960
                                while (is_array($value)) {
2961
                                    $value = array_shift($value);
2962
                                }
2963
                            }
2964
                            if ($value !== $nullValue) {
2965
                                $returnValue[$columnRef] = $value;
2966
                            }
2967
                        }
2968
                    }
2969
                }
2970
                ++$keyIndex;
2971
            }
2972
2973 165
            yield $rowRef => $returnValue;
2974
        }
2975
    }
2976
2977
    /**
2978
     * Prepare a row data filled with null values to deduplicate the memory areas for empty rows.
2979
     *
2980
     * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
2981 165
     * @param string $minCol Start column of the range
2982 165
     * @param string $maxCol End column of the range
2983 165
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
2984 165
     *                              True - Return rows and columns indexed by their actual row and column IDs
2985 2
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
2986
     *                             True - Don't return values for rows/columns that are defined as hidden.
2987 165
     * @param array<string, bool> $hiddenColumns
2988 165
     */
2989
    private function buildNullRow(
2990
        mixed $nullValue,
2991
        string $minCol,
2992 165
        string $maxCol,
2993
        bool $returnCellRef,
2994
        bool $ignoreHidden,
2995 17
        array &$hiddenColumns
2996
    ): array {
2997 17
        $nullRow = [];
2998 17
        $c = -1;
2999 6
        for ($col = $minCol; $col !== $maxCol; ++$col) {
3000 5
            if ($ignoreHidden === true && $this->columnDimensionExists($col) && $this->getColumnDimension($col)->getVisible() === false) {
3001
                $hiddenColumns[$col] = true;
3002
            } else {
3003 1
                $columnRef = $returnCellRef ? $col : ++$c;
3004
                $nullRow[$columnRef] = $nullValue;
3005
            }
3006 11
        }
3007
3008
        return $nullRow;
3009
    }
3010
3011
    private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName
3012
    {
3013
        $namedRange = DefinedName::resolveName($definedName, $this);
3014 11
        if ($namedRange === null) {
3015 2
            if ($returnNullIfInvalid) {
3016 2
                return null;
3017
            }
3018
3019
            throw new Exception('Named Range ' . $definedName . ' does not exist.');
3020
        }
3021
3022
        if ($namedRange->isFormula()) {
3023
            if ($returnNullIfInvalid) {
3024
                return null;
3025
            }
3026
3027 11
            throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.');
3028
        }
3029
3030
        if ($namedRange->getLocalOnly()) {
3031
            $worksheet = $namedRange->getWorksheet();
3032
            if ($worksheet === null || $this->hash !== $worksheet->getHashInt()) {
3033
                if ($returnNullIfInvalid) {
3034
                    return null;
3035
                }
3036
3037
                throw new Exception(
3038
                    'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle()
3039
                );
3040
            }
3041
        }
3042 2
3043
        return $namedRange;
3044
    }
3045
3046
    /**
3047
     * Create array from a range of cells.
3048
     *
3049
     * @param string $definedName The Named Range that should be returned
3050
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3051 2
     * @param bool $calculateFormulas Should formulas be calculated?
3052 2
     * @param bool $formatData Should formatting be applied to cell values?
3053 1
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3054 1
     *                             True - Return rows and columns indexed by their actual row and column IDs
3055 1
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3056 1
     *                            True - Don't return values for rows/columns that are defined as hidden.
3057 1
     */
3058 1
    public function namedRangeToArray(
3059
        string $definedName,
3060
        mixed $nullValue = null,
3061
        bool $calculateFormulas = true,
3062 1
        bool $formatData = true,
3063
        bool $returnCellRef = false,
3064
        bool $ignoreHidden = false,
3065
        bool $reduceArrays = false
3066
    ): array {
3067
        $retVal = [];
3068
        $namedRange = $this->validateNamedRange($definedName);
3069
        if ($namedRange !== null) {
3070
            $cellRange = ltrim(substr($namedRange->getValue(), (int) strrpos($namedRange->getValue(), '!')), '!');
3071
            $cellRange = str_replace('$', '', $cellRange);
3072
            $workSheet = $namedRange->getWorksheet();
3073
            if ($workSheet !== null) {
3074
                $retVal = $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays);
3075
            }
3076 72
        }
3077
3078
        return $retVal;
3079
    }
3080
3081
    /**
3082
     * Create array from worksheet.
3083
     *
3084
     * @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
3085 72
     * @param bool $calculateFormulas Should formulas be calculated?
3086 72
     * @param bool $formatData Should formatting be applied to cell values?
3087
     * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
3088
     *                             True - Return rows and columns indexed by their actual row and column IDs
3089 72
     * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden.
3090 72
     *                            True - Don't return values for rows/columns that are defined as hidden.
3091
     */
3092
    public function toArray(
3093 72
        mixed $nullValue = null,
3094
        bool $calculateFormulas = true,
3095
        bool $formatData = true,
3096
        bool $returnCellRef = false,
3097
        bool $ignoreHidden = false,
3098
        bool $reduceArrays = false
3099
    ): array {
3100
        // Garbage collect...
3101
        $this->garbageCollect();
3102 83
        $this->calculateArrays($calculateFormulas);
3103
3104 83
        //    Identify the range that we need to extract from the worksheet
3105
        $maxCol = $this->getHighestColumn();
3106
        $maxRow = $this->getHighestRow();
3107
3108
        // Return
3109
        return $this->rangeToArray("A1:{$maxCol}{$maxRow}", $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden, $reduceArrays);
3110
    }
3111
3112
    /**
3113 19
     * Get row iterator.
3114
     *
3115 19
     * @param int $startRow The row number at which to start iterating
3116
     * @param ?int $endRow The row number at which to stop iterating
3117
     */
3118
    public function getRowIterator(int $startRow = 1, ?int $endRow = null): RowIterator
3119
    {
3120
        return new RowIterator($this, $startRow, $endRow);
3121
    }
3122
3123 1079
    /**
3124
     * Get column iterator.
3125
     *
3126 1079
     * @param string $startColumn The column address at which to start iterating
3127
     * @param ?string $endColumn The column address at which to stop iterating
3128
     */
3129 1079
    public function getColumnIterator(string $startColumn = 'A', ?string $endColumn = null): ColumnIterator
3130 1079
    {
3131 1079
        return new ColumnIterator($this, $startColumn, $endColumn);
3132
    }
3133
3134 1079
    /**
3135 146
     * Run PhpSpreadsheet garbage collector.
3136
     *
3137
     * @return $this
3138
     */
3139 1079
    public function garbageCollect(): static
3140 89
    {
3141
        // Flush cache
3142
        $this->cellCollection->get('A1');
3143
3144 1079
        // Lookup highest column and highest row if cells are cleaned
3145
        $colRow = $this->cellCollection->getHighestRowAndColumn();
3146
        $highestRow = $colRow['row'];
3147 1079
        $highestColumn = Coordinate::columnIndexFromString($colRow['column']);
3148
3149 1079
        // Loop through column dimensions
3150
        foreach ($this->columnDimensions as $dimension) {
3151
            $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex()));
3152 1079
        }
3153
3154
        // Loop through row dimensions
3155
        foreach ($this->rowDimensions as $dimension) {
3156
            $highestRow = max($highestRow, $dimension->getRowIndex());
3157
        }
3158
3159
        // Cache values
3160
        if ($highestColumn < 1) {
3161
            $this->cachedHighestColumn = 1;
3162
        } else {
3163 10375
            $this->cachedHighestColumn = $highestColumn;
3164
        }
3165 10375
        $this->cachedHighestRow = $highestRow;
3166
3167
        // Return
3168
        return $this;
3169
    }
3170
3171
    /**
3172
     * @deprecated 3.5.0 use getHashInt instead.
3173
     */
3174
    public function getHashCode(): string
3175
    {
3176
        return (string) $this->hash;
3177
    }
3178
3179
    public function getHashInt(): int
3180
    {
3181
        return $this->hash;
3182
    }
3183 10269
3184
    /**
3185 10269
     * Extract worksheet title from range.
3186 13
     *
3187
     * Example: extractSheetTitle("testSheet!A1") ==> 'A1'
3188
     * Example: extractSheetTitle("testSheet!A1:C3") ==> 'A1:C3'
3189
     * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1'];
3190 10267
     * Example: extractSheetTitle("'testSheet 1'!A1:C3", true) ==> ['testSheet 1', 'A1:C3'];
3191 10241
     * Example: extractSheetTitle("A1", true) ==> ['', 'A1'];
3192
     * Example: extractSheetTitle("A1:C3", true) ==> ['', 'A1:C3']
3193
     *
3194 1323
     * @param ?string $range Range to extract title from
3195 1323
     * @param bool $returnRange Return range? (see example)
3196
     *
3197
     * @return ($range is non-empty-string ? ($returnRange is true ? array{0: string, 1: string} : string) : ($returnRange is true ? array{0: null, 1: null} : null))
3198 7
     */
3199
    public static function extractSheetTitle(?string $range, bool $returnRange = false): array|null|string
3200
    {
3201
        if (empty($range)) {
3202
            return $returnRange ? [null, null] : null;
3203
        }
3204
3205
        // Sheet title included?
3206 87
        if (($sep = strrpos($range, '!')) === false) {
3207
            return $returnRange ? ['', $range] : '';
3208
        }
3209 87
3210 40
        if ($returnRange) {
3211
            return [substr($range, 0, $sep), substr($range, $sep + 1)];
3212
        }
3213
3214 87
        return substr($range, $sep + 1);
3215
    }
3216 87
3217
    /**
3218
     * Get hyperlink.
3219
     *
3220
     * @param string $cellCoordinate Cell coordinate to get hyperlink for, eg: 'A1'
3221
     */
3222
    public function getHyperlink(string $cellCoordinate): Hyperlink
3223
    {
3224
        // return hyperlink if we already have one
3225
        if (isset($this->hyperlinkCollection[$cellCoordinate])) {
3226 42
            return $this->hyperlinkCollection[$cellCoordinate];
3227
        }
3228 42
3229 41
        // else create hyperlink
3230
        $this->hyperlinkCollection[$cellCoordinate] = new Hyperlink();
3231 21
3232
        return $this->hyperlinkCollection[$cellCoordinate];
3233
    }
3234 42
3235
    /**
3236
     * Set hyperlink.
3237
     *
3238
     * @param string $cellCoordinate Cell coordinate to insert hyperlink, eg: 'A1'
3239
     *
3240
     * @return $this
3241
     */
3242 522
    public function setHyperlink(string $cellCoordinate, ?Hyperlink $hyperlink = null): static
3243
    {
3244 522
        if ($hyperlink === null) {
3245
            unset($this->hyperlinkCollection[$cellCoordinate]);
3246
        } else {
3247
            $this->hyperlinkCollection[$cellCoordinate] = $hyperlink;
3248
        }
3249
3250
        return $this;
3251
    }
3252 536
3253
    /**
3254 536
     * Hyperlink at a specific coordinate exists?
3255
     *
3256
     * @param string $coordinate eg: 'A1'
3257
     */
3258
    public function hyperlinkExists(string $coordinate): bool
3259
    {
3260
        return isset($this->hyperlinkCollection[$coordinate]);
3261
    }
3262 31
3263
    /**
3264
     * Get collection of hyperlinks.
3265 31
     *
3266 20
     * @return Hyperlink[]
3267
     */
3268
    public function getHyperlinkCollection(): array
3269
    {
3270 30
        return $this->hyperlinkCollection;
3271
    }
3272 30
3273
    /**
3274
     * Get data validation.
3275
     *
3276
     * @param string $cellCoordinate Cell coordinate to get data validation for, eg: 'A1'
3277
     */
3278
    public function getDataValidation(string $cellCoordinate): DataValidation
3279
    {
3280
        // return data validation if we already have one
3281
        if (isset($this->dataValidationCollection[$cellCoordinate])) {
3282 48
            return $this->dataValidationCollection[$cellCoordinate];
3283
        }
3284 48
3285 43
        // else create data validation
3286
        $this->dataValidationCollection[$cellCoordinate] = new DataValidation();
3287 9
3288
        return $this->dataValidationCollection[$cellCoordinate];
3289
    }
3290 48
3291
    /**
3292
     * Set data validation.
3293
     *
3294
     * @param string $cellCoordinate Cell coordinate to insert data validation, eg: 'A1'
3295
     *
3296
     * @return $this
3297
     */
3298 18
    public function setDataValidation(string $cellCoordinate, ?DataValidation $dataValidation = null): static
3299
    {
3300 18
        if ($dataValidation === null) {
3301
            unset($this->dataValidationCollection[$cellCoordinate]);
3302
        } else {
3303
            $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
3304
        }
3305
3306
        return $this;
3307
    }
3308 536
3309
    /**
3310 536
     * Data validation at a specific coordinate exists?
3311
     *
3312
     * @param string $coordinate eg: 'A1'
3313
     */
3314
    public function dataValidationExists(string $coordinate): bool
3315
    {
3316
        return isset($this->dataValidationCollection[$coordinate]);
3317
    }
3318 21
3319
    /**
3320 21
     * Get collection of data validations.
3321 21
     *
3322 21
     * @return DataValidation[]
3323
     */
3324 21
    public function getDataValidationCollection(): array
3325 21
    {
3326 21
        return $this->dataValidationCollection;
3327
    }
3328 21
3329
    /**
3330
     * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet.
3331 21
     *
3332
     * @return string Adjusted range value
3333
     */
3334 21
    public function shrinkRangeToFit(string $range): string
3335
    {
3336
        $maxCol = $this->getHighestColumn();
3337 21
        $maxRow = $this->getHighestRow();
3338 4
        $maxCol = Coordinate::columnIndexFromString($maxCol);
3339
3340 21
        $rangeBlocks = explode(' ', $range);
3341
        foreach ($rangeBlocks as &$rangeSet) {
3342 21
            $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet);
3343
3344 21
            if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) {
3345
                $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol);
3346
            }
3347
            if ($rangeBoundaries[0][1] > $maxRow) {
3348
                $rangeBoundaries[0][1] = $maxRow;
3349
            }
3350 23
            if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) {
3351
                $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol);
3352 23
            }
3353 23
            if ($rangeBoundaries[1][1] > $maxRow) {
3354
                $rangeBoundaries[1][1] = $maxRow;
3355
            }
3356 23
            $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1];
3357
        }
3358
        unset($rangeSet);
3359
3360
        return implode(' ', $rangeBlocks);
3361
    }
3362
3363
    /**
3364 1
     * Get tab color.
3365
     */
3366 1
    public function getTabColor(): Color
3367
    {
3368 1
        if ($this->tabColor === null) {
3369
            $this->tabColor = new Color();
3370
        }
3371
3372
        return $this->tabColor;
3373
    }
3374 463
3375
    /**
3376 463
     * Reset tab color.
3377
     *
3378
     * @return $this
3379
     */
3380
    public function resetTabColor(): static
3381
    {
3382
        $this->tabColor = null;
3383
3384
        return $this;
3385
    }
3386
3387
    /**
3388
     * Tab color set?
3389
     */
3390
    public function isTabColorSet(): bool
3391
    {
3392
        return $this->tabColor !== null;
3393
    }
3394
3395
    /**
3396
     * Copy worksheet (!= clone!).
3397
     */
3398
    public function copy(): static
3399
    {
3400
        return clone $this;
3401
    }
3402
3403
    /**
3404 9
     * Returns a boolean true if the specified row contains no cells. By default, this means that no cell records
3405
     *          exist in the collection for this row. false will be returned otherwise.
3406
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3407 9
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3408 8
     *                  cells, then the row will be considered empty.
3409 8
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3410 1
     *                  string value cells, then the row will be considered empty.
3411 1
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3412
     *                  If the only cells in the collection are null value or empty string value cells, then the row
3413
     *                  will be considered empty.
3414 8
     *
3415
     * @param int $definitionOfEmptyFlags
3416
     *              Possible Flag Values are:
3417
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3418
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3419
     */
3420
    public function isEmptyRow(int $rowId, int $definitionOfEmptyFlags = 0): bool
3421
    {
3422
        try {
3423
            $iterator = new RowIterator($this, $rowId, $rowId);
3424
            $iterator->seek($rowId);
3425
            $row = $iterator->current();
3426
        } catch (Exception) {
3427
            return true;
3428
        }
3429
3430
        return $row->isEmpty($definitionOfEmptyFlags);
3431
    }
3432
3433
    /**
3434 9
     * Returns a boolean true if the specified column contains no cells. By default, this means that no cell records
3435
     *          exist in the collection for this column. false will be returned otherwise.
3436
     *     This rule can be modified by passing a $definitionOfEmptyFlags value:
3437 9
     *          1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
3438 8
     *                  cells, then the column will be considered empty.
3439 8
     *          2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
3440 1
     *                  string value cells, then the column will be considered empty.
3441 1
     *          3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3442
     *                  If the only cells in the collection are null value or empty string value cells, then the column
3443
     *                  will be considered empty.
3444 8
     *
3445
     * @param int $definitionOfEmptyFlags
3446
     *              Possible Flag Values are:
3447
     *                  CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
3448
     *                  CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
3449
     */
3450 14
    public function isEmptyColumn(string $columnId, int $definitionOfEmptyFlags = 0): bool
3451
    {
3452
        try {
3453 14
            $iterator = new ColumnIterator($this, $columnId, $columnId);
3454 14
            $iterator->seek($columnId);
3455 14
            $column = $iterator->current();
3456
        } catch (Exception) {
3457
            return true;
3458 14
        }
3459 14
3460 14
        return $column->isEmpty($definitionOfEmptyFlags);
3461 14
    }
3462 14
3463 14
    /**
3464 14
     * Implement PHP __clone to create a deep clone, not just a shallow copy.
3465 14
     */
3466 4
    public function __clone()
3467 4
    {
3468
        // @phpstan-ignore-next-line
3469 14
        foreach ($this as $key => $val) {
3470 14
            if ($key == 'parent') {
3471 14
                continue;
3472 14
            }
3473 1
3474 1
            if (is_object($val) || (is_array($val))) {
3475 1
                if ($key == 'cellCollection') {
3476
                    $newCollection = $this->cellCollection->cloneCellCollection($this);
3477 14
                    $this->cellCollection = $newCollection;
3478 14
                } elseif ($key == 'drawingCollection') {
3479 14
                    $currentCollection = $this->drawingCollection;
3480 14
                    $this->drawingCollection = new ArrayObject();
3481 5
                    foreach ($currentCollection as $item) {
3482 5
                        $newDrawing = clone $item;
3483
                        $newDrawing->setWorksheet($this);
3484 14
                    }
3485 14
                } elseif ($key == 'tableCollection') {
3486 14
                    $currentCollection = $this->tableCollection;
3487 14
                    $this->tableCollection = new ArrayObject();
3488
                    foreach ($currentCollection as $item) {
3489 14
                        $newTable = clone $item;
3490
                        $newTable->setName($item->getName() . 'clone');
3491
                        $this->addTable($newTable);
3492
                    }
3493 14
                } elseif ($key == 'chartCollection') {
3494
                    $currentCollection = $this->chartCollection;
3495
                    $this->chartCollection = new ArrayObject();
3496
                    foreach ($currentCollection as $item) {
3497
                        $newChart = clone $item;
3498
                        $this->addChart($newChart);
3499
                    }
3500
                } elseif (($key == 'autoFilter') && ($this->autoFilter instanceof AutoFilter)) {
3501
                    $newAutoFilter = clone $this->autoFilter;
3502
                    $this->autoFilter = $newAutoFilter;
3503
                    $this->autoFilter->setParent($this);
3504
                } else {
3505
                    $this->{$key} = unserialize(serialize($val));
3506 10413
                }
3507
            }
3508
        }
3509 10413
        $this->hash = spl_object_id($this);
3510
    }
3511
3512
    /**
3513 10413
     * Define the code name of the sheet.
3514 10413
     *
3515
     * @param string $codeName Same rule as Title minus space not allowed (but, like Excel, change
3516
     *                       silently space to underscore)
3517
     * @param bool $validate False to skip validation of new title. WARNING: This should only be set
3518 10413
     *                       at parse time (by Readers), where titles can be assumed to be valid.
3519
     *
3520
     * @return $this
3521
     */
3522 10413
    public function setCodeName(string $codeName, bool $validate = true): static
3523
    {
3524 10374
        // Is this a 'rename' or not?
3525
        if ($this->getCodeName() == $codeName) {
3526
            return $this;
3527 671
        }
3528
3529
        if ($validate) {
3530 671
            $codeName = str_replace(' ', '_', $codeName); //Excel does this automatically without flinching, we are doing the same
3531 671
3532 275
            // Syntax check
3533 275
            // throw an exception if not valid
3534 2
            self::checkSheetCodeName($codeName);
3535
3536
            // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_'
3537 275
3538
            if ($this->parent !== null) {
3539
                // Is there already such sheet name?
3540
                if ($this->parent->sheetCodeNameExists($codeName)) {
3541
                    // Use name, but append with lowest possible integer
3542
3543
                    if (Shared\StringHelper::countCharacters($codeName) > 29) {
3544 671
                        $codeName = Shared\StringHelper::substring($codeName, 0, 29);
3545
                    }
3546
                    $i = 1;
3547
                    while ($this->getParentOrThrow()->sheetCodeNameExists($codeName . '_' . $i)) {
3548
                        ++$i;
3549 10413
                        if ($i == 10) {
3550
                            if (Shared\StringHelper::countCharacters($codeName) > 28) {
3551 10413
                                $codeName = Shared\StringHelper::substring($codeName, 0, 28);
3552
                            }
3553
                        } elseif ($i == 100) {
3554
                            if (Shared\StringHelper::countCharacters($codeName) > 27) {
3555
                                $codeName = Shared\StringHelper::substring($codeName, 0, 27);
3556
                            }
3557 10413
                        }
3558
                    }
3559 10413
3560
                    $codeName .= '_' . $i; // ok, we have a valid name
3561
                }
3562
            }
3563
        }
3564
3565 2
        $this->codeName = $codeName;
3566
3567 2
        return $this;
3568
    }
3569
3570 4
    /**
3571
     * Return the code name of the sheet.
3572 4
     */
3573
    public function getCodeName(): ?string
3574
    {
3575 116
        return $this->codeName;
3576
    }
3577 116
3578
    /**
3579
     * Sheet has a code name ?
3580
     */
3581
    public function hasCodeName(): bool
3582
    {
3583 1
        return $this->codeName !== null;
3584
    }
3585 1
3586 1
    public static function nameRequiresQuotes(string $sheetName): bool
3587
    {
3588 1
        return preg_match(self::SHEET_NAME_REQUIRES_NO_QUOTES, $sheetName) !== 1;
3589 1
    }
3590
3591 1
    public function isRowVisible(int $row): bool
3592 1
    {
3593 1
        return !$this->rowDimensionExists($row) || $this->getRowDimension($row)->getVisible();
3594 1
    }
3595
3596
    /**
3597
     * Same as Cell->isLocked, but without creating cell if it doesn't exist.
3598
     */
3599
    public function isCellLocked(string $coordinate): bool
3600
    {
3601
        if ($this->getProtection()->getsheet() !== true) {
3602
            return false;
3603 1
        }
3604
        if ($this->cellExists($coordinate)) {
3605 1
            return $this->getCell($coordinate)->isLocked();
3606 1
        }
3607
        $spreadsheet = $this->parent;
3608
        $xfIndex = $this->getXfIndex($coordinate);
3609
        if ($spreadsheet === null || $xfIndex === null) {
3610
            return true;
3611 1
        }
3612
3613
        return $spreadsheet->getCellXfByIndex($xfIndex)->getProtection()->getLocked() !== StyleProtection::PROTECTION_UNPROTECTED;
3614 1
    }
3615
3616 1
    /**
3617 1
     * Same as Cell->isHiddenOnFormulaBar, but without creating cell if it doesn't exist.
3618 1
     */
3619 1
    public function isCellHiddenOnFormulaBar(string $coordinate): bool
3620
    {
3621
        if ($this->cellExists($coordinate)) {
3622 1
            return $this->getCell($coordinate)->isHiddenOnFormulaBar();
3623
        }
3624
3625
        // cell doesn't exist, therefore isn't a formula,
3626 1
        // therefore isn't hidden on formula bar.
3627
        return false;
3628
    }
3629
3630
    private function getXfIndex(string $coordinate): ?int
3631
    {
3632
        [$column, $row] = Coordinate::coordinateFromString($coordinate);
3633
        $row = (int) $row;
3634
        $xfIndex = null;
3635 919
        if ($this->rowDimensionExists($row)) {
3636
            $xfIndex = $this->getRowDimension($row)->getXfIndex();
3637 919
        }
3638
        if ($xfIndex === null && $this->ColumnDimensionExists($column)) {
3639
            $xfIndex = $this->getColumnDimension($column)->getXfIndex();
3640 366
        }
3641
3642 366
        return $xfIndex;
3643
    }
3644
3645 366
    private string $backgroundImage = '';
3646
3647 366
    private string $backgroundMime = '';
3648
3649
    private string $backgroundExtension = '';
3650
3651
    public function getBackgroundImage(): string
3652
    {
3653
        return $this->backgroundImage;
3654
    }
3655
3656
    public function getBackgroundMime(): string
3657 4
    {
3658
        return $this->backgroundMime;
3659 4
    }
3660 4
3661 4
    public function getBackgroundExtension(): string
3662 3
    {
3663 3
        return $this->backgroundExtension;
3664 3
    }
3665 3
3666 3
    /**
3667
     * Set background image.
3668
     * Used on read/write for Xlsx.
3669 4
     * Used on write for Html.
3670
     *
3671
     * @param string $backgroundImage Image represented as a string, e.g. results of file_get_contents
3672
     */
3673
    public function setBackgroundImage(string $backgroundImage): self
3674
    {
3675
        $imageArray = getimagesizefromstring($backgroundImage) ?: ['mime' => ''];
3676
        $mime = $imageArray['mime'];
3677
        if ($mime !== '') {
3678
            $extension = explode('/', $mime);
3679
            $extension = $extension[1];
3680 1
            $this->backgroundImage = $backgroundImage;
3681
            $this->backgroundMime = $mime;
3682 1
            $this->backgroundExtension = $extension;
3683 1
        }
3684 1
3685 1
        return $this;
3686 1
    }
3687 1
3688 1
    /**
3689 1
     * Copy cells, adjusting relative cell references in formulas.
3690 1
     * Acts similarly to Excel "fill handle" feature.
3691 1
     *
3692 1
     * @param string $fromCell Single source cell, e.g. C3
3693
     * @param string $toCells Single cell or cell range, e.g. C4 or C4:C10
3694
     * @param bool $copyStyle Copy styles as well as values, defaults to true
3695
     */
3696
    public function copyCells(string $fromCell, string $toCells, bool $copyStyle = true): void
3697
    {
3698 1065
        $toArray = Coordinate::extractAllCellReferencesInRange($toCells);
3699
        $valueString = $this->getCell($fromCell)->getValueString();
3700 1065
        $style = $this->getStyle($fromCell)->exportArray();
3701 41
        $fromIndexes = Coordinate::indexesFromString($fromCell);
3702 41
        $referenceHelper = ReferenceHelper::getInstance();
3703 41
        foreach ($toArray as $destination) {
3704 41
            if ($destination !== $fromCell) {
3705
                $toIndexes = Coordinate::indexesFromString($destination);
3706
                $this->getCell($destination)->setValue($referenceHelper->updateFormulaReferences($valueString, 'A1', $toIndexes[0] - $fromIndexes[0], $toIndexes[1] - $fromIndexes[1]));
3707
                if ($copyStyle) {
3708
                    $this->getCell($destination)->getStyle()->applyFromArray($style);
3709
                }
3710 2
            }
3711
        }
3712 2
    }
3713 1
3714
    public function calculateArrays(bool $preCalculateFormulas = true): void
3715 1
    {
3716 1
        if ($preCalculateFormulas && Calculation::getInstance($this->parent)->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY) {
3717 1
            $keys = $this->cellCollection->getCoordinates();
3718 1
            foreach ($keys as $key) {
3719 1
                if ($this->getCell($key)->getDataType() === DataType::TYPE_FORMULA) {
3720 1
                    if (preg_match(self::FUNCTION_LIKE_GROUPBY, $this->getCell($key)->getValue()) !== 1) {
3721
                        $this->getCell($key)->getCalculatedValue();
3722 1
                    }
3723
                }
3724
            }
3725
        }
3726
    }
3727 1
3728
    public function isCellInSpillRange(string $coordinate): bool
3729
    {
3730 2
        if (Calculation::getInstance($this->parent)->getInstanceArrayReturnType() !== Calculation::RETURN_ARRAY_AS_ARRAY) {
3731
            return false;
3732 2
        }
3733 2
        $this->calculateArrays();
3734 1
        $keys = $this->cellCollection->getCoordinates();
3735
        foreach ($keys as $key) {
3736 1
            $attributes = $this->getCell($key)->getFormulaAttributes();
3737 1
            if (isset($attributes['ref'])) {
3738 1
                if (Coordinate::coordinateIsInsideRange($attributes['ref'], $coordinate)) {
3739 1
                    // false for first cell in range, true otherwise
3740 1
                    return $coordinate !== $key;
3741 1
                }
3742
            }
3743
        }
3744 1
3745
        return false;
3746
    }
3747
3748
    public function applyStylesFromArray(string $coordinate, array $styleArray): bool
3749
    {
3750
        $spreadsheet = $this->parent;
3751
        if ($spreadsheet === null) {
3752
            return false;
3753
        }
3754
        $activeSheetIndex = $spreadsheet->getActiveSheetIndex();
3755
        $originalSelected = $this->selectedCells;
3756
        $this->getStyle($coordinate)->applyFromArray($styleArray);
3757
        $this->setSelectedCells($originalSelected);
3758
        if ($activeSheetIndex >= 0) {
3759
            $spreadsheet->setActiveSheetIndex($activeSheetIndex);
3760
        }
3761
3762
        return true;
3763
    }
3764
}
3765