Worksheet::garbageCollect()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 31
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4.0058

Importance

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