Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
<?php
2
 
3
namespace PhpOffice\PhpSpreadsheet;
4
 
5
use JsonSerializable;
6
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
7
use PhpOffice\PhpSpreadsheet\Cell\IValueBinder;
8
use PhpOffice\PhpSpreadsheet\Document\Properties;
9
use PhpOffice\PhpSpreadsheet\Document\Security;
10
use PhpOffice\PhpSpreadsheet\Shared\Date;
11
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
12
use PhpOffice\PhpSpreadsheet\Style\Style;
13
use PhpOffice\PhpSpreadsheet\Worksheet\Iterator;
14
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
15
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
16
 
17
class Spreadsheet implements JsonSerializable
18
{
19
    // Allowable values for workbook window visilbity
20
    const VISIBILITY_VISIBLE = 'visible';
21
    const VISIBILITY_HIDDEN = 'hidden';
22
    const VISIBILITY_VERY_HIDDEN = 'veryHidden';
23
 
24
    private const DEFINED_NAME_IS_RANGE = false;
25
    private const DEFINED_NAME_IS_FORMULA = true;
26
 
27
    private const WORKBOOK_VIEW_VISIBILITY_VALUES = [
28
        self::VISIBILITY_VISIBLE,
29
        self::VISIBILITY_HIDDEN,
30
        self::VISIBILITY_VERY_HIDDEN,
31
    ];
32
 
33
    protected int $excelCalendar = Date::CALENDAR_WINDOWS_1900;
34
 
35
    /**
36
     * Unique ID.
37
     */
38
    private string $uniqueID;
39
 
40
    /**
41
     * Document properties.
42
     */
43
    private Properties $properties;
44
 
45
    /**
46
     * Document security.
47
     */
48
    private Security $security;
49
 
50
    /**
51
     * Collection of Worksheet objects.
52
     *
53
     * @var Worksheet[]
54
     */
55
    private array $workSheetCollection;
56
 
57
    /**
58
     * Calculation Engine.
59
     */
60
    private ?Calculation $calculationEngine;
61
 
62
    /**
63
     * Active sheet index.
64
     */
65
    private int $activeSheetIndex;
66
 
67
    /**
68
     * Named ranges.
69
     *
70
     * @var DefinedName[]
71
     */
72
    private array $definedNames;
73
 
74
    /**
75
     * CellXf supervisor.
76
     */
77
    private Style $cellXfSupervisor;
78
 
79
    /**
80
     * CellXf collection.
81
     *
82
     * @var Style[]
83
     */
84
    private array $cellXfCollection = [];
85
 
86
    /**
87
     * CellStyleXf collection.
88
     *
89
     * @var Style[]
90
     */
91
    private array $cellStyleXfCollection = [];
92
 
93
    /**
94
     * hasMacros : this workbook have macros ?
95
     */
96
    private bool $hasMacros = false;
97
 
98
    /**
99
     * macrosCode : all macros code as binary data (the vbaProject.bin file, this include form, code,  etc.), null if no macro.
100
     */
101
    private ?string $macrosCode = null;
102
 
103
    /**
104
     * macrosCertificate : if macros are signed, contains binary data vbaProjectSignature.bin file, null if not signed.
105
     */
106
    private ?string $macrosCertificate = null;
107
 
108
    /**
109
     * ribbonXMLData : null if workbook is'nt Excel 2007 or not contain a customized UI.
110
     *
111
     * @var null|array{target: string, data: string}
112
     */
113
    private ?array $ribbonXMLData = null;
114
 
115
    /**
116
     * ribbonBinObjects : null if workbook is'nt Excel 2007 or not contain embedded objects (picture(s)) for Ribbon Elements
117
     * ignored if $ribbonXMLData is null.
118
     */
119
    private ?array $ribbonBinObjects = null;
120
 
121
    /**
122
     * List of unparsed loaded data for export to same format with better compatibility.
123
     * It has to be minimized when the library start to support currently unparsed data.
124
     */
125
    private array $unparsedLoadedData = [];
126
 
127
    /**
128
     * Controls visibility of the horizonal scroll bar in the application.
129
     */
130
    private bool $showHorizontalScroll = true;
131
 
132
    /**
133
     * Controls visibility of the horizonal scroll bar in the application.
134
     */
135
    private bool $showVerticalScroll = true;
136
 
137
    /**
138
     * Controls visibility of the sheet tabs in the application.
139
     */
140
    private bool $showSheetTabs = true;
141
 
142
    /**
143
     * Specifies a boolean value that indicates whether the workbook window
144
     * is minimized.
145
     */
146
    private bool $minimized = false;
147
 
148
    /**
149
     * Specifies a boolean value that indicates whether to group dates
150
     * when presenting the user with filtering optiomd in the user
151
     * interface.
152
     */
153
    private bool $autoFilterDateGrouping = true;
154
 
155
    /**
156
     * Specifies the index to the first sheet in the book view.
157
     */
158
    private int $firstSheetIndex = 0;
159
 
160
    /**
161
     * Specifies the visible status of the workbook.
162
     */
163
    private string $visibility = self::VISIBILITY_VISIBLE;
164
 
165
    /**
166
     * Specifies the ratio between the workbook tabs bar and the horizontal
167
     * scroll bar.  TabRatio is assumed to be out of 1000 of the horizontal
168
     * window width.
169
     */
170
    private int $tabRatio = 600;
171
 
172
    private Theme $theme;
173
 
174
    private ?IValueBinder $valueBinder = null;
175
 
176
    public function getTheme(): Theme
177
    {
178
        return $this->theme;
179
    }
180
 
181
    /**
182
     * The workbook has macros ?
183
     */
184
    public function hasMacros(): bool
185
    {
186
        return $this->hasMacros;
187
    }
188
 
189
    /**
190
     * Define if a workbook has macros.
191
     *
192
     * @param bool $hasMacros true|false
193
     */
194
    public function setHasMacros(bool $hasMacros): void
195
    {
196
        $this->hasMacros = (bool) $hasMacros;
197
    }
198
 
199
    /**
200
     * Set the macros code.
201
     */
202
    public function setMacrosCode(?string $macroCode): void
203
    {
204
        $this->macrosCode = $macroCode;
205
        $this->setHasMacros($macroCode !== null);
206
    }
207
 
208
    /**
209
     * Return the macros code.
210
     */
211
    public function getMacrosCode(): ?string
212
    {
213
        return $this->macrosCode;
214
    }
215
 
216
    /**
217
     * Set the macros certificate.
218
     */
219
    public function setMacrosCertificate(?string $certificate): void
220
    {
221
        $this->macrosCertificate = $certificate;
222
    }
223
 
224
    /**
225
     * Is the project signed ?
226
     *
227
     * @return bool true|false
228
     */
229
    public function hasMacrosCertificate(): bool
230
    {
231
        return $this->macrosCertificate !== null;
232
    }
233
 
234
    /**
235
     * Return the macros certificate.
236
     */
237
    public function getMacrosCertificate(): ?string
238
    {
239
        return $this->macrosCertificate;
240
    }
241
 
242
    /**
243
     * Remove all macros, certificate from spreadsheet.
244
     */
245
    public function discardMacros(): void
246
    {
247
        $this->hasMacros = false;
248
        $this->macrosCode = null;
249
        $this->macrosCertificate = null;
250
    }
251
 
252
    /**
253
     * set ribbon XML data.
254
     */
255
    public function setRibbonXMLData(mixed $target, mixed $xmlData): void
256
    {
257
        if (is_string($target) && is_string($xmlData)) {
258
            $this->ribbonXMLData = ['target' => $target, 'data' => $xmlData];
259
        } else {
260
            $this->ribbonXMLData = null;
261
        }
262
    }
263
 
264
    /**
265
     * retrieve ribbon XML Data.
266
     */
267
    public function getRibbonXMLData(string $what = 'all'): null|array|string //we need some constants here...
268
    {
269
        $returnData = null;
270
        $what = strtolower($what);
271
        switch ($what) {
272
            case 'all':
273
                $returnData = $this->ribbonXMLData;
274
 
275
                break;
276
            case 'target':
277
            case 'data':
278
                if (is_array($this->ribbonXMLData)) {
279
                    $returnData = $this->ribbonXMLData[$what];
280
                }
281
 
282
                break;
283
        }
284
 
285
        return $returnData;
286
    }
287
 
288
    /**
289
     * store binaries ribbon objects (pictures).
290
     */
291
    public function setRibbonBinObjects(mixed $binObjectsNames, mixed $binObjectsData): void
292
    {
293
        if ($binObjectsNames !== null && $binObjectsData !== null) {
294
            $this->ribbonBinObjects = ['names' => $binObjectsNames, 'data' => $binObjectsData];
295
        } else {
296
            $this->ribbonBinObjects = null;
297
        }
298
    }
299
 
300
    /**
301
     * List of unparsed loaded data for export to same format with better compatibility.
302
     * It has to be minimized when the library start to support currently unparsed data.
303
     *
304
     * @internal
305
     */
306
    public function getUnparsedLoadedData(): array
307
    {
308
        return $this->unparsedLoadedData;
309
    }
310
 
311
    /**
312
     * List of unparsed loaded data for export to same format with better compatibility.
313
     * It has to be minimized when the library start to support currently unparsed data.
314
     *
315
     * @internal
316
     */
317
    public function setUnparsedLoadedData(array $unparsedLoadedData): void
318
    {
319
        $this->unparsedLoadedData = $unparsedLoadedData;
320
    }
321
 
322
    /**
323
     * retrieve Binaries Ribbon Objects.
324
     */
325
    public function getRibbonBinObjects(string $what = 'all'): ?array
326
    {
327
        $ReturnData = null;
328
        $what = strtolower($what);
329
        switch ($what) {
330
            case 'all':
331
                return $this->ribbonBinObjects;
332
            case 'names':
333
            case 'data':
334
                if (is_array($this->ribbonBinObjects) && isset($this->ribbonBinObjects[$what])) {
335
                    $ReturnData = $this->ribbonBinObjects[$what];
336
                }
337
 
338
                break;
339
            case 'types':
340
                if (
341
                    is_array($this->ribbonBinObjects)
342
                    && isset($this->ribbonBinObjects['data']) && is_array($this->ribbonBinObjects['data'])
343
                ) {
344
                    $tmpTypes = array_keys($this->ribbonBinObjects['data']);
345
                    $ReturnData = array_unique(array_map(fn (string $path): string => pathinfo($path, PATHINFO_EXTENSION), $tmpTypes));
346
                } else {
347
                    $ReturnData = []; // the caller want an array... not null if empty
348
                }
349
 
350
                break;
351
        }
352
 
353
        return $ReturnData;
354
    }
355
 
356
    /**
357
     * This workbook have a custom UI ?
358
     */
359
    public function hasRibbon(): bool
360
    {
361
        return $this->ribbonXMLData !== null;
362
    }
363
 
364
    /**
365
     * This workbook have additionnal object for the ribbon ?
366
     */
367
    public function hasRibbonBinObjects(): bool
368
    {
369
        return $this->ribbonBinObjects !== null;
370
    }
371
 
372
    /**
373
     * Check if a sheet with a specified code name already exists.
374
     *
375
     * @param string $codeName Name of the worksheet to check
376
     */
377
    public function sheetCodeNameExists(string $codeName): bool
378
    {
379
        return $this->getSheetByCodeName($codeName) !== null;
380
    }
381
 
382
    /**
383
     * Get sheet by code name. Warning : sheet don't have always a code name !
384
     *
385
     * @param string $codeName Sheet name
386
     */
387
    public function getSheetByCodeName(string $codeName): ?Worksheet
388
    {
389
        $worksheetCount = count($this->workSheetCollection);
390
        for ($i = 0; $i < $worksheetCount; ++$i) {
391
            if ($this->workSheetCollection[$i]->getCodeName() == $codeName) {
392
                return $this->workSheetCollection[$i];
393
            }
394
        }
395
 
396
        return null;
397
    }
398
 
399
    /**
400
     * Create a new PhpSpreadsheet with one Worksheet.
401
     */
402
    public function __construct()
403
    {
404
        $this->uniqueID = uniqid('', true);
405
        $this->calculationEngine = new Calculation($this);
406
        $this->theme = new Theme();
407
 
408
        // Initialise worksheet collection and add one worksheet
409
        $this->workSheetCollection = [];
410
        $this->workSheetCollection[] = new Worksheet($this);
411
        $this->activeSheetIndex = 0;
412
 
413
        // Create document properties
414
        $this->properties = new Properties();
415
 
416
        // Create document security
417
        $this->security = new Security();
418
 
419
        // Set defined names
420
        $this->definedNames = [];
421
 
422
        // Create the cellXf supervisor
423
        $this->cellXfSupervisor = new Style(true);
424
        $this->cellXfSupervisor->bindParent($this);
425
 
426
        // Create the default style
427
        $this->addCellXf(new Style());
428
        $this->addCellStyleXf(new Style());
429
    }
430
 
431
    /**
432
     * Code to execute when this worksheet is unset().
433
     */
434
    public function __destruct()
435
    {
436
        $this->disconnectWorksheets();
437
        $this->calculationEngine = null;
438
        $this->cellXfCollection = [];
439
        $this->cellStyleXfCollection = [];
440
        $this->definedNames = [];
441
    }
442
 
443
    /**
444
     * Disconnect all worksheets from this PhpSpreadsheet workbook object,
445
     * typically so that the PhpSpreadsheet object can be unset.
446
     */
447
    public function disconnectWorksheets(): void
448
    {
449
        foreach ($this->workSheetCollection as $worksheet) {
450
            $worksheet->disconnectCells();
451
            unset($worksheet);
452
        }
453
        $this->workSheetCollection = [];
454
    }
455
 
456
    /**
457
     * Return the calculation engine for this worksheet.
458
     */
459
    public function getCalculationEngine(): ?Calculation
460
    {
461
        return $this->calculationEngine;
462
    }
463
 
464
    /**
465
     * Get properties.
466
     */
467
    public function getProperties(): Properties
468
    {
469
        return $this->properties;
470
    }
471
 
472
    /**
473
     * Set properties.
474
     */
475
    public function setProperties(Properties $documentProperties): void
476
    {
477
        $this->properties = $documentProperties;
478
    }
479
 
480
    /**
481
     * Get security.
482
     */
483
    public function getSecurity(): Security
484
    {
485
        return $this->security;
486
    }
487
 
488
    /**
489
     * Set security.
490
     */
491
    public function setSecurity(Security $documentSecurity): void
492
    {
493
        $this->security = $documentSecurity;
494
    }
495
 
496
    /**
497
     * Get active sheet.
498
     */
499
    public function getActiveSheet(): Worksheet
500
    {
501
        return $this->getSheet($this->activeSheetIndex);
502
    }
503
 
504
    /**
505
     * Create sheet and add it to this workbook.
506
     *
507
     * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
508
     */
509
    public function createSheet(?int $sheetIndex = null): Worksheet
510
    {
511
        $newSheet = new Worksheet($this);
512
        $this->addSheet($newSheet, $sheetIndex, true);
513
 
514
        return $newSheet;
515
    }
516
 
517
    /**
518
     * Check if a sheet with a specified name already exists.
519
     *
520
     * @param string $worksheetName Name of the worksheet to check
521
     */
522
    public function sheetNameExists(string $worksheetName): bool
523
    {
524
        return $this->getSheetByName($worksheetName) !== null;
525
    }
526
 
527
    public function duplicateWorksheetByTitle(string $title): Worksheet
528
    {
529
        $original = $this->getSheetByNameOrThrow($title);
530
        $index = $this->getIndex($original) + 1;
531
        $clone = clone $original;
532
 
533
        return $this->addSheet($clone, $index, true);
534
    }
535
 
536
    /**
537
     * Add sheet.
538
     *
539
     * @param Worksheet $worksheet The worksheet to add
540
     * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
541
     */
542
    public function addSheet(Worksheet $worksheet, ?int $sheetIndex = null, bool $retitleIfNeeded = false): Worksheet
543
    {
544
        if ($retitleIfNeeded) {
545
            $title = $worksheet->getTitle();
546
            if ($this->sheetNameExists($title)) {
547
                $i = 1;
548
                $newTitle = "$title $i";
549
                while ($this->sheetNameExists($newTitle)) {
550
                    ++$i;
551
                    $newTitle = "$title $i";
552
                }
553
                $worksheet->setTitle($newTitle);
554
            }
555
        }
556
        if ($this->sheetNameExists($worksheet->getTitle())) {
557
            throw new Exception(
558
                "Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename this worksheet first."
559
            );
560
        }
561
 
562
        if ($sheetIndex === null) {
563
            if ($this->activeSheetIndex < 0) {
564
                $this->activeSheetIndex = 0;
565
            }
566
            $this->workSheetCollection[] = $worksheet;
567
        } else {
568
            // Insert the sheet at the requested index
569
            array_splice(
570
                $this->workSheetCollection,
571
                $sheetIndex,
572
                0,
573
                [$worksheet]
574
            );
575
 
576
            // Adjust active sheet index if necessary
577
            if ($this->activeSheetIndex >= $sheetIndex) {
578
                ++$this->activeSheetIndex;
579
            }
580
            if ($this->activeSheetIndex < 0) {
581
                $this->activeSheetIndex = 0;
582
            }
583
        }
584
 
585
        if ($worksheet->getParent() === null) {
586
            $worksheet->rebindParent($this);
587
        }
588
 
589
        return $worksheet;
590
    }
591
 
592
    /**
593
     * Remove sheet by index.
594
     *
595
     * @param int $sheetIndex Index position of the worksheet to remove
596
     */
597
    public function removeSheetByIndex(int $sheetIndex): void
598
    {
599
        $numSheets = count($this->workSheetCollection);
600
        if ($sheetIndex > $numSheets - 1) {
601
            throw new Exception(
602
                "You tried to remove a sheet by the out of bounds index: {$sheetIndex}. The actual number of sheets is {$numSheets}."
603
            );
604
        }
605
        array_splice($this->workSheetCollection, $sheetIndex, 1);
606
 
607
        // Adjust active sheet index if necessary
608
        if (
609
            ($this->activeSheetIndex >= $sheetIndex)
610
            && ($this->activeSheetIndex > 0 || $numSheets <= 1)
611
        ) {
612
            --$this->activeSheetIndex;
613
        }
614
    }
615
 
616
    /**
617
     * Get sheet by index.
618
     *
619
     * @param int $sheetIndex Sheet index
620
     */
621
    public function getSheet(int $sheetIndex): Worksheet
622
    {
623
        if (!isset($this->workSheetCollection[$sheetIndex])) {
624
            $numSheets = $this->getSheetCount();
625
 
626
            throw new Exception(
627
                "Your requested sheet index: {$sheetIndex} is out of bounds. The actual number of sheets is {$numSheets}."
628
            );
629
        }
630
 
631
        return $this->workSheetCollection[$sheetIndex];
632
    }
633
 
634
    /**
635
     * Get all sheets.
636
     *
637
     * @return Worksheet[]
638
     */
639
    public function getAllSheets(): array
640
    {
641
        return $this->workSheetCollection;
642
    }
643
 
644
    /**
645
     * Get sheet by name.
646
     *
647
     * @param string $worksheetName Sheet name
648
     */
649
    public function getSheetByName(string $worksheetName): ?Worksheet
650
    {
651
        $worksheetCount = count($this->workSheetCollection);
652
        for ($i = 0; $i < $worksheetCount; ++$i) {
653
            if (strcasecmp($this->workSheetCollection[$i]->getTitle(), trim($worksheetName, "'")) === 0) {
654
                return $this->workSheetCollection[$i];
655
            }
656
        }
657
 
658
        return null;
659
    }
660
 
661
    /**
662
     * Get sheet by name, throwing exception if not found.
663
     */
664
    public function getSheetByNameOrThrow(string $worksheetName): Worksheet
665
    {
666
        $worksheet = $this->getSheetByName($worksheetName);
667
        if ($worksheet === null) {
668
            throw new Exception("Sheet $worksheetName does not exist.");
669
        }
670
 
671
        return $worksheet;
672
    }
673
 
674
    /**
675
     * Get index for sheet.
676
     *
677
     * @return int index
678
     */
679
    public function getIndex(Worksheet $worksheet, bool $noThrow = false): int
680
    {
681
        $wsHash = $worksheet->getHashInt();
682
        foreach ($this->workSheetCollection as $key => $value) {
683
            if ($value->getHashInt() === $wsHash) {
684
                return $key;
685
            }
686
        }
687
        if ($noThrow) {
688
            return -1;
689
        }
690
 
691
        throw new Exception('Sheet does not exist.');
692
    }
693
 
694
    /**
695
     * Set index for sheet by sheet name.
696
     *
697
     * @param string $worksheetName Sheet name to modify index for
698
     * @param int $newIndexPosition New index for the sheet
699
     *
700
     * @return int New sheet index
701
     */
702
    public function setIndexByName(string $worksheetName, int $newIndexPosition): int
703
    {
704
        $oldIndex = $this->getIndex($this->getSheetByNameOrThrow($worksheetName));
705
        $worksheet = array_splice(
706
            $this->workSheetCollection,
707
            $oldIndex,
708
            1
709
        );
710
        array_splice(
711
            $this->workSheetCollection,
712
            $newIndexPosition,
713
            0,
714
            $worksheet
715
        );
716
 
717
        return $newIndexPosition;
718
    }
719
 
720
    /**
721
     * Get sheet count.
722
     */
723
    public function getSheetCount(): int
724
    {
725
        return count($this->workSheetCollection);
726
    }
727
 
728
    /**
729
     * Get active sheet index.
730
     *
731
     * @return int Active sheet index
732
     */
733
    public function getActiveSheetIndex(): int
734
    {
735
        return $this->activeSheetIndex;
736
    }
737
 
738
    /**
739
     * Set active sheet index.
740
     *
741
     * @param int $worksheetIndex Active sheet index
742
     */
743
    public function setActiveSheetIndex(int $worksheetIndex): Worksheet
744
    {
745
        $numSheets = count($this->workSheetCollection);
746
 
747
        if ($worksheetIndex > $numSheets - 1) {
748
            throw new Exception(
749
                "You tried to set a sheet active by the out of bounds index: {$worksheetIndex}. The actual number of sheets is {$numSheets}."
750
            );
751
        }
752
        $this->activeSheetIndex = $worksheetIndex;
753
 
754
        return $this->getActiveSheet();
755
    }
756
 
757
    /**
758
     * Set active sheet index by name.
759
     *
760
     * @param string $worksheetName Sheet title
761
     */
762
    public function setActiveSheetIndexByName(string $worksheetName): Worksheet
763
    {
764
        if (($worksheet = $this->getSheetByName($worksheetName)) instanceof Worksheet) {
765
            $this->setActiveSheetIndex($this->getIndex($worksheet));
766
 
767
            return $worksheet;
768
        }
769
 
770
        throw new Exception('Workbook does not contain sheet:' . $worksheetName);
771
    }
772
 
773
    /**
774
     * Get sheet names.
775
     *
776
     * @return string[]
777
     */
778
    public function getSheetNames(): array
779
    {
780
        $returnValue = [];
781
        $worksheetCount = $this->getSheetCount();
782
        for ($i = 0; $i < $worksheetCount; ++$i) {
783
            $returnValue[] = $this->getSheet($i)->getTitle();
784
        }
785
 
786
        return $returnValue;
787
    }
788
 
789
    /**
790
     * Add external sheet.
791
     *
792
     * @param Worksheet $worksheet External sheet to add
793
     * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
794
     */
795
    public function addExternalSheet(Worksheet $worksheet, ?int $sheetIndex = null): Worksheet
796
    {
797
        if ($this->sheetNameExists($worksheet->getTitle())) {
798
            throw new Exception("Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename the external sheet first.");
799
        }
800
 
801
        // count how many cellXfs there are in this workbook currently, we will need this below
802
        $countCellXfs = count($this->cellXfCollection);
803
 
804
        // copy all the shared cellXfs from the external workbook and append them to the current
805
        foreach ($worksheet->getParentOrThrow()->getCellXfCollection() as $cellXf) {
806
            $this->addCellXf(clone $cellXf);
807
        }
808
 
809
        // move sheet to this workbook
810
        $worksheet->rebindParent($this);
811
 
812
        // update the cellXfs
813
        foreach ($worksheet->getCoordinates(false) as $coordinate) {
814
            $cell = $worksheet->getCell($coordinate);
815
            $cell->setXfIndex($cell->getXfIndex() + $countCellXfs);
816
        }
817
 
818
        // update the column dimensions Xfs
819
        foreach ($worksheet->getColumnDimensions() as $columnDimension) {
820
            $columnDimension->setXfIndex($columnDimension->getXfIndex() + $countCellXfs);
821
        }
822
 
823
        // update the row dimensions Xfs
824
        foreach ($worksheet->getRowDimensions() as $rowDimension) {
825
            $xfIndex = $rowDimension->getXfIndex();
826
            if ($xfIndex !== null) {
827
                $rowDimension->setXfIndex($xfIndex + $countCellXfs);
828
            }
829
        }
830
 
831
        return $this->addSheet($worksheet, $sheetIndex);
832
    }
833
 
834
    /**
835
     * Get an array of all Named Ranges.
836
     *
837
     * @return DefinedName[]
838
     */
839
    public function getNamedRanges(): array
840
    {
841
        return array_filter(
842
            $this->definedNames,
843
            fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_RANGE
844
        );
845
    }
846
 
847
    /**
848
     * Get an array of all Named Formulae.
849
     *
850
     * @return DefinedName[]
851
     */
852
    public function getNamedFormulae(): array
853
    {
854
        return array_filter(
855
            $this->definedNames,
856
            fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_FORMULA
857
        );
858
    }
859
 
860
    /**
861
     * Get an array of all Defined Names (both named ranges and named formulae).
862
     *
863
     * @return DefinedName[]
864
     */
865
    public function getDefinedNames(): array
866
    {
867
        return $this->definedNames;
868
    }
869
 
870
    /**
871
     * Add a named range.
872
     * If a named range with this name already exists, then this will replace the existing value.
873
     */
874
    public function addNamedRange(NamedRange $namedRange): void
875
    {
876
        $this->addDefinedName($namedRange);
877
    }
878
 
879
    /**
880
     * Add a named formula.
881
     * If a named formula with this name already exists, then this will replace the existing value.
882
     */
883
    public function addNamedFormula(NamedFormula $namedFormula): void
884
    {
885
        $this->addDefinedName($namedFormula);
886
    }
887
 
888
    /**
889
     * Add a defined name (either a named range or a named formula).
890
     * If a defined named with this name already exists, then this will replace the existing value.
891
     */
892
    public function addDefinedName(DefinedName $definedName): void
893
    {
894
        $upperCaseName = StringHelper::strToUpper($definedName->getName());
895
        if ($definedName->getScope() == null) {
896
            // global scope
897
            $this->definedNames[$upperCaseName] = $definedName;
898
        } else {
899
            // local scope
900
            $this->definedNames[$definedName->getScope()->getTitle() . '!' . $upperCaseName] = $definedName;
901
        }
902
    }
903
 
904
    /**
905
     * Get named range.
906
     *
907
     * @param null|Worksheet $worksheet Scope. Use null for global scope
908
     */
909
    public function getNamedRange(string $namedRange, ?Worksheet $worksheet = null): ?NamedRange
910
    {
911
        $returnValue = null;
912
 
913
        if ($namedRange !== '') {
914
            $namedRange = StringHelper::strToUpper($namedRange);
915
            // first look for global named range
916
            $returnValue = $this->getGlobalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE);
917
            // then look for local named range (has priority over global named range if both names exist)
918
            $returnValue = $this->getLocalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE, $worksheet) ?: $returnValue;
919
        }
