• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PHPOffice / PhpSpreadsheet / 26717149869

31 May 2026 03:48PM UTC coverage: 97.066% (+0.001%) from 97.065%
26717149869

Pull #4886

github

web-flow
Merge 668106c68 into e322f5407
Pull Request #4886: Add IReader2 Interface with listWorksheetInfo/Names

4 of 4 new or added lines in 1 file covered. (100.0%)

4 existing lines in 3 files now uncovered.

48073 of 49526 relevant lines covered (97.07%)

386.49 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.93
/src/PhpSpreadsheet/Spreadsheet.php
1
<?php
2

3
namespace PhpOffice\PhpSpreadsheet;
4

5
use Composer\Pcre\Preg;
6
use JsonSerializable;
7
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
8
use PhpOffice\PhpSpreadsheet\Cell\IValueBinder;
9
use PhpOffice\PhpSpreadsheet\Document\Properties;
10
use PhpOffice\PhpSpreadsheet\Document\Security;
11
use PhpOffice\PhpSpreadsheet\Shared\Date;
12
use PhpOffice\PhpSpreadsheet\Shared\Font as SharedFont;
13
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
14
use PhpOffice\PhpSpreadsheet\Style\Style;
15
use PhpOffice\PhpSpreadsheet\Worksheet\Iterator;
16
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
17
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
18

