Passed
Pull Request — master (#4330)
by Owen
14:12
created

Worksheet::getStyle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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