920
 
921
        return $returnValue instanceof NamedRange ? $returnValue : null;
922
    }
923
 
924
    /**
925
     * Get named formula.
926
     *
927
     * @param null|Worksheet $worksheet Scope. Use null for global scope
928
     */
929
    public function getNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): ?NamedFormula
930
    {
931
        $returnValue = null;
932
 
933
        if ($namedFormula !== '') {
934
            $namedFormula = StringHelper::strToUpper($namedFormula);
935
            // first look for global named formula
936
            $returnValue = $this->getGlobalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA);
937
            // then look for local named formula (has priority over global named formula if both names exist)
938
            $returnValue = $this->getLocalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA, $worksheet) ?: $returnValue;
939
        }
940
 
941
        return $returnValue instanceof NamedFormula ? $returnValue : null;
942
    }
943
 
944
    private function getGlobalDefinedNameByType(string $name, bool $type): ?DefinedName
945
    {
946
        if (isset($this->definedNames[$name]) && $this->definedNames[$name]->isFormula() === $type) {
947
            return $this->definedNames[$name];
948
        }
949
 
950
        return null;
951
    }
952
 
953
    private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $worksheet = null): ?DefinedName
954
    {
955
        if (
956
            ($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $name])
957
            && $this->definedNames[$worksheet->getTitle() . '!' . $name]->isFormula() === $type
958
        ) {
959
            return $this->definedNames[$worksheet->getTitle() . '!' . $name];
960
        }