19
class Spreadsheet implements JsonSerializable
20
{
21
    // Allowable values for workbook window visibility
22
    const VISIBILITY_VISIBLE = 'visible';
23
    const VISIBILITY_HIDDEN = 'hidden';
24
    const VISIBILITY_VERY_HIDDEN = 'veryHidden';
25

26
    private const DEFINED_NAME_IS_RANGE = false;
27
    private const DEFINED_NAME_IS_FORMULA = true;
28

29
    private const WORKBOOK_VIEW_VISIBILITY_VALUES = [
30
        self::VISIBILITY_VISIBLE,
31
        self::VISIBILITY_HIDDEN,
32
        self::VISIBILITY_VERY_HIDDEN,
33
    ];
34

35
    protected int $excelCalendar = Date::CALENDAR_WINDOWS_1900;
36

37
    /**
38
     * Unique ID.
39
     */
40
    private string $uniqueID;
41

42
    /**
43
     * Document properties.
44
     */
45
    private Properties $properties;
46

47
    /**
48
     * Document security.
49
     */
50
    private Security $security;
51

52
    /**
53
     * Collection of Worksheet objects.
54
     *
55
     * @var Worksheet[]
56
     */
57
    private array $workSheetCollection;
58

59
    /**
60
     * Calculation Engine.
61
     */
62
    private Calculation $calculationEngine;
63

64
    /**
65
     * Active sheet index.
66
     */
67
    private int $activeSheetIndex;
68

69
    /**
70
     * Named ranges.
71
     *
72
     * @var DefinedName[]
73
     */
74
    private array $definedNames;
75

76
    /**
77
     * CellXf supervisor.
78
     */
79
    private Style $cellXfSupervisor;
80

81
    /**
82
     * CellXf collection.
83
     *
84
     * @var Style[]
85
     */
86
    private array $cellXfCollection = [];
87

88
    /**
89
     * CellStyleXf collection.
90
     *
91
     * @var Style[]
92
     */
93
    private array $cellStyleXfCollection = [];
94

95
    /**
96
     * hasMacros : this workbook have macros ?
97
     */
98
    private bool $hasMacros = false;
99

100
    /**
101
     * macrosCode : all macros code as binary data (the vbaProject.bin file, this include form, code,  etc.), null if no macro.
102
     */
103
    private ?string $macrosCode = null;
104

105
    /**
106
     * macrosCertificate : if macros are signed, contains binary data vbaProjectSignature.bin file, null if not signed.
107
     */
108
    private ?string $macrosCertificate = null;
109

110
    /**
111
     * ribbonXMLData : null if workbook isn't Excel 2007 or not contain a customized UI.
112
     *
113
     * @var null|array{target: string, data: string}
114
     */
115
    private ?array $ribbonXMLData = null;
116

117
    /**
118
     * ribbonBinObjects : null if workbook isn't Excel 2007 or not contain embedded objects (picture(s)) for Ribbon Elements
119
     * ignored if $ribbonXMLData is null.
120
     *
121
     * @var null|mixed[]
122
     */
123
    private ?array $ribbonBinObjects = null;
124

125
    /**
126
     * List of unparsed loaded data for export to same format with better compatibility.
127
     * It has to be minimized when the library start to support currently unparsed data.
128
     *
129
     * @var array<array<array<array<string>|string>>>
130
     */
131
    private array $unparsedLoadedData = [];
132

133
    /**
134
     * Controls visibility of the horizonal scroll bar in the application.
135
     */
136
    private bool $showHorizontalScroll = true;
137

138
    /**
139
     * Controls visibility of the horizonal scroll bar in the application.
140
     */
141
    private bool $showVerticalScroll = true;
142

143
    /**
144
     * Controls visibility of the sheet tabs in the application.
145
     */
146
    private bool $showSheetTabs = true;
147

148
    /**
149
     * Specifies a boolean value that indicates whether the workbook window
150
     * is minimized.
151
     */
152
    private bool $minimized = false;
153

154
    /**
155
     * Specifies a boolean value that indicates whether to group dates
156
     * when presenting the user with filtering options in the user
157
     * interface.
158
     */
159
    private bool $autoFilterDateGrouping = true;
160

161
    /**
162
     * Specifies the index to the first sheet in the book view.
163
     */
164
    private int $firstSheetIndex = 0;
165

166
    /**
167
     * Specifies the visible status of the workbook.
168
     */
169
    private string $visibility = self::VISIBILITY_VISIBLE;
170

171
    /**
172
     * Specifies the ratio between the workbook tabs bar and the horizontal
173
     * scroll bar.  TabRatio is assumed to be out of 1000 of the horizontal
174
     * window width.
175
     */
176
    private int $tabRatio = 600;
177

178
    private Theme $theme;
179

180
    private ?IValueBinder $valueBinder = null;
181

182
    /** @var array<string, int> */
183
    private array $fontCharsets = [
184
        'B Nazanin' => SharedFont::CHARSET_ANSI_ARABIC,
185
    ];
186

187
    /**
188
     * @param int $charset uses any value from Shared\Font,
189
     *    but defaults to ARABIC because that is the only known
190
     *    charset for which this declaration might be needed
191
     */
192
    public function addFontCharset(string $fontName, int $charset = SharedFont::CHARSET_ANSI_ARABIC): void
34✔
193
    {
194
        $this->fontCharsets[$fontName] = $charset;
34✔
195
    }
196

197
    public function getFontCharset(string $fontName): int
444✔
198
    {
199
        return $this->fontCharsets[$fontName] ?? -1;
444✔
200
    }
201

202
    /**
203
     * Return all fontCharsets.
204
     *
205
     * @return array<string, int>
206
     */
207
    public function getFontCharsets(): array
1✔
208
    {
209
        return $this->fontCharsets;
1✔
210
    }
211

212
    public function getTheme(): Theme
878✔
213
    {
214
        return $this->theme;
878✔
215
    }
216

217
    /**
218
     * The workbook has macros ?
219
     */
220
    public function hasMacros(): bool
513✔
221
    {
222
        return $this->hasMacros;
513✔
223
    }
224

225
    /**
226
     * Define if a workbook has macros.
227
     *
228
     * @param bool $hasMacros true|false
229
     */
230
    public function setHasMacros(bool $hasMacros): void
3✔
231
    {
232
        $this->hasMacros = (bool) $hasMacros;
3✔
233
    }
234

235
    /**
236
     * Set the macros code.
237
     */
238
    public function setMacrosCode(?string $macroCode): void
3✔
239
    {
240
        $this->macrosCode = $macroCode;
3✔
241
        $this->setHasMacros($macroCode !== null);
3✔
242
    }
243

244
    /**
245
     * Return the macros code.
246
     */
247
    public function getMacrosCode(): ?string
3✔
248
    {
249
        return $this->macrosCode;
3✔
250
    }
251

252
    /**
253
     * Set the macros certificate.
254
     */
255
    public function setMacrosCertificate(?string $certificate): void
3✔
256
    {
257
        $this->macrosCertificate = $certificate;
3✔
258
    }
259

260
    /**
261
     * Is the project signed ?
262
     *
263
     * @return bool true|false
264
     */
265
    public function hasMacrosCertificate(): bool
2✔
266
    {
267
        return $this->macrosCertificate !== null;
2✔
268
    }
269

270
    /**
271
     * Return the macros certificate.
272
     */
273
    public function getMacrosCertificate(): ?string
2✔
274
    {
275
        return $this->macrosCertificate;
2✔
276
    }
277

278
    /**
279
     * Remove all macros, certificate from spreadsheet.
280
     */
281
    public function discardMacros(): void
1✔
282
    {
283
        $this->hasMacros = false;
1✔
284
        $this->macrosCode = null;
1✔
285
        $this->macrosCertificate = null;
1✔
286
    }
287

288
    /**
289
     * set ribbon XML data.
290
     */
291
    public function setRibbonXMLData(mixed $target, mixed $xmlData): void
2✔
292
    {
293
        if (is_string($target) && is_string($xmlData)) {
2✔
294
            $this->ribbonXMLData = ['target' => $target, 'data' => $xmlData];
2✔
295
        } else {
296
            $this->ribbonXMLData = null;
×
297
        }
298
    }
299

300
    /**
301
     * retrieve ribbon XML Data.
302
     *
303
     * @return mixed[]
304
     */
305
    public function getRibbonXMLData(string $what = 'all'): null|array|string //we need some constants here...
442✔
306
    {
307
        $returnData = null;
442✔
308
        $what = strtolower($what);
442✔
309
        switch ($what) {
310
            case 'all':
442✔
311
                $returnData = $this->ribbonXMLData;
2✔
312

313
                break;
2✔
314
            case 'target':
442✔
315
            case 'data':
2✔
316
                if (is_array($this->ribbonXMLData)) {
442✔
317
                    $returnData = $this->ribbonXMLData[$what];
2✔
318
                }
319

320
                break;
442✔
321
        }
322

323
        return $returnData;
442✔
324
    }
325

326
    /**
327
     * store binaries ribbon objects (pictures).
328
     */
329
    public function setRibbonBinObjects(mixed $binObjectsNames, mixed $binObjectsData): void
2✔
330
    {
331
        if ($binObjectsNames !== null && $binObjectsData !== null) {
2✔
332
            $this->ribbonBinObjects = ['names' => $binObjectsNames, 'data' => $binObjectsData];
×
333
        } else {
334
            $this->ribbonBinObjects = null;
2✔
335
        }
336
    }
337

338
    /**
339
     * List of unparsed loaded data for export to same format with better compatibility.
340
     * It has to be minimized when the library start to support currently unparsed data.
341
     *
342
     * @internal
343
     *
344
     * @return mixed[]
345
     */
346
    public function getUnparsedLoadedData(): array
515✔
347
    {
348
        return $this->unparsedLoadedData;
515✔
349
    }
350

351
    /**
352
     * List of unparsed loaded data for export to same format with better compatibility.
353
     * It has to be minimized when the library start to support currently unparsed data.
354
     *
355
     * @internal
356
     *
357
     * @param array<array<array<array<string>|string>>> $unparsedLoadedData
358
     */
359
    public function setUnparsedLoadedData(array $unparsedLoadedData): void
754✔
360
    {
361
        $this->unparsedLoadedData = $unparsedLoadedData;
754✔
362
    }
363

364
    /**
365
     * retrieve Binaries Ribbon Objects.
366
     *
367
     * @return mixed[]
368
     */
369
    public function getRibbonBinObjects(string $what = 'all'): ?array
2✔
370
    {
371
        $ReturnData = null;
2✔
372
        $what = strtolower($what);
2✔
373
        switch ($what) {
374
            case 'all':
2✔
375
                return $this->ribbonBinObjects;
2✔
376
            case 'names':
1✔
377
            case 'data':
1✔
378
                if (is_array($this->ribbonBinObjects) && is_array($this->ribbonBinObjects[$what] ?? null)) {
1✔
379
                    $ReturnData = $this->ribbonBinObjects[$what];
×
380
                }
381

382
                break;
1✔
383
            case 'types':
1✔
384
                if (
385
                    is_array($this->ribbonBinObjects)
1✔
386
                    && isset($this->ribbonBinObjects['data']) && is_array($this->ribbonBinObjects['data'])
1✔
387
                ) {
388
                    $tmpTypes = array_keys($this->ribbonBinObjects['data']);
×
389
                    $ReturnData = array_unique(array_map(fn (string $path): string => pathinfo($path, PATHINFO_EXTENSION), $tmpTypes));
×
390
                } else {
391
                    $ReturnData = []; // the caller want an array... not null if empty
1✔
392
                }
393

394
                break;
1✔
395
        }
396

397
        return $ReturnData;
1✔
398
    }
399

400
    /**
401
     * This workbook have a custom UI ?
402
     */
403
    public function hasRibbon(): bool
442✔
404
    {
405
        return $this->ribbonXMLData !== null;
442✔
406
    }
407

408
    /**
409
     * This workbook have additional object for the ribbon ?
410
     */
411
    public function hasRibbonBinObjects(): bool
442✔
412
    {
413
        return $this->ribbonBinObjects !== null;
442✔
414
    }
415

416
    /**
417
     * This workbook has in cell images.
418
     */
419
    public function hasInCellDrawings(): bool
442✔
420
    {
421
        $sheetCount = $this->getSheetCount();
442✔
422
        for ($i = 0; $i < $sheetCount; ++$i) {
442✔
423
            if ($this->getSheet($i)->getInCellDrawingCollection()->count() > 0) {
442✔
424
                return true;
8✔
425
            }
426
        }
427

428
        return false;
434✔
429
    }
430

431
    /**
432
     * Check if a sheet with a specified code name already exists.
433
     *
434
     * @param string $codeName Name of the worksheet to check
435
     */
436
    public function sheetCodeNameExists(string $codeName): bool
11,411✔
437
    {
438
        return $this->getSheetByCodeName($codeName) !== null;
11,411✔
439
    }
440

441
    /**
442
     * Get sheet by code name. Warning : sheet don't have always a code name !
443
     *
444
     * @param string $codeName Sheet name
445
     */
446
    public function getSheetByCodeName(string $codeName): ?Worksheet
11,411✔
447
    {
448
        $worksheetCount = count($this->workSheetCollection);
11,411✔
449
        for ($i = 0; $i < $worksheetCount; ++$i) {
11,411✔
450
            if ($this->workSheetCollection[$i]->getCodeName() == $codeName) {
771✔
451
                return $this->workSheetCollection[$i];
737✔
452
            }
453
        }
454

455
        return null;
11,411✔
456
    }
457

458
    /**
459
     * Create a new PhpSpreadsheet with one Worksheet.
460
     */
461
    public function __construct()
11,411✔
462
    {
463
        $this->uniqueID = uniqid('', true);
11,411✔
464
        $this->calculationEngine = new Calculation($this);
11,411✔
465
        $this->theme = new Theme();
11,411✔
466

467
        // Initialise worksheet collection and add one worksheet
468
        $this->workSheetCollection = [];
11,411✔
469
        $this->workSheetCollection[] = new Worksheet($this);
11,411✔
470
        $this->activeSheetIndex = 0;
11,411✔
471

472
        // Create document properties
473
        $this->properties = new Properties();
11,411✔
474

475
        // Create document security
476
        $this->security = new Security();
11,411✔
477

478
        // Set defined names
479
        $this->definedNames = [];
11,411✔
480

481
        // Create the cellXf supervisor
482
        $this->cellXfSupervisor = new Style(true);
11,411✔
483
        $this->cellXfSupervisor->bindParent($this);
11,411✔
484

485
        // Create the default style
486
        $this->addCellXf(new Style());
11,411✔
487
        $this->addCellStyleXf(new Style());
11,411✔
488
    }
489

490
    /**
491
     * Code to execute when this worksheet is unset().
492
     */
493
    public function __destruct()
124✔
494
    {
495
        $this->disconnectWorksheets();
124✔
496
        unset($this->calculationEngine);
124✔
497
        $this->cellXfCollection = [];
124✔
498
        $this->cellStyleXfCollection = [];
124✔
499
        $this->definedNames = [];
124✔
500
    }
501

502
    /**
503
     * Disconnect all worksheets from this PhpSpreadsheet workbook object,
504
     * typically so that the PhpSpreadsheet object can be unset.
505
     */
506
    public function disconnectWorksheets(): void
10,461✔
507
    {
508
        foreach ($this->workSheetCollection as $worksheet) {
10,461✔
509
            $worksheet->disconnectCells();
10,460✔
510
            unset($worksheet);
10,460✔
511
        }
512
        $this->workSheetCollection = [];
10,461✔
513
        $this->activeSheetIndex = -1;
10,461✔
514
    }
515

516
    /**
517
     * Return the calculation engine for this worksheet.
518
     */
519
    public function getCalculationEngine(): Calculation
10,285✔
520
    {
521
        return $this->calculationEngine;
10,285✔
522
    }
523

524
    /**
525
     * Intended for use only via a destructor.
526
     *
527
     * @internal
528
     */
529
    public function getCalculationEngineOrNull(): ?Calculation
86✔
530
    {
531
        if (!isset($this->calculationEngine)) { //* @phpstan-ignore-line
86✔
532
            return null;
57✔
533
        }
534

535
        return $this->calculationEngine;
84✔
536
    }
537

538
    /**
539
     * Get properties.
540
     */
541
    public function getProperties(): Properties
1,828✔
542
    {
543
        return $this->properties;
1,828✔
544
    }
545

546
    /**
547
     * Set properties.
548
     */
549
    public function setProperties(Properties $documentProperties): void
1✔
550
    {
551
        $this->properties = $documentProperties;
1✔
552
    }
553

554
    /**
555
     * Get security.
556
     */
557
    public function getSecurity(): Security
460✔
558
    {
559
        return $this->security;
460✔
560
    }
561

562
    /**
563
     * Set security.
564
     */
565
    public function setSecurity(Security $documentSecurity): void
1✔
566
    {
567
        $this->security = $documentSecurity;
1✔
568
    }
569

570
    /**
571
     * Get active sheet.
572
     */
573
    public function getActiveSheet(): Worksheet
11,301✔
574
    {
575
        return $this->getSheet($this->activeSheetIndex);
11,301✔
576
    }
577

578
    /**
579
     * Create sheet and add it to this workbook.
580
     *
581
     * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
582
     */
583
    public function createSheet(?int $sheetIndex = null): Worksheet
1,402✔
584
    {
585
        $newSheet = new Worksheet($this);
1,402✔
586
        $this->addSheet($newSheet, $sheetIndex, true);
1,402✔
587

588
        return $newSheet;
1,402✔
589
    }
590

591
    /**
592
     * Check if a sheet with a specified name already exists.
593
     *
594
     * @param string $worksheetName Name of the worksheet to check
595
     */
596
    public function sheetNameExists(string $worksheetName): bool
1,998✔
597
    {
598
        return $this->getSheetByName($worksheetName) !== null;
1,998✔
599
    }
600

601
    public function duplicateWorksheetByTitle(string $title): Worksheet
1✔
602
    {
603
        $original = $this->getSheetByNameOrThrow($title);
1✔
604
        $index = $this->getIndex($original) + 1;
1✔
605
        $clone = clone $original;
1✔
606

607
        return $this->addSheet($clone, $index, true);
1✔
608
    }
609

610
    /**
611
     * Add sheet.
612
     *
613
     * @param Worksheet $worksheet The worksheet to add
614
     * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
615
     */
616
    public function addSheet(Worksheet $worksheet, ?int $sheetIndex = null, bool $retitleIfNeeded = false): Worksheet
1,493✔
617
    {
618
        if ($retitleIfNeeded) {
1,493✔
619
            $title = $worksheet->getTitle();
1,402✔
620
            if ($this->sheetNameExists($title)) {
1,402✔
621
                $i = 1;
189✔
622
                $newTitle = "$title $i";
189✔
623
                while ($this->sheetNameExists($newTitle)) {
189✔
624
                    ++$i;
44✔
625
                    $newTitle = "$title $i";
44✔
626
                }
627
                $worksheet->setTitle($newTitle);
189✔
628
            }
629
        }
630
        if ($this->sheetNameExists($worksheet->getTitle())) {
1,493✔
631
            throw new Exception(
2✔
632
                "Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename this worksheet first."
2✔
633
            );
2✔
634
        }
635

636
        if ($sheetIndex === null) {
1,493✔
637
            if ($this->activeSheetIndex < 0) {
1,459✔
638
                $this->activeSheetIndex = 0;
1,043✔
639
            }
640
            $this->workSheetCollection[] = $worksheet;
1,459✔
641
        } else {
642
            // Insert the sheet at the requested index
643
            array_splice(
39✔
644
                $this->workSheetCollection,
39✔
645
                $sheetIndex,
39✔
646
                0,
39✔
647
                [$worksheet]
39✔
648
            );
39✔
649

650
            // Adjust active sheet index if necessary
651
            if ($this->activeSheetIndex >= $sheetIndex) {
39✔
652
                ++$this->activeSheetIndex;
30✔
653
            }
654
            if ($this->activeSheetIndex < 0) {
39✔
655
                $this->activeSheetIndex = 0;
4✔
656
            }
657
        }
658

659
        if ($worksheet->getParent() === null) {
1,493✔
660
            $worksheet->rebindParent($this);
51✔
661
        }
662

663
        return $worksheet;
1,493✔
664
    }
665

666
    /**
667
     * Remove sheet by index.
668
     *
669
     * @param int $sheetIndex Index position of the worksheet to remove
670
     */
671
    public function removeSheetByIndex(int $sheetIndex): void
1,093✔
672
    {
673
        $numSheets = count($this->workSheetCollection);
1,093✔
674
        if ($sheetIndex > $numSheets - 1) {
1,093✔
675
            throw new Exception(
1✔
676
                "You tried to remove a sheet by the out of bounds index: {$sheetIndex}. The actual number of sheets is {$numSheets}."
1✔
677
            );
1✔
678
        }
679
        array_splice($this->workSheetCollection, $sheetIndex, 1);
1,092✔
680

681
        // Adjust active sheet index if necessary
682
        if (
683
            ($this->activeSheetIndex >= $sheetIndex)
1,092✔
684
            && ($this->activeSheetIndex > 0 || $numSheets <= 1)
1,092✔
685
        ) {
686
            --$this->activeSheetIndex;
1,090✔
687
        }
688
    }
689

690
    /**
691
     * Get sheet by index.
692
     *
693
     * @param int $sheetIndex Sheet index
694
     */
695
    public function getSheet(int $sheetIndex): Worksheet
11,309✔
696
    {
697
        if (!isset($this->workSheetCollection[$sheetIndex])) {
11,309✔
698
            $numSheets = $this->getSheetCount();
1✔
699

700
            throw new Exception(
1✔
701
                "Your requested sheet index: {$sheetIndex} is out of bounds. The actual number of sheets is {$numSheets}."
1✔
702
            );
1✔
703
        }
704

705
        return $this->workSheetCollection[$sheetIndex];
11,309✔
706
    }
707

708
    /**
709
     * Get all sheets.
710
     *
711
     * @return Worksheet[]
712
     */
713
    public function getAllSheets(): array
199✔
714
    {
715
        return $this->workSheetCollection;
199✔
716
    }
717

718
    /**
719
     * Get sheet by name.
720
     *
721
     * @param string $worksheetName Sheet name
722
     */
723
    public function getSheetByName(string $worksheetName): ?Worksheet
10,038✔
724
    {
725
        $trimWorksheetName = StringHelper::strToUpper(trim($worksheetName, "'"));
10,038✔
726
        foreach ($this->workSheetCollection as $worksheet) {
10,038✔
727
            if (StringHelper::strToUpper($worksheet->getTitle()) === $trimWorksheetName) {
9,639✔
728
                return $worksheet;
9,035✔
729
            }
730
        }
731

732
        return null;
2,015✔
733
    }
734

735
    /**
736
     * Get sheet by name, throwing exception if not found.
737
     */
738
    public function getSheetByNameOrThrow(string $worksheetName): Worksheet
250✔
739
    {
740
        $worksheet = $this->getSheetByName($worksheetName);
250✔
741
        if ($worksheet === null) {
250✔
742
            throw new Exception("Sheet $worksheetName does not exist.");
1✔
743
        }
744

745
        return $worksheet;
249✔
746
    }
747

748
    /**
749
     * Get index for sheet.
750
     *
751
     * @return int index
752
     */
753
    public function getIndex(Worksheet $worksheet, bool $noThrow = false): int
11,411✔
754
    {
755
        foreach ($this->workSheetCollection as $key => $value) {
11,411✔
756
            if ($value === $worksheet) {
11,097✔
757
                return $key;
11,085✔
758
            }
759
        }
760
        if ($noThrow) {
11,411✔
761
            return -1;
11,411✔
762
        }
763

764
        throw new Exception('Sheet does not exist.');
3✔
765
    }
766

767
    /**
768
     * Set index for sheet by sheet name.
769
     *
770
     * @param string $worksheetName Sheet name to modify index for
771
     * @param int $newIndexPosition New index for the sheet
772
     *
773
     * @return int New sheet index
774
     */
775
    public function setIndexByName(string $worksheetName, int $newIndexPosition): int
1✔
776
    {
777
        $oldIndex = $this->getIndex($this->getSheetByNameOrThrow($worksheetName));
1✔
778
        $worksheet = array_splice(
1✔
779
            $this->workSheetCollection,
1✔
780
            $oldIndex,
1✔
781
            1
1✔
782
        );
1✔
783
        array_splice(
1✔
784
            $this->workSheetCollection,
1✔
785
            $newIndexPosition,
1✔
786
            0,
1✔
787
            $worksheet
1✔
788
        );
1✔
789

790
        return $newIndexPosition;
1✔
791
    }
792

793
    /**
794
     * Get sheet count.
795
     */
796
    public function getSheetCount(): int
1,826✔
797
    {
798
        return count($this->workSheetCollection);
1,826✔
799
    }
800

801
    /**
802
     * Get active sheet index.
803
     *
804
     * @return int Active sheet index
805
     */
806
    public function getActiveSheetIndex(): int
10,957✔
807
    {
808
        return $this->activeSheetIndex;
10,957✔
809
    }
810

811
    /**
812
     * Set active sheet index.
813
     *
814
     * @param int $worksheetIndex Active sheet index
815
     */
816
    public function setActiveSheetIndex(int $worksheetIndex): Worksheet
11,044✔
817
    {
818
        $numSheets = count($this->workSheetCollection);
11,044✔
819

820
        if ($worksheetIndex > $numSheets - 1) {
11,044✔
821
            throw new Exception(
11✔
822
                "You tried to set a sheet active by the out of bounds index: {$worksheetIndex}. The actual number of sheets is {$numSheets}."
11✔
823
            );
11✔
824
        }
825
        $this->activeSheetIndex = $worksheetIndex;
11,033✔
826

827
        return $this->getActiveSheet();
11,033✔
828
    }
829

830
    /**
831
     * Set active sheet index by name.
832
     *
833
     * @param string $worksheetName Sheet title
834
     */
835
    public function setActiveSheetIndexByName(string $worksheetName): Worksheet
132✔
836
    {
837
        if (($worksheet = $this->getSheetByName($worksheetName)) instanceof Worksheet) {
132✔
838
            $this->setActiveSheetIndex($this->getIndex($worksheet));
129✔
839

840
            return $worksheet;
129✔
841
        }
842

843
        throw new Exception('Workbook does not contain sheet:' . $worksheetName);
3✔
844
    }
845

846
    /**
847
     * Get sheet names.
848
     *
849
     * @return string[]
850
     */
851
    public function getSheetNames(): array
10✔
852
    {
853
        $returnValue = [];
10✔
854
        $worksheetCount = $this->getSheetCount();
10✔
855
        for ($i = 0; $i < $worksheetCount; ++$i) {
10✔
856
            $returnValue[] = $this->getSheet($i)->getTitle();
10✔
857
        }
858

859
        return $returnValue;
10✔
860
    }
861

862
    /**
863
     * Add external sheet.
864
     *
865
     * @param Worksheet $worksheet External sheet to add
866
     * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
867
     */
868
    public function addExternalSheet(Worksheet $worksheet, ?int $sheetIndex = null): Worksheet
5✔
869
    {
870
        if ($this->sheetNameExists($worksheet->getTitle())) {
5✔
871
            throw new Exception("Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename the external sheet first.");
1✔
872
        }
873

874
        // count how many cellXfs there are in this workbook currently, we will need this below
875
        $countCellXfs = count($this->cellXfCollection);
4✔
876

877
        // copy all the shared cellXfs from the external workbook and append them to the current
878
        foreach ($worksheet->getParentOrThrow()->getCellXfCollection() as $cellXf) {
4✔
879
            $this->addCellXf(clone $cellXf);
4✔
880
        }
881

882
        // move sheet to this workbook
883
        $worksheet->rebindParent($this);
4✔
884

885
        // update the cellXfs
886
        foreach ($worksheet->getCoordinates(false) as $coordinate) {
4✔
887
            $cell = $worksheet->getCell($coordinate);
4✔
888
            $cell->setXfIndex($cell->getXfIndex() + $countCellXfs);
4✔
889
        }
890

891
        // update the column dimensions Xfs
892
        foreach ($worksheet->getColumnDimensions() as $columnDimension) {
4✔
893
            $columnDimension->setXfIndex($columnDimension->getXfIndex() + $countCellXfs);
1✔
894
        }
895

896
        // update the row dimensions Xfs
897
        foreach ($worksheet->getRowDimensions() as $rowDimension) {
4✔
898
            $xfIndex = $rowDimension->getXfIndex();
1✔
899
            if ($xfIndex !== null) {
1✔
900
                $rowDimension->setXfIndex($xfIndex + $countCellXfs);
1✔
901
            }
902
        }
903

904
        return $this->addSheet($worksheet, $sheetIndex);
4✔
905
    }
906

907
    /**
908
     * Get an array of all Named Ranges.
909
     *
910
     * @return DefinedName[]
911
     */
912
    public function getNamedRanges(): array
9✔
913
    {
914
        return array_filter(
9✔
915
            $this->definedNames,
9✔
916
            fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_RANGE
9✔
917
        );
9✔
918
    }
919

920
    /**
921
     * Get an array of all Named Formulae.
922
     *
923
     * @return DefinedName[]
924
     */
925
    public function getNamedFormulae(): array
15✔
926
    {
927
        return array_filter(
15✔
928
            $this->definedNames,
15✔
929
            fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_FORMULA
15✔
930
        );
15✔
931
    }
932

933
    /**
934
     * Get an array of all Defined Names (both named ranges and named formulae).
935
     *
936
     * @return DefinedName[]
937
     */
938
    public function getDefinedNames(): array
706✔
939
    {
940
        return $this->definedNames;
706✔
941
    }
942

943
    /**
944
     * Add a named range.
945
     * If a named range with this name already exists, then this will replace the existing value.
946
     */
947
    public function addNamedRange(NamedRange $namedRange): void
351✔
948
    {
949
        $this->addDefinedName($namedRange);
351✔
950
    }
951

952
    /**
953
     * Add a named formula.
954
     * If a named formula with this name already exists, then this will replace the existing value.
955
     */
956
    public function addNamedFormula(NamedFormula $namedFormula): void
12✔
957
    {
958
        $this->addDefinedName($namedFormula);
12✔
959
    }
960

961
    /**
962
     * Add a defined name (either a named range or a named formula).
963
     * If a defined named with this name already exists, then this will replace the existing value.
964
     */
965
    public function addDefinedName(DefinedName $definedName): void
499✔
966
    {
967
        $upperCaseName = StringHelper::strToUpper($definedName->getName());
499✔
968
        if ($definedName->getScope() == null) {
499✔
969
            // global scope
970
            $this->definedNames[$upperCaseName] = $definedName;
485✔
971
        } else {
972
            // local scope
973
            $this->definedNames[$definedName->getScope()->getTitle() . '!' . $upperCaseName] = $definedName;
146✔
974
        }
975
    }
976

977
    /**
978
     * Get named range.
979
     *
980
     * @param null|Worksheet $worksheet Scope. Use null for global scope
981
     */
982
    public function getNamedRange(string $namedRange, ?Worksheet $worksheet = null): ?NamedRange
34✔
983
    {
984
        $returnValue = null;
34✔
985

986
        if ($namedRange !== '') {
34✔
987
            $namedRange = StringHelper::strToUpper($namedRange);
33✔
988
            // first look for global named range
989
            $returnValue = $this->getGlobalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE);
33✔
990
            // then look for local named range (has priority over global named range if both names exist)
991
            $returnValue = $this->getLocalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE, $worksheet) ?: $returnValue;
33✔
992
        }
