Passed
Pull Request — master (#4465)
by Owen
14:25
created

Worksheet::removeColumn()   C

Complexity

Conditions 13
Paths 97

Size

Total Lines 69
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 13

Importance

Changes 0
Metric Value
eloc 45
c 0
b 0
f 0
dl 0
loc 69
ccs 16
cts 16
cp 1
rs 6.6166
cc 13
nc 97
nop 2
crap 13

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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