961
 
962
        return null;
963
    }
964
 
965
    /**
966
     * Get named range.
967
     *
968
     * @param null|Worksheet $worksheet Scope. Use null for global scope
969
     */
970
    public function getDefinedName(string $definedName, ?Worksheet $worksheet = null): ?DefinedName
971
    {
972
        $returnValue = null;
973
 
974
        if ($definedName !== '') {
975
            $definedName = StringHelper::strToUpper($definedName);
976
            // first look for global defined name
977
            if (isset($this->definedNames[$definedName])) {
978
                $returnValue = $this->definedNames[$definedName];
979
            }
980
 
981
            // then look for local defined name (has priority over global defined name if both names exist)
982
            if (($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) {
983
                $returnValue = $this->definedNames[$worksheet->getTitle() . '!' . $definedName];
984
            }
985
        }
986
 
987
        return $returnValue;
988
    }
989
 
990
    /**
991
     * Remove named range.
992
     *
993
     * @param null|Worksheet $worksheet scope: use null for global scope
994
     *
995
     * @return $this
996
     */
997
    public function removeNamedRange(string $namedRange, ?Worksheet $worksheet = null): self
998
    {
999
        if ($this->getNamedRange($namedRange, $worksheet) === null) {
1000
            return $this;
1001
        }
1002
 
1003
        return $this->removeDefinedName($namedRange, $worksheet);
1004
    }
1005
 
1006
    /**
1007
     * Remove named formula.
1008
     *
1009
     * @param null|Worksheet $worksheet scope: use null for global scope
1010
     *
1011
     * @return $this
1012
     */
1013
    public function removeNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): self