993

994
        return $returnValue instanceof NamedRange ? $returnValue : null;
34✔
995
    }
996

997
    /**
998
     * Get named formula.
999
     *
1000
     * @param null|Worksheet $worksheet Scope. Use null for global scope
1001
     */
1002
    public function getNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): ?NamedFormula
11✔
1003
    {
1004
        $returnValue = null;
11✔
1005

1006
        if ($namedFormula !== '') {
11✔
1007
            $namedFormula = StringHelper::strToUpper($namedFormula);
11✔
1008
            // first look for global named formula
1009
            $returnValue = $this->getGlobalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA);
11✔
1010
            // then look for local named formula (has priority over global named formula if both names exist)
1011
            $returnValue = $this->getLocalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA, $worksheet) ?: $returnValue;
11✔
1012
        }
1013

1014
        return $returnValue instanceof NamedFormula ? $returnValue : null;
11✔
1015
    }
1016

1017
    private function getGlobalDefinedNameByType(string $name, bool $type): ?DefinedName
44✔
1018
    {
1019
        if (isset($this->definedNames[$name]) && $this->definedNames[$name]->isFormula() === $type) {
44✔
1020
            return $this->definedNames[$name];
30✔
1021
        }
1022

1023
        return null;
16✔
1024
    }
1025

