Passed
Pull Request — master (#4317)
by Owen
15:23
created

Worksheet::getRowStyle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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