1014
    {
1015
        if ($this->getNamedFormula($namedFormula, $worksheet) === null) {
1016
            return $this;
1017
        }
1018
 
1019
        return $this->removeDefinedName($namedFormula, $worksheet);
1020
    }
1021
 
1022
    /**
1023
     * Remove defined name.
1024
     *
1025
     * @param null|Worksheet $worksheet scope: use null for global scope
1026
     *
1027
     * @return $this
1028
     */
1029
    public function removeDefinedName(string $definedName, ?Worksheet $worksheet = null): self
1030
    {
1031
        $definedName = StringHelper::strToUpper($definedName);
1032
 
1033
        if ($worksheet === null) {
1034
            if (isset($this->definedNames[$definedName])) {
1035
                unset($this->definedNames[$definedName]);
1036
            }
1037
        } else {
1038
            if (isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) {
1039
                unset($this->definedNames[$worksheet->getTitle() . '!' . $definedName]);
1040
            } elseif (isset($this->definedNames[$definedName])) {
1041
                unset($this->definedNames[$definedName]);
1042
            }
1043
        }
1044
 
1045
        return $this;
1046
    }
1047
 
1048
    /**
1049
     * Get worksheet iterator.
1050
     */
1051
    public function getWorksheetIterator(): Iterator
1052
    {
1053
        return new Iterator($this);
1054
    }