1026
    private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $worksheet = null): ?DefinedName
44✔
1027
    {
1028
        if (
1029
            ($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $name])
44✔
1030
            && $this->definedNames[$worksheet->getTitle() . '!' . $name]->isFormula() === $type
44✔
1031
        ) {
1032
            return $this->definedNames[$worksheet->getTitle() . '!' . $name];
8✔
1033
        }
1034

1035
        return null;
42✔
1036
    }
1037

1038
    /**
1039
     * Get named range.
1040
     *
1041
     * @param null|Worksheet $worksheet Scope. Use null for global scope
1042
     */
1043
    public function getDefinedName(string $definedName, ?Worksheet $worksheet = null): ?DefinedName
10,978✔
1044
    {
1045
        $returnValue = null;
10,978✔
1046

1047
        if ($definedName !== '') {
10,978✔
1048
            $definedName = StringHelper::strToUpper($definedName);
10,978✔
1049
            // first look for global defined name
1050
            foreach ($this->definedNames as $dn) {
10,978✔
1051
                $upper = StringHelper::strToUpper($dn->getName());
421✔
1052
                if (
1053
                    !$dn->getLocalOnly()
421✔
1054
                    && $definedName === $upper
421✔
1055
                ) {
1056
                    $returnValue = $dn;
148✔
1057

1058
                    break;
148✔
1059
                }
1060
            }
1061

1062
            // then look for local defined name (has priority over global defined name if both names exist)
1063
            if ($worksheet !== null) {
10,978✔
1064
                $wsTitle = StringHelper::strToUpper($worksheet->getTitle());
10,976✔
1065
                $definedName = Preg::replace('/^.*!/', '', $definedName);
10,976✔
1066
                foreach ($this->definedNames as $dn) {
10,976✔
1067
                    $sheet = $dn->getScope() ?? $dn->getWorksheet();
417✔
1068
                    $upper = StringHelper::strToUpper($dn->getName());
417✔
1069
                    $upperTitle = StringHelper::strToUpper((string) $sheet?->getTitle());
417✔
1070
                    if (
1071
                        $dn->getLocalOnly()
417✔
1072
                        && $upper === $definedName
417✔
1073
                        && $upperTitle === $wsTitle
417✔
1074
                    ) {
1075
                        return $dn;
28✔
1076
                    }
1077
                }
1078
            }
1079
        }
1080

1081
        return $returnValue;
10,977✔
1082
    }