1055
 
1056
    /**
1057
     * Copy workbook (!= clone!).
1058
     */
1059
    public function copy(): self
1060
    {
1061
        return unserialize(serialize($this));
1062
    }
1063
 
1064
    /**
1065
     * Implement PHP __clone to create a deep clone, not just a shallow copy.
1066
     */
1067
    public function __clone()
1068
    {
1069
        $this->uniqueID = uniqid('', true);
1070
 
1071
        $usedKeys = [];
1072
        // I don't now why new Style rather than clone.
1073
        $this->cellXfSupervisor = new Style(true);
1074
        //$this->cellXfSupervisor = clone $this->cellXfSupervisor;
1075
        $this->cellXfSupervisor->bindParent($this);
1076
        $usedKeys['cellXfSupervisor'] = true;
1077
 
1078
        $oldCalc = $this->calculationEngine;
1079
        $this->calculationEngine = new Calculation($this);
1080
        if ($oldCalc !== null) {
1081
            $this->calculationEngine
1082
                ->setInstanceArrayReturnType(
1083
                    $oldCalc->getInstanceArrayReturnType()
1084
                );
1085
        }
1086
        $usedKeys['calculationEngine'] = true;
1087
 
1088
        $currentCollection = $this->cellStyleXfCollection;
1089
        $this->cellStyleXfCollection = [];
1090
        foreach ($currentCollection as $item) {
1091
            $clone = $item->exportArray();
1092
            $style = (new Style())->applyFromArray($clone);
1093
            $this->addCellStyleXf($style);
1094
        }
1095
        $usedKeys['cellStyleXfCollection'] = true;
1096
 
1097
        $currentCollection = $this->cellXfCollection;
1098
        $this->cellXfCollection = [];
1099
        foreach ($currentCollection as $item) {
1100
            $clone = $item->exportArray();
1101
            $style = (new Style())->applyFromArray($clone);
1102
            $this->addCellXf($style);
1103
        }
1104
        $usedKeys['cellXfCollection'] = true;
1105
 
1106
        $currentCollection = $this->workSheetCollection;
1107
        $this->workSheetCollection = [];
1108
        foreach ($currentCollection as $item) {
1109
            $clone = clone $item;
1110
            $clone->setParent($this);
1111
            $this->workSheetCollection[] = $clone;
1112
        }
1113
        $usedKeys['workSheetCollection'] = true;
1114
 
1115
        foreach (get_object_vars($this) as $key => $val) {
1116
            if (isset($usedKeys[$key])) {
1117
                continue;
1118
            }
1119
            switch ($key) {
1120
                // arrays of objects not covered above
1121
                case 'definedNames':
1122
                    $currentCollection = $val;
1123
                    $this->$key = [];
1124
                    foreach ($currentCollection as $item) {
1125
                        $clone = clone $item;
1126
                        $this->{$key}[] = $clone;
1127
                    }
1128
 
1129
                    break;
1130
                default:
1131
                    if (is_object($val)) {
1132
                        $this->$key = clone $val;
1133
                    }
1134
            }
1135
        }
1136
    }
1137
 
1138
    /**
1139
     * Get the workbook collection of cellXfs.
1140
     *
1141
     * @return Style[]
1142
     */
1143
    public function getCellXfCollection(): array
1144
    {
1145
        return $this->cellXfCollection;
1146
    }
1147
 
1148
    /**
1149
     * Get cellXf by index.
1150
     */
1151
    public function getCellXfByIndex(int $cellStyleIndex): Style
1152
    {
1153
        return $this->cellXfCollection[$cellStyleIndex];
1154
    }
1155
 
1156
    public function getCellXfByIndexOrNull(?int $cellStyleIndex): ?Style
1157
    {
1158
        return ($cellStyleIndex === null) ? null : ($this->cellXfCollection[$cellStyleIndex] ?? null);
1159
    }
1160
 
1161
    /**
1162
     * Get cellXf by hash code.
1163
     *
1164
     * @return false|Style
1165
     */
1166
    public function getCellXfByHashCode(string $hashcode): bool|Style
1167
    {
1168
        foreach ($this->cellXfCollection as $cellXf) {
1169
            if ($cellXf->getHashCode() === $hashcode) {
1170
                return $cellXf;
1171
            }
1172
        }
1173
 
1174
        return false;
1175
    }
1176
 
1177
    /**
1178
     * Check if style exists in style collection.
1179
     */
1180
    public function cellXfExists(Style $cellStyleIndex): bool
1181
    {
1182
        return in_array($cellStyleIndex, $this->cellXfCollection, true);
1183
    }
1184
 
1185
    /**
1186
     * Get default style.
1187
     */
1188
    public function getDefaultStyle(): Style
1189
    {
1190
        if (isset($this->cellXfCollection[0])) {
1191
            return $this->cellXfCollection[0];
1192
        }
1193
 
1194
        throw new Exception('No default style found for this workbook');
1195
    }
1196
 
1197
    /**
1198
     * Add a cellXf to the workbook.
1199
     */
1200
    public function addCellXf(Style $style): void
1201
    {
1202
        $this->cellXfCollection[] = $style;
1203
        $style->setIndex(count($this->cellXfCollection) - 1);
1204
    }
1205
 
1206
    /**
1207
     * Remove cellXf by index. It is ensured that all cells get their xf index updated.
1208
     *
1209
     * @param int $cellStyleIndex Index to cellXf
1210
     */
1211
    public function removeCellXfByIndex(int $cellStyleIndex): void
1212
    {
1213
        if ($cellStyleIndex > count($this->cellXfCollection) - 1) {
1214
            throw new Exception('CellXf index is out of bounds.');
1215
        }
1216
 
1217
        // first remove the cellXf
1218
        array_splice($this->cellXfCollection, $cellStyleIndex, 1);
1219
 
1220
        // then update cellXf indexes for cells
1221
        foreach ($this->workSheetCollection as $worksheet) {
1222
            foreach ($worksheet->getCoordinates(false) as $coordinate) {
1223
                $cell = $worksheet->getCell($coordinate);
1224
                $xfIndex = $cell->getXfIndex();
1225
                if ($xfIndex > $cellStyleIndex) {
1226
                    // decrease xf index by 1
1227
                    $cell->setXfIndex($xfIndex - 1);
1228
                } elseif ($xfIndex == $cellStyleIndex) {
1229
                    // set to default xf index 0
1230
                    $cell->setXfIndex(0);
1231
                }
1232
            }
1233
        }
1234
    }
1235
 
1236
    /**
1237
     * Get the cellXf supervisor.
1238
     */
1239
    public function getCellXfSupervisor(): Style
1240
    {
1241
        return $this->cellXfSupervisor;
1242
    }
1243
 
1244
    /**
1245
     * Get the workbook collection of cellStyleXfs.
1246
     *
1247
     * @return Style[]
1248
     */
1249
    public function getCellStyleXfCollection(): array
1250
    {
1251
        return $this->cellStyleXfCollection;
1252
    }
1253
 
1254
    /**
1255
     * Get cellStyleXf by index.
1256
     *
1257
     * @param int $cellStyleIndex Index to cellXf
1258
     */
1259
    public function getCellStyleXfByIndex(int $cellStyleIndex): Style
1260
    {
1261
        return $this->cellStyleXfCollection[$cellStyleIndex];
1262
    }
1263
 
1264
    /**
1265
     * Get cellStyleXf by hash code.
1266
     *
1267
     * @return false|Style
1268
     */
1269
    public function getCellStyleXfByHashCode(string $hashcode): bool|Style
1270
    {
1271
        foreach ($this->cellStyleXfCollection as $cellStyleXf) {
1272
            if ($cellStyleXf->getHashCode() === $hashcode) {
1273
                return $cellStyleXf;
1274
            }
1275
        }
1276
 
1277
        return false;
1278
    }
1279
 
1280
    /**
1281
     * Add a cellStyleXf to the workbook.
1282
     */
1283
    public function addCellStyleXf(Style $style): void
1284
    {
1285
        $this->cellStyleXfCollection[] = $style;
1286
        $style->setIndex(count($this->cellStyleXfCollection) - 1);
1287
    }
1288
 
1289
    /**
1290
     * Remove cellStyleXf by index.
1291
     *
1292
     * @param int $cellStyleIndex Index to cellXf
1293
     */
1294
    public function removeCellStyleXfByIndex(int $cellStyleIndex): void
1295
    {
1296
        if ($cellStyleIndex > count($this->cellStyleXfCollection) - 1) {
1297
            throw new Exception('CellStyleXf index is out of bounds.');
1298
        }
1299
        array_splice($this->cellStyleXfCollection, $cellStyleIndex, 1);
1300
    }
1301
 
1302
    /**
1303
     * Eliminate all unneeded cellXf and afterwards update the xfIndex for all cells
1304
     * and columns in the workbook.
1305
     */
1306
    public function garbageCollect(): void