1083

1084
    /**
1085
     * Remove named range.
1086
     *
1087
     * @param null|Worksheet $worksheet scope: use null for global scope
1088
     *
1089
     * @return $this
1090
     */
1091
    public function removeNamedRange(string $namedRange, ?Worksheet $worksheet = null): self
5✔
1092
    {
1093
        if ($this->getNamedRange($namedRange, $worksheet) === null) {
5✔
1094
            return $this;
1✔
1095
        }
1096

1097
        return $this->removeDefinedName($namedRange, $worksheet);
4✔
1098
    }
1099

1100
    /**
1101
     * Remove named formula.
1102
     *
1103
     * @param null|Worksheet $worksheet scope: use null for global scope
1104
     *
1105
     * @return $this
1106
     */
1107
    public function removeNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): self
4✔
1108
    {
1109
        if ($this->getNamedFormula($namedFormula, $worksheet) === null) {
4✔
1110
            return $this;
1✔
1111
        }
1112

1113
        return $this->removeDefinedName($namedFormula, $worksheet);
3✔
1114
    }
1115

1116
    /**
1117
     * Remove defined name.
1118
     *
1119
     * @param null|Worksheet $worksheet scope: use null for global scope
1120
     *
1121
     * @return $this
1122
     */
1123
    public function removeDefinedName(string $definedName, ?Worksheet $worksheet = null): self
11✔
1124
    {
1125
        $definedName = StringHelper::strToUpper($definedName);
11✔
1126

1127
        if ($worksheet === null) {
11✔
1128
            if (isset($this->definedNames[$definedName])) {
1✔
1129
                unset($this->definedNames[$definedName]);
1✔
1130
            }
1131
        } else {
1132
            if (isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) {
10✔
1133
                unset($this->definedNames[$worksheet->getTitle() . '!' . $definedName]);
3✔
1134
            } elseif (isset($this->definedNames[$definedName])) {
7✔
1135
                unset($this->definedNames[$definedName]);
7✔
1136
            }
1137
        }
1138

1139
        return $this;
11✔
1140
    }
1141

1142
    /**
1143
     * Get worksheet iterator.
1144
     */
1145
    public function getWorksheetIterator(): Iterator
1,570✔
1146
    {
1147
        return new Iterator($this);
1,570✔
1148
    }
1149

1150
    /**
1151
     * Copy workbook (!= clone!).
1152
     *
1153
     * Uses serialize/unserialize which is broadly faster than clone across
1154
     * PHP versions and platforms, though clone uses less memory.
1155
     *
1156
     * @see \PhpOffice\PhpSpreadsheetBenchmarks\SpreadsheetCopyBenchmarkTest
1157
     */
1158
    public function copy(): self
12✔
1159
    {
1160
        return unserialize(serialize($this)); //* @phpstan-ignore-line
12✔
1161
    }
1162

1163
    /**
1164
     * Implement PHP __clone to create a deep clone, not just a shallow copy.
1165
     *
1166
     * Clone uses less memory than serialize/unserialize but speed varies
1167
     * across PHP versions and platforms.
1168
     *
1169
     * @see \PhpOffice\PhpSpreadsheetBenchmarks\SpreadsheetCopyBenchmarkTest
1170
     */
1171
    public function __clone()
12✔
1172
    {
1173
        $this->uniqueID = uniqid('', true);
12✔
1174

1175
        $usedKeys = [];
12✔
1176
        // I don't know why new Style rather than clone.
1177
        $this->cellXfSupervisor = new Style(true);
12✔
1178
        //$this->cellXfSupervisor = clone $this->cellXfSupervisor;
1179
        $this->cellXfSupervisor->bindParent($this);
12✔
1180
        $usedKeys['cellXfSupervisor'] = true;
12✔
1181

1182
        $oldCalc = $this->calculationEngine;
12✔
1183
        $this->calculationEngine = new Calculation($this);
12✔
1184
        $this->calculationEngine
12✔
1185
            ->setSuppressFormulaErrors(
12✔
1186
                $oldCalc->getSuppressFormulaErrors()
12✔
1187
            )
12✔
1188
            ->setCalculationCacheEnabled(
12✔
1189
                $oldCalc->getCalculationCacheEnabled()
12✔
1190
            )
12✔
1191
            ->setBranchPruningEnabled(
12✔
1192
                $oldCalc->getBranchPruningEnabled()
12✔
1193
            )
12✔
1194
            ->setInstanceArrayReturnType(
12✔
1195
                $oldCalc->getInstanceArrayReturnType()
12✔
1196
            );
12✔
1197
        $usedKeys['calculationEngine'] = true;
12✔
1198

1199
        $currentCollection = $this->cellStyleXfCollection;
12✔
1200
        $this->cellStyleXfCollection = [];
12✔
1201
        foreach ($currentCollection as $item) {
12✔
1202
            $clone = $item->exportArray();
12✔
1203
            $style = (new Style())->applyFromArray($clone);
12✔
1204
            $this->addCellStyleXf($style);
12✔
1205
        }
1206
        $usedKeys['cellStyleXfCollection'] = true;
12✔
1207

1208
        $currentCollection = $this->cellXfCollection;
12✔
1209
        $this->cellXfCollection = [];
12✔
1210
        foreach ($currentCollection as $item) {
12✔
1211
            $clone = $item->exportArray();
12✔
1212
            $style = (new Style())->applyFromArray($clone);
12✔
1213
            $this->addCellXf($style);
12✔
1214
        }
1215
        $usedKeys['cellXfCollection'] = true;
12✔
1216

1217
        $currentCollection = $this->workSheetCollection;
12✔
1218
        $this->workSheetCollection = [];
12✔
1219
        foreach ($currentCollection as $item) {
12✔
1220
            $clone = clone $item;
12✔
1221
            $clone->setParent($this);
12✔
1222
            $this->workSheetCollection[] = $clone;
12✔
1223
        }
1224
        $usedKeys['workSheetCollection'] = true;
12✔
1225

1226
        foreach (get_object_vars($this) as $key => $val) {
12✔
1227
            if (isset($usedKeys[$key])) {
12✔
1228
                continue;
12✔
1229
            }
1230
            switch ($key) {
1231
                // arrays of objects not covered above
1232
                case 'definedNames':
12✔
1233
                    /** @var DefinedName[] */
1234
                    $currentCollection = $val;
12✔
1235
                    $this->$key = [];
12✔
1236
                    foreach ($currentCollection as $item) {
12✔
1237
                        $clone = clone $item;
2✔
1238
                        $title = $clone->getWorksheet()?->getTitle();
2✔
1239
                        if ($title !== null) {
2✔
1240
                            $ws = $this->getSheetByName($title);
2✔
1241
                            $clone->setWorksheet($ws);
2✔
1242
                        }
1243
                        $title = $clone->getScope()?->getTitle();
2✔
1244
                        if ($title !== null) {
2✔
1245
                            $ws = $this->getSheetByName($title);
1✔
1246
                            $clone->setScope($ws);
1✔
1247
                        }
1248
                        $this->{$key}[] = $clone;
2✔
1249
                    }
1250

1251
                    break;
12✔
1252
                default:
1253
                    if (is_object($val)) {
12✔
1254
                        $this->$key = clone $val;
12✔
1255
                    }
1256
            }
1257
        }
1258
    }
1259

1260
    /**
1261
     * Get the workbook collection of cellXfs.
1262
     *
1263
     * @return Style[]
1264
     */
1265
    public function getCellXfCollection(): array
1,359✔
1266
    {
1267
        return $this->cellXfCollection;
1,359✔
1268
    }
1269

1270
    /**
1271
     * Get cellXf by index.
1272
     */
1273
    public function getCellXfByIndex(int $cellStyleIndex): Style
10,876✔
1274
    {
1275
        return $this->cellXfCollection[$cellStyleIndex];
10,876✔
1276
    }
1277

1278
    public function getCellXfByIndexOrNull(?int $cellStyleIndex): ?Style
2✔
1279
    {
1280
        return ($cellStyleIndex === null) ? null : ($this->cellXfCollection[$cellStyleIndex] ?? null);
2✔
1281
    }