1307
    {
1308
        // how many references are there to each cellXf ?
1309
        $countReferencesCellXf = [];
1310
        foreach ($this->cellXfCollection as $index => $cellXf) {
1311
            $countReferencesCellXf[$index] = 0;
1312
        }
1313
 
1314
        foreach ($this->getWorksheetIterator() as $sheet) {
1315
            // from cells
1316
            foreach ($sheet->getCoordinates(false) as $coordinate) {
1317
                $cell = $sheet->getCell($coordinate);
1318
                ++$countReferencesCellXf[$cell->getXfIndex()];
1319
            }
1320
 
1321
            // from row dimensions
1322
            foreach ($sheet->getRowDimensions() as $rowDimension) {
1323
                if ($rowDimension->getXfIndex() !== null) {
1324
                    ++$countReferencesCellXf[$rowDimension->getXfIndex()];
1325
                }
1326
            }
1327
 
1328
            // from column dimensions
1329
            foreach ($sheet->getColumnDimensions() as $columnDimension) {
1330
                ++$countReferencesCellXf[$columnDimension->getXfIndex()];
1331
            }
1332
        }
1333
 
1334
        // remove cellXfs without references and create mapping so we can update xfIndex
1335
        // for all cells and columns
1336
        $countNeededCellXfs = 0;
1337
        $map = [];
1338
        foreach ($this->cellXfCollection as $index => $cellXf) {
1339
            if ($countReferencesCellXf[$index] > 0 || $index == 0) { // we must never remove the first cellXf
1340
                ++$countNeededCellXfs;
1341
            } else {
1342
                unset($this->cellXfCollection[$index]);
1343
            }
1344
            $map[$index] = $countNeededCellXfs - 1;
1345
        }
1346
        $this->cellXfCollection = array_values($this->cellXfCollection);
1347
 
1348
        // update the index for all cellXfs
1349
        foreach ($this->cellXfCollection as $i => $cellXf) {
1350
            $cellXf->setIndex($i);
1351
        }
1352
 
1353
        // make sure there is always at least one cellXf (there should be)
1354
        if (empty($this->cellXfCollection)) {
1355
            $this->cellXfCollection[] = new Style();
1356
        }
1357
 
1358
        // update the xfIndex for all cells, row dimensions, column dimensions
1359
        foreach ($this->getWorksheetIterator() as $sheet) {
1360
            // for all cells
1361
            foreach ($sheet->getCoordinates(false) as $coordinate) {
1362
                $cell = $sheet->getCell($coordinate);
1363
                $cell->setXfIndex($map[$cell->getXfIndex()]);
1364
            }
1365
 
1366
            // for all row dimensions
1367
            foreach ($sheet->getRowDimensions() as $rowDimension) {
1368
                if ($rowDimension->getXfIndex() !== null) {
1369
                    $rowDimension->setXfIndex($map[$rowDimension->getXfIndex()]);
1370
                }
1371
            }
1372
 
1373
            // for all column dimensions
1374
            foreach ($sheet->getColumnDimensions() as $columnDimension) {
1375
                $columnDimension->setXfIndex($map[$columnDimension->getXfIndex()]);
1376
            }
1377
 
1378
            // also do garbage collection for all the sheets
1379
            $sheet->garbageCollect();
1380
        }
1381
    }
1382
 
1383
    /**
1384
     * Return the unique ID value assigned to this spreadsheet workbook.
1385
     */
1386
    public function getID(): string
1387
    {
1388
        return $this->uniqueID;
1389
    }
1390
 
1391
    /**
1392
     * Get the visibility of the horizonal scroll bar in the application.
1393
     *
1394
     * @return bool True if horizonal scroll bar is visible
1395
     */
1396
    public function getShowHorizontalScroll(): bool
1397
    {
1398
        return $this->showHorizontalScroll;
1399
    }
1400
 
1401
    /**
1402
     * Set the visibility of the horizonal scroll bar in the application.
1403
     *
1404
     * @param bool $showHorizontalScroll True if horizonal scroll bar is visible
1405
     */
1406
    public function setShowHorizontalScroll(bool $showHorizontalScroll): void
1407
    {
1408
        $this->showHorizontalScroll = (bool) $showHorizontalScroll;
1409
    }
1410
 
1411
    /**
1412
     * Get the visibility of the vertical scroll bar in the application.
1413
     *
1414
     * @return bool True if vertical scroll bar is visible
1415
     */
1416
    public function getShowVerticalScroll(): bool
1417
    {
1418
        return $this->showVerticalScroll;
1419
    }
1420
 
1421
    /**
1422
     * Set the visibility of the vertical scroll bar in the application.
1423
     *
1424
     * @param bool $showVerticalScroll True if vertical scroll bar is visible
1425
     */
1426
    public function setShowVerticalScroll(bool $showVerticalScroll): void
1427
    {
1428
        $this->showVerticalScroll = (bool) $showVerticalScroll;
1429
    }
1430
 
1431
    /**
1432
     * Get the visibility of the sheet tabs in the application.
1433
     *
1434
     * @return bool True if the sheet tabs are visible
1435
     */
1436
    public function getShowSheetTabs(): bool
1437
    {
1438
        return $this->showSheetTabs;
1439
    }
1440
 
1441
    /**
1442
     * Set the visibility of the sheet tabs  in the application.
1443
     *
1444
     * @param bool $showSheetTabs True if sheet tabs are visible
1445
     */
1446
    public function setShowSheetTabs(bool $showSheetTabs): void
1447
    {
1448
        $this->showSheetTabs = (bool) $showSheetTabs;
1449
    }
1450
 
1451
    /**
1452
     * Return whether the workbook window is minimized.
1453
     *
1454
     * @return bool true if workbook window is minimized
1455
     */
1456
    public function getMinimized(): bool
1457
    {
1458
        return $this->minimized;
1459
    }
1460
 
1461
    /**
1462
     * Set whether the workbook window is minimized.
1463
     *
1464
     * @param bool $minimized true if workbook window is minimized
1465
     */
1466
    public function setMinimized(bool $minimized): void
1467
    {
1468
        $this->minimized = (bool) $minimized;
1469
    }
1470
 
1471
    /**
1472
     * Return whether to group dates when presenting the user with
1473
     * filtering optiomd in the user interface.
1474
     *
1475
     * @return bool true if workbook window is minimized
1476
     */
1477
    public function getAutoFilterDateGrouping(): bool
1478
    {
1479
        return $this->autoFilterDateGrouping;
1480
    }
1481
 
1482
    /**
1483
     * Set whether to group dates when presenting the user with
1484
     * filtering optiomd in the user interface.
1485
     *
1486
     * @param bool $autoFilterDateGrouping true if workbook window is minimized
1487
     */
1488
    public function setAutoFilterDateGrouping(bool $autoFilterDateGrouping): void
1489
    {
1490
        $this->autoFilterDateGrouping = (bool) $autoFilterDateGrouping;
1491
    }
1492
 
1493
    /**
1494
     * Return the first sheet in the book view.
1495
     *
1496
     * @return int First sheet in book view
1497
     */
1498
    public function getFirstSheetIndex(): int
1499
    {
1500
        return $this->firstSheetIndex;
1501
    }
1502
 
1503
    /**
1504
     * Set the first sheet in the book view.
1505
     *
1506
     * @param int $firstSheetIndex First sheet in book view
1507
     */
1508
    public function setFirstSheetIndex(int $firstSheetIndex): void
1509
    {
1510
        if ($firstSheetIndex >= 0) {
1511
            $this->firstSheetIndex = (int) $firstSheetIndex;
1512
        } else {
1513
            throw new Exception('First sheet index must be a positive integer.');
1514
        }
1515
    }
1516
 
1517
    /**
1518
     * Return the visibility status of the workbook.
1519
     *
1520
     * This may be one of the following three values:
1521
     * - visibile
1522
     *
1523
     * @return string Visible status
1524
     */
1525
    public function getVisibility(): string
1526
    {
1527
        return $this->visibility;
1528
    }
1529
 
1530
    /**
1531
     * Set the visibility status of the workbook.
1532
     *
1533
     * Valid values are:
1534
     *  - 'visible' (self::VISIBILITY_VISIBLE):
1535
     *       Workbook window is visible
1536
     *  - 'hidden' (self::VISIBILITY_HIDDEN):
1537
     *       Workbook window is hidden, but can be shown by the user
1538
     *       via the user interface
1539
     *  - 'veryHidden' (self::VISIBILITY_VERY_HIDDEN):
1540
     *       Workbook window is hidden and cannot be shown in the
1541
     *       user interface.
1542
     *
1543
     * @param null|string $visibility visibility status of the workbook
1544
     */