1282

1283
    /**
1284
     * Get cellXf by hash code.
1285
     *
1286
     * @return false|Style
1287
     */
1288
    public function getCellXfByHashCode(string $hashcode): bool|Style
1,034✔
1289
    {
1290
        foreach ($this->cellXfCollection as $cellXf) {
1,034✔
1291
            if ($cellXf->getHashCode() === $hashcode) {
1,034✔
1292
                return $cellXf;
313✔
1293
            }
1294
        }
1295

1296
        return false;
972✔
1297
    }
1298

1299
    /**
1300
     * Check if style exists in style collection.
1301
     */
1302
    public function cellXfExists(Style $cellStyleIndex): bool
1✔
1303
    {
1304
        return in_array($cellStyleIndex, $this->cellXfCollection, true);
1✔
1305
    }
1306

1307
    /**
1308
     * Get default style.
1309
     */
1310
    public function getDefaultStyle(): Style
1,250✔
1311
    {
1312
        if (isset($this->cellXfCollection[0])) {
1,250✔
1313
            return $this->cellXfCollection[0];
1,249✔
1314
        }
1315

1316
        throw new Exception('No default style found for this workbook');
1✔
1317
    }
1318

1319
    /**
1320
     * Add a cellXf to the workbook.
1321
     */
1322
    public function addCellXf(Style $style): void
11,411✔
1323
    {
1324
        $this->cellXfCollection[] = $style;
11,411✔
1325
        $style->setIndex(count($this->cellXfCollection) - 1);
11,411✔
1326
    }
1327

1328
    /**
1329
     * Remove cellXf by index. It is ensured that all cells get their xf index updated.
1330
     *
1331
     * @param int $cellStyleIndex Index to cellXf
1332
     */
1333
    public function removeCellXfByIndex(int $cellStyleIndex): void
892✔
1334
    {
1335
        if ($cellStyleIndex > count($this->cellXfCollection) - 1) {
892✔
1336
            throw new Exception('CellXf index is out of bounds.');
1✔
1337
        }
1338

1339
        // first remove the cellXf
1340
        array_splice($this->cellXfCollection, $cellStyleIndex, 1);
891✔
1341

1342
        // then update cellXf indexes for cells
1343
        foreach ($this->workSheetCollection as $worksheet) {
891✔
1344
            foreach ($worksheet->getCoordinates(false) as $coordinate) {
2✔
1345
                $cell = $worksheet->getCell($coordinate);
1✔
1346
                $xfIndex = $cell->getXfIndex();
1✔
1347
                if ($xfIndex > $cellStyleIndex) {
1✔
1348
                    // decrease xf index by 1
1349
                    $cell->setXfIndex($xfIndex - 1);
1✔
1350
                } elseif ($xfIndex == $cellStyleIndex) {
1✔
1351
                    // set to default xf index 0
1352
                    $cell->setXfIndex(0);
1✔
1353
                }
1354
            }
1355
        }
1356
    }
1357

1358
    /**
1359
     * Get the cellXf supervisor.
1360
     */
1361
    public function getCellXfSupervisor(): Style
10,902✔
1362
    {
1363
        return $this->cellXfSupervisor;
10,902✔
1364
    }
1365

1366
    /**
1367
     * Get the workbook collection of cellStyleXfs.
1368
     *
1369
     * @return Style[]
1370
     */
1371
    public function getCellStyleXfCollection(): array
1✔
1372
    {
1373
        return $this->cellStyleXfCollection;
1✔
1374
    }
1375

1376
    /**
1377
     * Get cellStyleXf by index.
1378
     *
1379
     * @param int $cellStyleIndex Index to cellXf
1380
     */
1381
    public function getCellStyleXfByIndex(int $cellStyleIndex): Style
1✔
1382
    {
1383
        return $this->cellStyleXfCollection[$cellStyleIndex];
1✔
1384
    }
1385

1386
    /**
1387
     * Get cellStyleXf by hash code.
1388
     *
1389
     * @return false|Style
1390
     */
1391
    public function getCellStyleXfByHashCode(string $hashcode): bool|Style
1✔
1392
    {
1393
        foreach ($this->cellStyleXfCollection as $cellStyleXf) {
1✔
1394
            if ($cellStyleXf->getHashCode() === $hashcode) {
1✔
1395
                return $cellStyleXf;
1✔
1396
            }
1397
        }
1398

1399
        return false;
1✔
1400
    }
1401

1402
    /**
1403
     * Add a cellStyleXf to the workbook.
1404
     */
1405
    public function addCellStyleXf(Style $style): void
11,411✔
1406
    {
1407
        $this->cellStyleXfCollection[] = $style;
11,411✔
1408
        $style->setIndex(count($this->cellStyleXfCollection) - 1);
11,411✔
1409
    }
1410

1411
    /**
1412
     * Remove cellStyleXf by index.
1413
     *
1414
     * @param int $cellStyleIndex Index to cellXf
1415
     */
1416
    public function removeCellStyleXfByIndex(int $cellStyleIndex): void
889✔
1417
    {
1418
        if ($cellStyleIndex > count($this->cellStyleXfCollection) - 1) {
889✔
1419
            throw new Exception('CellStyleXf index is out of bounds.');
1✔
1420
        }
1421
        array_splice($this->cellStyleXfCollection, $cellStyleIndex, 1);
888✔
1422
    }
1423

1424
    /**
1425
     * Eliminate all unneeded cellXf and afterwards update the xfIndex for all cells
1426
     * and columns in the workbook.
1427
     */
1428
    public function garbageCollect(): void
1,164✔
1429
    {
1430
        // how many references are there to each cellXf ?
1431
        $countReferencesCellXf = [];
1,164✔
1432
        foreach ($this->cellXfCollection as $index => $cellXf) {
1,164✔
1433
            $countReferencesCellXf[$index] = 0;
1,164✔
1434
        }
1435

1436
        foreach ($this->getWorksheetIterator() as $sheet) {
1,164✔
1437
            // from cells
1438
            foreach ($sheet->getCoordinates(false) as $coordinate) {
1,164✔
1439
                $cell = $sheet->getCell($coordinate);
1,133✔
1440
                ++$countReferencesCellXf[$cell->getXfIndex()];
1,133✔
1441
            }
1442

1443
            // from row dimensions
1444
            foreach ($sheet->getRowDimensions() as $rowDimension) {
1,164✔
1445
                if ($rowDimension->getXfIndex() !== null) {
111✔
1446
                    ++$countReferencesCellXf[$rowDimension->getXfIndex()];
11✔
1447
                }
1448
            }
1449

1450
            // from column dimensions
1451
            foreach ($sheet->getColumnDimensions() as $columnDimension) {
1,164✔
1452
                ++$countReferencesCellXf[$columnDimension->getXfIndex()];
174✔
1453
            }
1454
        }
1455

1456
        // remove cellXfs without references and create mapping so we can update xfIndex
1457
        // for all cells and columns
1458
        $countNeededCellXfs = 0;
1,164✔
1459
        $map = [];
1,164✔
1460
        foreach ($this->cellXfCollection as $index => $cellXf) {
1,164✔
1461
            if ($countReferencesCellXf[$index] > 0 || $index == 0) { // we must never remove the first cellXf
1,164✔
1462
                ++$countNeededCellXfs;
1,164✔
1463
            } else {
1464
                unset($this->cellXfCollection[$index]);
44✔
1465
            }
1466
            $map[$index] = $countNeededCellXfs - 1;
1,164✔
1467
        }
1468
        $this->cellXfCollection = array_values($this->cellXfCollection);
1,164✔
1469

1470
        // update the index for all cellXfs
1471
        foreach ($this->cellXfCollection as $i => $cellXf) {
1,164✔
1472
            $cellXf->setIndex($i);
1,164✔
1473
        }
1474

1475
        // make sure there is always at least one cellXf (there should be)
1476
        if (empty($this->cellXfCollection)) {
1,164✔
UNCOV
1477
            $this->cellXfCollection[] = new Style();
×
1478
        }
1479

1480
        // update the xfIndex for all cells, row dimensions, column dimensions
1481
        foreach ($this->getWorksheetIterator() as $sheet) {
1,164✔
1482
            // for all cells
1483
            foreach ($sheet->getCoordinates(false) as $coordinate) {
1,164✔
1484
                $cell = $sheet->getCell($coordinate);
1,133✔
1485
                $cell->setXfIndex($map[$cell->getXfIndex()]);
1,133✔
1486
            }
1487

1488
            // for all row dimensions
1489
            foreach ($sheet->getRowDimensions() as $rowDimension) {
1,164✔
1490
                if ($rowDimension->getXfIndex() !== null) {
111✔
1491
                    $rowDimension->setXfIndex($map[$rowDimension->getXfIndex()]);
11✔
1492
                }
1493
            }
1494

1495
            // for all column dimensions
1496
            foreach ($sheet->getColumnDimensions() as $columnDimension) {
1,164✔
1497
                $columnDimension->setXfIndex($map[$columnDimension->getXfIndex()]);
174✔
1498
            }
1499

1500
            // also do garbage collection for all the sheets
1501
            $sheet->garbageCollect();
1,164✔
1502
        }
1503
    }
1504

1505
    /**
1506
     * Return the unique ID value assigned to this spreadsheet workbook.
1507
     *
1508
     * @deprecated 5.2.0 Serves no useful purpose. No replacement.
1509
     *
1510
     * @codeCoverageIgnore
1511
     */
1512
    public function getID(): string
1513
    {
1514
        return $this->uniqueID;
1515
    }
1516

1517
    /**
1518
     * Get the visibility of the horizonal scroll bar in the application.
1519
     *
1520
     * @return bool True if horizonal scroll bar is visible
1521
     */
1522
    public function getShowHorizontalScroll(): bool
443✔
1523
    {
1524
        return $this->showHorizontalScroll;
443✔
1525
    }
1526

1527
    /**
1528
     * Set the visibility of the horizonal scroll bar in the application.
1529
     *
1530
     * @param bool $showHorizontalScroll True if horizonal scroll bar is visible
1531
     */
1532
    public function setShowHorizontalScroll(bool $showHorizontalScroll): void
319✔
1533
    {
1534
        $this->showHorizontalScroll = (bool) $showHorizontalScroll;
319✔
1535
    }
1536

1537
    /**
1538
     * Get the visibility of the vertical scroll bar in the application.
1539
     *
1540
     * @return bool True if vertical scroll bar is visible
1541
     */
1542
    public function getShowVerticalScroll(): bool
443✔
1543
    {
1544
        return $this->showVerticalScroll;
443✔
1545
    }
1546

1547
    /**
1548
     * Set the visibility of the vertical scroll bar in the application.
1549
     *
1550
     * @param bool $showVerticalScroll True if vertical scroll bar is visible
1551
     */
1552
    public function setShowVerticalScroll(bool $showVerticalScroll): void
319✔
1553
    {
1554
        $this->showVerticalScroll = (bool) $showVerticalScroll;
319✔
1555
    }
1556

1557
    /**
1558
     * Get the visibility of the sheet tabs in the application.
1559
     *
1560
     * @return bool True if the sheet tabs are visible
1561
     */
1562
    public function getShowSheetTabs(): bool
443✔
1563
    {
1564
        return $this->showSheetTabs;
443✔
1565
    }
1566

1567
    /**
1568
     * Set the visibility of the sheet tabs  in the application.
1569
     *
1570
     * @param bool $showSheetTabs True if sheet tabs are visible
1571
     */
1572
    public function setShowSheetTabs(bool $showSheetTabs): void
319✔
1573
    {
1574
        $this->showSheetTabs = (bool) $showSheetTabs;
319✔
1575
    }
1576

1577
    /**
1578
     * Return whether the workbook window is minimized.
1579
     *
1580
     * @return bool true if workbook window is minimized
1581
     */
1582
    public function getMinimized(): bool
443✔
1583
    {
1584
        return $this->minimized;
443✔
1585
    }
1586

1587
    /**
1588
     * Set whether the workbook window is minimized.
1589
     *
1590
     * @param bool $minimized true if workbook window is minimized
1591
     */
1592
    public function setMinimized(bool $minimized): void
301✔
1593
    {
1594
        $this->minimized = (bool) $minimized;
301✔
1595
    }
1596

1597
    /**
1598
     * Return whether to group dates when presenting the user with
1599
     * filtering options in the user interface.
1600
     *
1601
     * @return bool true if workbook window is minimized
1602
     */
1603
    public function getAutoFilterDateGrouping(): bool
443✔
1604
    {
1605
        return $this->autoFilterDateGrouping;
443✔
1606
    }
1607

1608
    /**
1609
     * Set whether to group dates when presenting the user with
1610
     * filtering options in the user interface.
1611
     *
1612
     * @param bool $autoFilterDateGrouping true if workbook window is minimized
1613
     */
1614
    public function setAutoFilterDateGrouping(bool $autoFilterDateGrouping): void
301✔
1615
    {
1616
        $this->autoFilterDateGrouping = (bool) $autoFilterDateGrouping;
301✔
1617
    }
1618

1619
    /**
1620
     * Return the first sheet in the book view.
1621
     *
1622
     * @return int First sheet in book view
1623
     */
1624
    public function getFirstSheetIndex(): int
443✔
1625
    {
1626
        return $this->firstSheetIndex;
443✔
1627
    }
1628

1629
    /**
1630
     * Set the first sheet in the book view.
1631
     *
1632
     * @param int $firstSheetIndex First sheet in book view
1633
     */
1634
    public function setFirstSheetIndex(int $firstSheetIndex): void
320✔
1635
    {
1636
        if ($firstSheetIndex >= 0) {
320✔
1637
            $this->firstSheetIndex = (int) $firstSheetIndex;
319✔
1638
        } else {
1639
            throw new Exception('First sheet index must be a positive integer.');
1✔
1640
        }
1641
    }
1642

1643
    /**
1644
     * Return the visibility status of the workbook.
1645
     *
1646
     * This may be one of the following three values:
1647
     * - visibile
1648
     *
1649
     * @return string Visible status
1650
     */
1651
    public function getVisibility(): string
444✔
1652
    {
1653
        return $this->visibility;
444✔
1654
    }
1655

1656
    /**
1657
     * Set the visibility status of the workbook.
1658
     *
1659
     * Valid values are:
1660
     *  - 'visible' (self::VISIBILITY_VISIBLE):
1661
     *       Workbook window is visible
1662
     *  - 'hidden' (self::VISIBILITY_HIDDEN):
1663
     *       Workbook window is hidden, but can be shown by the user
1664
     *       via the user interface
1665
     *  - 'veryHidden' (self::VISIBILITY_VERY_HIDDEN):
1666
     *       Workbook window is hidden and cannot be shown in the
1667
     *       user interface.
1668
     *
1669
     * @param null|string $visibility visibility status of the workbook
1670
     */
1671
    public function setVisibility(?string $visibility): void
302✔
1672
    {
1673
        if ($visibility === null) {
302✔
1674
            $visibility = self::VISIBILITY_VISIBLE;
1✔
1675
        }
1676

1677
        if (in_array($visibility, self::WORKBOOK_VIEW_VISIBILITY_VALUES)) {
302✔
1678
            $this->visibility = $visibility;
302✔
1679
        } else {
1680
            throw new Exception('Invalid visibility value.');
1✔
1681
        }
1682
    }
1683

1684
    /**
1685
     * Get the ratio between the workbook tabs bar and the horizontal scroll bar.
1686
     * TabRatio is assumed to be out of 1000 of the horizontal window width.
1687
     *
1688
     * @return int Ratio between the workbook tabs bar and the horizontal scroll bar
1689
     */
1690
    public function getTabRatio(): int
443✔
1691
    {
1692
        return $this->tabRatio;
443✔
1693
    }
1694

1695
    /**
1696
     * Set the ratio between the workbook tabs bar and the horizontal scroll bar
1697
     * TabRatio is assumed to be out of 1000 of the horizontal window width.
1698
     *
1699
     * @param int $tabRatio Ratio between the tabs bar and the horizontal scroll bar
1700
     */
1701
    public function setTabRatio(int $tabRatio): void
324✔
1702
    {
1703
        if ($tabRatio >= 0 && $tabRatio <= 1000) {
324✔
1704
            $this->tabRatio = (int) $tabRatio;
323✔
1705
        } else {
1706
            throw new Exception('Tab ratio must be between 0 and 1000.');
1✔
1707
        }
1708
    }
1709

1710
    public function reevaluateAutoFilters(bool $resetToMax): void
2✔
1711
    {
1712
        foreach ($this->workSheetCollection as $sheet) {
2✔
1713
            $filter = $sheet->getAutoFilter();
2✔
1714
            if (!empty($filter->getRange())) {
2✔
1715
                if ($resetToMax) {
2✔
1716
                    $filter->setRangeToMaxRow();
1✔
1717
                }
1718
                $filter->showHideRows();
2✔
1719
            }
1720
        }
1721
    }
1722

1723
    /**
1724
     * @throws Exception
1725
     */
1726
    public function jsonSerialize(): mixed
1✔
1727
    {
1728
        throw new Exception('Spreadsheet objects cannot be json encoded');
1✔
1729
    }
1730

1731
    public function resetThemeFonts(): void
1✔
1732
    {
1733
        $majorFontLatin = $this->theme->getMajorFontLatin();
1✔
1734
        $minorFontLatin = $this->theme->getMinorFontLatin();
1✔
1735
        foreach ($this->cellXfCollection as $cellStyleXf) {
1✔
1736
            $scheme = $cellStyleXf->getFont()->getScheme();
1✔
1737
            if ($scheme === 'major') {
1✔
1738
                $cellStyleXf->getFont()->setName($majorFontLatin)->setScheme($scheme);
1✔
1739
            } elseif ($scheme === 'minor') {
1✔
1740
                $cellStyleXf->getFont()->setName($minorFontLatin)->setScheme($scheme);
1✔
1741
            }
1742
        }
1743
        foreach ($this->cellStyleXfCollection as $cellStyleXf) {
1✔
1744
            $scheme = $cellStyleXf->getFont()->getScheme();
1✔
1745
            if ($scheme === 'major') {
1✔
UNCOV
1746
                $cellStyleXf->getFont()->setName($majorFontLatin)->setScheme($scheme);
×
1747
            } elseif ($scheme === 'minor') {
1✔
1748
                $cellStyleXf->getFont()->setName($minorFontLatin)->setScheme($scheme);
1✔
1749
            }
1750
        }
1751
    }