1545
    public function setVisibility(?string $visibility): void
1546
    {
1547
        if ($visibility === null) {
1548
            $visibility = self::VISIBILITY_VISIBLE;
1549
        }
1550
 
1551
        if (in_array($visibility, self::WORKBOOK_VIEW_VISIBILITY_VALUES)) {
1552
            $this->visibility = $visibility;
1553
        } else {
1554
            throw new Exception('Invalid visibility value.');
1555
        }
1556
    }
1557
 
1558
    /**
1559
     * Get the ratio between the workbook tabs bar and the horizontal scroll bar.
1560
     * TabRatio is assumed to be out of 1000 of the horizontal window width.
1561
     *
1562
     * @return int Ratio between the workbook tabs bar and the horizontal scroll bar
1563
     */
1564
    public function getTabRatio(): int
1565
    {
1566
        return $this->tabRatio;
1567
    }
1568
 
1569
    /**
1570
     * Set the ratio between the workbook tabs bar and the horizontal scroll bar
1571
     * TabRatio is assumed to be out of 1000 of the horizontal window width.
1572
     *
1573
     * @param int $tabRatio Ratio between the tabs bar and the horizontal scroll bar
1574
     */
1575
    public function setTabRatio(int $tabRatio): void
1576
    {
1577
        if ($tabRatio >= 0 && $tabRatio <= 1000) {
1578
            $this->tabRatio = (int) $tabRatio;
1579
        } else {
1580
            throw new Exception('Tab ratio must be between 0 and 1000.');
1581
        }
1582
    }
1583
 
1584
    public function reevaluateAutoFilters(bool $resetToMax): void
1585
    {
1586
        foreach ($this->workSheetCollection as $sheet) {
1587
            $filter = $sheet->getAutoFilter();
1588
            if (!empty($filter->getRange())) {
1589
                if ($resetToMax) {
1590
                    $filter->setRangeToMaxRow();
1591
                }
1592
                $filter->showHideRows();
1593
            }
1594
        }
1595
    }
1596
 
1597
    /**
1598
     * @throws Exception
1599
     */
1600
    public function jsonSerialize(): mixed
1601
    {
1602
        throw new Exception('Spreadsheet objects cannot be json encoded');
1603
    }
1604
 
1605
    public function resetThemeFonts(): void
1606
    {
1607
        $majorFontLatin = $this->theme->getMajorFontLatin();
1608
        $minorFontLatin = $this->theme->getMinorFontLatin();
1609
        foreach ($this->cellXfCollection as $cellStyleXf) {
1610
            $scheme = $cellStyleXf->getFont()->getScheme();
1611
            if ($scheme === 'major') {
1612
                $cellStyleXf->getFont()->setName($majorFontLatin)->setScheme($scheme);
1613
            } elseif ($scheme === 'minor') {
1614
                $cellStyleXf->getFont()->setName($minorFontLatin)->setScheme($scheme);
1615
            }
1616
        }
1617
        foreach ($this->cellStyleXfCollection as $cellStyleXf) {
1618
            $scheme = $cellStyleXf->getFont()->getScheme();
1619
            if ($scheme === 'major') {
1620
                $cellStyleXf->getFont()->setName($majorFontLatin)->setScheme($scheme);
1621
            } elseif ($scheme === 'minor') {
1622
                $cellStyleXf->getFont()->setName($minorFontLatin)->setScheme($scheme);
1623
            }
1624
        }
1625
    }
1626
 
1627
    public function getTableByName(string $tableName): ?Table
1628
    {
1629
        $table = null;
1630
        foreach ($this->workSheetCollection as $sheet) {
1631
            $table = $sheet->getTableByName($tableName);
1632
            if ($table !== null) {
1633
                break;
1634
            }
1635
        }
1636
 
1637
        return $table;
1638
    }
1639
 
1640
    /**
1641
     * @return bool Success or failure
1642
     */
1643
    public function setExcelCalendar(int $baseYear): bool
1644
    {
1645
        if (($baseYear === Date::CALENDAR_WINDOWS_1900) || ($baseYear === Date::CALENDAR_MAC_1904)) {
1646
            $this->excelCalendar = $baseYear;
1647
 
1648
            return true;
1649
        }
1650
 
1651
        return false;
1652
    }
1653
 
1654
    /**
1655
     * @return int Excel base date (1900 or 1904)
1656
     */
1657
    public function getExcelCalendar(): int
1658
    {
1659
        return $this->excelCalendar;
1660
    }
1661
 
1662
    public function deleteLegacyDrawing(Worksheet $worksheet): void
1663
    {
1664
        unset($this->unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing']);
1665
    }
1666
 
1667
    public function getLegacyDrawing(Worksheet $worksheet): ?string
1668
    {
1669
        return $this->unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing'] ?? null;
1670
    }
1671
 
1672
    public function getValueBinder(): ?IValueBinder
1673
    {
1674
        return $this->valueBinder;
1675
    }
1676
 
1677
    public function setValueBinder(?IValueBinder $valueBinder): self
1678
    {
1679
        $this->valueBinder = $valueBinder;
1680
 
1681
        return $this;
1682
    }
1683
 
1684
    /**
1685
     * All the PDF writers treat charts as if they occupy a single cell.
1686
     * This will be better most of the time.
1687
     * It is not needed for any other output type.
1688
     * It changes the contents of the spreadsheet, so you might
1689
     * be better off cloning the spreadsheet and then using
1690
     * this method on, and then writing, the clone.
1691
     */
1692
    public function mergeChartCellsForPdf(): void
1693
    {
1694
        foreach ($this->workSheetCollection as $worksheet) {
1695
            foreach ($worksheet->getChartCollection() as $chart) {
1696
                $br = $chart->getBottomRightCell();
1697
                $tl = $chart->getTopLeftCell();
1698
                if ($br !== '' && $br !== $tl) {
1699
                    if (!$worksheet->cellExists($br)) {
1700
                        $worksheet->getCell($br)->setValue(' ');
1701
                    }
1702
                    $worksheet->mergeCells("$tl:$br");
1703
                }
1704
            }
1705
        }
1706
    }
1707
 
1708
    /**
1709
     * All the PDF writers do better with drawings than charts.
1710
     * This will be better some of the time.
1711
     * It is not needed for any other output type.
1712
     * It changes the contents of the spreadsheet, so you might
1713
     * be better off cloning the spreadsheet and then using
1714
     * this method on, and then writing, the clone.
1715
     */
1716
    public function mergeDrawingCellsForPdf(): void
1717
    {
1718
        foreach ($this->workSheetCollection as $worksheet) {
1719
            foreach ($worksheet->getDrawingCollection() as $drawing) {
1720
                $br = $drawing->getCoordinates2();
1721
                $tl = $drawing->getCoordinates();
1722
                if ($br !== '' && $br !== $tl) {
1723
                    if (!$worksheet->cellExists($br)) {
1724
                        $worksheet->getCell($br)->setValue(' ');
1725
                    }
1726
                    $worksheet->mergeCells("$tl:$br");
1727
                }
1728
            }
1729
        }
1730
    }
1731
}