1752

1753
    public function getTableByName(string $tableName): ?Table
41✔
1754
    {
1755
        $table = null;
41✔
1756
        foreach ($this->workSheetCollection as $sheet) {
41✔
1757
            $table = $sheet->getTableByName($tableName);
41✔
1758
            if ($table !== null) {
41✔
1759
                break;
5✔
1760
            }
1761
        }
1762

1763
        return $table;
41✔
1764
    }
1765

1766
    /**
1767
     * @return bool Success or failure
1768
     */
1769
    public function setExcelCalendar(int $baseYear): bool
886✔
1770
    {
1771
        if (($baseYear === Date::CALENDAR_WINDOWS_1900) || ($baseYear === Date::CALENDAR_MAC_1904)) {
886✔
1772
            $this->excelCalendar = $baseYear;
886✔
1773

1774
            return true;
886✔
1775
        }
1776

1777
        return false;
1✔
1778
    }
1779

1780
    /**
1781
     * @return int Excel base date (1900 or 1904)
1782
     */
1783
    public function getExcelCalendar(): int
8,977✔
1784
    {
1785
        return $this->excelCalendar;
8,977✔
1786
    }
1787

1788
    public function deleteLegacyDrawing(Worksheet $worksheet): void
2✔
1789
    {
1790
        unset($this->unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing']);
2✔
1791
    }
1792

1793
    public function getLegacyDrawing(Worksheet $worksheet): ?string
3✔
1794
    {
1795
        /** @var ?string */
1796
        $temp = $this->unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing'] ?? null;
3✔
1797

1798
        return $temp;
3✔
1799
    }
1800

1801
    public function getValueBinder(): ?IValueBinder
10,699✔
1802
    {
1803
        return $this->valueBinder;
10,699✔
1804
    }
1805

1806
    public function setValueBinder(?IValueBinder $valueBinder): self
1,770✔
1807
    {
1808
        $this->valueBinder = $valueBinder;
1,770✔
1809

1810
        return $this;
1,770✔
1811
    }
1812

1813
    /**
1814
     * All the PDF writers treat charts as if they occupy a single cell.
1815
     * This will be better most of the time.
1816
     * It is not needed for any other output type.
1817
     * It changes the contents of the spreadsheet, so you might
1818
     * be better off cloning the spreadsheet and then using
1819
     * this method on, and then writing, the clone.
1820
     */
1821
    public function mergeChartCellsForPdf(): void
1✔
1822
    {
1823
        foreach ($this->workSheetCollection as $worksheet) {
1✔
1824
            foreach ($worksheet->getChartCollection() as $chart) {
1✔
1825
                $br = $chart->getBottomRightCell();
1✔
1826
                $tl = $chart->getTopLeftCell();
1✔
1827
                if ($br !== '' && $br !== $tl) {
1✔
1828
                    if (!$worksheet->cellExists($br)) {
1✔
1829
                        $worksheet->getCell($br)->setValue(' ');
1✔
1830
                    }
1831
                    $worksheet->mergeCells("$tl:$br");
1✔
1832
                }
1833
            }
1834
        }
1835
    }
1836

1837
    /**
1838
     * All the PDF writers do better with drawings than charts.
1839
     * This will be better some of the time.
1840
     * It is not needed for any other output type.
1841
     * It changes the contents of the spreadsheet, so you might
1842
     * be better off cloning the spreadsheet and then using
1843
     * this method on, and then writing, the clone.
1844
     */
1845
    public function mergeDrawingCellsForPdf(): void
1✔
1846
    {
1847
        foreach ($this->workSheetCollection as $worksheet) {
1✔
1848
            foreach ($worksheet->getDrawingCollection() as $drawing) {
1✔
1849
                $br = $drawing->getCoordinates2();
1✔
1850
                $tl = $drawing->getCoordinates();
1✔
1851
                if ($br !== '' && $br !== $tl) {
1✔
1852
                    if (!$worksheet->cellExists($br)) {
1✔
1853
                        $worksheet->getCell($br)->setValue(' ');
1✔
1854
                    }
1855
                    $worksheet->mergeCells("$tl:$br");
1✔
1856
                }
1857
            }
1858
        }
1859
    }
1860

1861
    /**
1862
     * Excel will sometimes replace user's formatting choice
1863
     * with a built-in choice that it thinks is equivalent.
1864
     * Its choice is often not equivalent after all.
1865
     * Such treatment is astonishingly user-hostile.
1866
     * This function will undo such changes.
1867
     */
1868
    public function replaceBuiltinNumberFormat(int $builtinFormatIndex, string $formatCode): void
1✔
1869
    {
1870
        foreach ($this->cellXfCollection as $style) {
1✔
1871
            $numberFormat = $style->getNumberFormat();
1✔
1872
            if ($numberFormat->getBuiltInFormatCode() === $builtinFormatIndex) {
1✔
1873
                $numberFormat->setFormatCode($formatCode);
1✔
1874
            }
1875
        }
1876
    }
1877

1878
    /**
1879
     * Change all 2-digit-year date styles to use 4-digit year;
1880
     * change all dd-mm-yyyy and mm-dd-yyyy styles to yyyy-mm-dd;
1881
     * dd-mmm-yyyy is unambiguous and left unchanged.
1882
     */
1883
    public function disambiguateDateStyles(): void
1✔
1884
    {
1885
        foreach ($this->cellXfCollection as $style) {
1✔
1886
            $numberFormat = $style->getNumberFormat();
1✔
1887
            $oldFormat = (string) $numberFormat->getFormatCode();
1✔
1888
            $newFormat = Preg::replace('/\byy\b/i', 'yyyy', $oldFormat);
1✔
1889
            $newFormat = Preg::replace(
1✔
1890
                '~\bdd?(-|/|"-"|"/")'
1✔
1891
                    . 'mm?(-|/|"-"|"/")'
1✔
1892
                    . 'yyyy~',
1✔
1893
                'yyyy-mm-dd',
1✔
1894
                $newFormat
1✔
1895
            );
1✔
1896
            $newFormat = Preg::replace(
1✔
1897
                '~\bmm?(-|/|"-"|"/")'
1✔
1898
                    . 'dd?(-|/|"-"|"/")'
1✔
1899
                    . 'yyyy~',
1✔
1900
                'yyyy-mm-dd',
1✔
1901
                $newFormat
1✔
1902
            );
1✔
1903
            if ($newFormat !== $oldFormat) {
1✔
1904
                $numberFormat->setFormatCode($newFormat);
1✔
1905
            }
1906
        }
1907
    }
1908

1909
    public function returnArrayAsArray(): void
91✔
1910
    {
1911
        $this->calculationEngine->setInstanceArrayReturnType(
91✔
1912
            Calculation::RETURN_ARRAY_AS_ARRAY
91✔
1913
        );
91✔
1914
    }
1915

1916
    public function returnArrayAsValue(): void
2✔
1917
    {
1918
        $this->calculationEngine->setInstanceArrayReturnType(
2✔
1919
            Calculation::RETURN_ARRAY_AS_VALUE
2✔
1920
        );
2✔
1921
    }
1922

1923
    /** @var string[] */
1924
    private $domainWhiteList = [];
1925

1926
    /**
1927
     * Currently used only by WEBSERVICE function.
1928
     *
1929
     * @param string[] $domainWhiteList
1930
     */
1931
    public function setDomainWhiteList(array $domainWhiteList): self
9✔
1932
    {
1933
        $this->domainWhiteList = $domainWhiteList;
9✔
1934

1935
        return $this;
9✔
1936
    }
1937

1938
    /** @return string[] */
1939
    public function getDomainWhiteList(): array
6✔
1940
    {
1941
        return $this->domainWhiteList;
6✔
1942
    }
1943

1944
    private bool $usesCheckBoxStyle = false;
1945

1946
    public function getUsesCheckBoxStyle(): bool
442✔
1947
    {
1948
        return $this->usesCheckBoxStyle;
442✔
1949
    }
1950

1951
    public function setUsesCheckBoxStyle(): bool
535✔
1952
    {
1953
        $this->usesCheckBoxStyle = false;
535✔
1954
        foreach ($this->getCellXfCollection() as $cellXf) {
535✔
1955
            if ($cellXf->getCheckBox()) {
535✔
1956
                $this->usesCheckBoxStyle = true;
2✔
1957

1958
                break;
2✔
1959
            }
1960
        }
1961

1962
        return $this->usesCheckBoxStyle;
535✔
1963
    }
1964
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc