Worksheet   F
last analyzed

Complexity

Total Complexity 347

Size/Duplication

Total Lines 1804
Duplicated Lines 0 %

Test Coverage

Coverage 98.03%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 347
eloc 997
dl 0
loc 1804
ccs 997
cts 1017
cp 0.9803
rs 1.603
c 2
b 0
f 0

47 Methods

Rating   Name   Duplication   Size   Complexity  
B writeTextCondElements() 0 17 7
A writeIgnoredErrors() 0 10 2
A writeDimension() 0 6 1
A writeAttributeIf() 0 4 2
A writeIgnoredError() 0 11 3
B writeCols() 0 55 9
F writeSheetViews() 0 153 38
C writeTimePeriodCondElements() 0 29 13
C writeSheetPr() 0 48 12
B writeSheetFormatPr() 0 42 8
A writeElementIf() 0 4 2
A writeAttributeNotNull() 0 4 2
A writeProtectionAttribute() 0 6 3
B writeOtherCondElements() 0 28 11
A writeSheetProtection() 0 35 4
B writeExtConditionalFormattingElements() 0 48 8
F writeColorScaleElements() 0 93 20
B writeDataBarElements() 0 37 7
A writeCellNumeric() 0 7 3
A writeHyperlinks() 0 32 5
A writeCellError() 0 6 2
A writeLegacyDrawing() 0 9 3
A parseRef() 0 20 3
B writeIconSetElements() 0 39 7
A writeTable() 0 17 3
B writePageSetup() 0 33 6
A writeMergeCells() 0 15 3
A writeWorksheet() 0 116 2
A writeProtectedRanges() 0 20 3
F writeSheetData() 0 112 28
F writeCell() 0 74 20
A writeLegacyDrawingHF() 0 7 2
A writePrintOptions() 0 17 4
A writeAutoFilter() 0 3 1
F writeCellFormula() 0 81 21
B writeBreaks() 0 60 11
A writeCellString() 0 7 2
A writeCellBoolean() 0 4 2
A writeBackgroundImage() 0 6 2
F writeDataValidations() 0 56 16
D writeConditionalFormatting() 0 81 21
A writeAlternateContent() 0 9 2
A writePageMargins() 0 11 1
B writeHeaderFooter() 0 28 6
B writeExtLst() 0 25 7
A writeCellInlineStr() 0 21 3
A writeDrawings() 0 24 6

How to fix   Complexity   

Complex Class

Complex classes like Worksheet often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Worksheet, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
4
5
use Composer\Pcre\Preg;
6
use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue;
7
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
8
use PhpOffice\PhpSpreadsheet\Cell\Cell;
9
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
10
use PhpOffice\PhpSpreadsheet\Cell\DataType;
11
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
12
use PhpOffice\PhpSpreadsheet\RichText\RichText;
13
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
14
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
15
use PhpOffice\PhpSpreadsheet\Style\Conditional;
16
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalColorScale;
17
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar;
18
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormattingRuleExtension;
19
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalIconSet;
20
use PhpOffice\PhpSpreadsheet\Style\Font;
21
use PhpOffice\PhpSpreadsheet\Worksheet\RowDimension;
22
use PhpOffice\PhpSpreadsheet\Worksheet\SheetView;
23
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as PhpspreadsheetWorksheet;
24
25
class Worksheet extends WriterPart
26
{
27
    private string $numberStoredAsText = '';
28
29
    private string $formula = '';
30
31
    private string $formulaRange = '';
32
33
    private string $twoDigitTextYear = '';
34
35
    private string $evalError = '';
36
37
    private bool $explicitStyle0;
38
39
    private bool $useDynamicArrays = false;
40
41
    /**
42
     * Write worksheet to XML format.
43
     *
44
     * @param string[] $stringTable
45
     * @param bool $includeCharts Flag indicating if we should write charts
46
     *
47
     * @return string XML Output
48
     */
49 464
    public function writeWorksheet(PhpspreadsheetWorksheet $worksheet, array $stringTable = [], bool $includeCharts = false): string
50
    {
51 464
        $this->useDynamicArrays = $this->getParentWriter()->useDynamicArrays();
52 464
        $this->explicitStyle0 = $this->getParentWriter()->getExplicitStyle0();
53 464
        $worksheet->calculateArrays($this->getParentWriter()->getPreCalculateFormulas());
54 464
        $this->numberStoredAsText = '';
55 464
        $this->formula = '';
56 464
        $this->formulaRange = '';
57 464
        $this->twoDigitTextYear = '';
58 464
        $this->evalError = '';
59
        // Create XML writer
60 464
        $objWriter = null;
61 464
        if ($this->getParentWriter()->getUseDiskCaching()) {
62
            $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
63
        } else {
64 464
            $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
65
        }
66
67
        // XML header
68 464
        $objWriter->startDocument('1.0', 'UTF-8', 'yes');
69
70
        // Worksheet
71 464
        $objWriter->startElement('worksheet');
72 464
        $objWriter->writeAttribute('xmlns', Namespaces::MAIN);
73 464
        $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT);
74
75 464
        $objWriter->writeAttribute('xmlns:xdr', Namespaces::SPREADSHEET_DRAWING);
76 464
        $objWriter->writeAttribute('xmlns:x14', Namespaces::DATA_VALIDATIONS1);
77 464
        $objWriter->writeAttribute('xmlns:xm', Namespaces::DATA_VALIDATIONS2);
78 464
        $objWriter->writeAttribute('xmlns:mc', Namespaces::COMPATIBILITY);
79 464
        $objWriter->writeAttribute('mc:Ignorable', 'x14ac');
80 464
        $objWriter->writeAttribute('xmlns:x14ac', Namespaces::SPREADSHEETML_AC);
81
82
        // sheetPr
83 464
        $this->writeSheetPr($objWriter, $worksheet);
84
85
        // Dimension
86 464
        $this->writeDimension($objWriter, $worksheet);
87
88
        // sheetViews
89 464
        $this->writeSheetViews($objWriter, $worksheet);
90
91
        // sheetFormatPr
92 464
        $this->writeSheetFormatPr($objWriter, $worksheet);
93
94
        // cols
95 464
        $this->writeCols($objWriter, $worksheet);
96
97
        // sheetData
98 464
        $this->writeSheetData($objWriter, $worksheet, $stringTable);
99
100
        // sheetProtection
101 463
        $this->writeSheetProtection($objWriter, $worksheet);
102
103
        // protectedRanges
104 463
        $this->writeProtectedRanges($objWriter, $worksheet);
105
106
        // autoFilter
107 463
        $this->writeAutoFilter($objWriter, $worksheet);
108
109
        // mergeCells
110 463
        $this->writeMergeCells($objWriter, $worksheet);
111
112
        // conditionalFormatting
113 463
        $this->writeConditionalFormatting($objWriter, $worksheet);
114
115
        // dataValidations
116 463
        $this->writeDataValidations($objWriter, $worksheet);
117
118
        // hyperlinks
119 463
        $this->writeHyperlinks($objWriter, $worksheet);
120
121
        // Print options
122 463
        $this->writePrintOptions($objWriter, $worksheet);
123
124
        // Page margins
125 463
        $this->writePageMargins($objWriter, $worksheet);
126
127
        // Page setup
128 463
        $this->writePageSetup($objWriter, $worksheet);
129
130
        // Header / footer
131 463
        $this->writeHeaderFooter($objWriter, $worksheet);
132
133
        // Breaks
134 463
        $this->writeBreaks($objWriter, $worksheet);
135
136
        // IgnoredErrors
137 463
        $this->writeIgnoredErrors($objWriter);
138
139
        // Drawings and/or Charts
140 463
        $this->writeDrawings($objWriter, $worksheet, $includeCharts);
141
142
        // LegacyDrawing
143 463
        $this->writeLegacyDrawing($objWriter, $worksheet);
144
145
        // LegacyDrawingHF
146 463
        $this->writeLegacyDrawingHF($objWriter, $worksheet);
147
148
        // AlternateContent
149 463
        $this->writeAlternateContent($objWriter, $worksheet);
150
151
        // BackgroundImage must come after ignored, before table
152 463
        $this->writeBackgroundImage($objWriter, $worksheet);
153
154
        // Table
155 463
        $this->writeTable($objWriter, $worksheet);
156
157
        // ConditionalFormattingRuleExtensionList
158
        // (Must be inserted last. Not insert last, an Excel parse error will occur)
159 463
        $this->writeExtLst($objWriter, $worksheet);
160
161 463
        $objWriter->endElement();
162
163
        // Return
164 463
        return $objWriter->getData();
165
    }
166
167 463
    private function writeIgnoredError(XMLWriter $objWriter, bool &$started, string $attr, string $cells): void
168
    {
169 463
        if ($cells !== '') {
170 4
            if (!$started) {
171 4
                $objWriter->startElement('ignoredErrors');
172 4
                $started = true;
173
            }
174 4
            $objWriter->startElement('ignoredError');
175 4
            $objWriter->writeAttribute('sqref', substr($cells, 1));
176 4
            $objWriter->writeAttribute($attr, '1');
177 4
            $objWriter->endElement();
178
        }
179
    }
180
181 463
    private function writeIgnoredErrors(XMLWriter $objWriter): void
182
    {
183 463
        $started = false;
184 463
        $this->writeIgnoredError($objWriter, $started, 'numberStoredAsText', $this->numberStoredAsText);
185 463
        $this->writeIgnoredError($objWriter, $started, 'formula', $this->formula);
186 463
        $this->writeIgnoredError($objWriter, $started, 'formulaRange', $this->formulaRange);
187 463
        $this->writeIgnoredError($objWriter, $started, 'twoDigitTextYear', $this->twoDigitTextYear);
188 463
        $this->writeIgnoredError($objWriter, $started, 'evalError', $this->evalError);
189 463
        if ($started) {
190 4
            $objWriter->endElement();
191
        }
192
    }
193
194
    /**
195
     * Write SheetPr.
196
     */
197 464
    private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
198
    {
199
        // sheetPr
200 464
        $objWriter->startElement('sheetPr');
201 464
        if ($worksheet->getParentOrThrow()->hasMacros()) {
202
            //if the workbook have macros, we need to have codeName for the sheet
203 2
            if (!$worksheet->hasCodeName()) {
204
                $worksheet->setCodeName($worksheet->getTitle());
205
            }
206 2
            self::writeAttributeNotNull($objWriter, 'codeName', $worksheet->getCodeName());
207
        }
208 464
        $autoFilterRange = $worksheet->getAutoFilter()->getRange();
209 464
        if (!empty($autoFilterRange)) {
210 10
            $objWriter->writeAttribute('filterMode', '1');
211 10
            if (!$worksheet->getAutoFilter()->getEvaluated()) {
212 6
                $worksheet->getAutoFilter()->showHideRows();
213
            }
214
        }
215 464
        $tables = $worksheet->getTableCollection();
216 464
        if (count($tables)) {
217 8
            foreach ($tables as $table) {
218 8
                if (!$table->getAutoFilter()->getEvaluated()) {
219 8
                    $table->getAutoFilter()->showHideRows();
220
                }
221
            }
222
        }
223
224
        // tabColor
225 464
        if ($worksheet->isTabColorSet()) {
226 8
            $objWriter->startElement('tabColor');
227 8
            $objWriter->writeAttribute('rgb', $worksheet->getTabColor()->getARGB() ?? '');
228 8
            $objWriter->endElement();
229
        }
230
231
        // outlinePr
232 464
        $objWriter->startElement('outlinePr');
233 464
        $objWriter->writeAttribute('summaryBelow', ($worksheet->getShowSummaryBelow() ? '1' : '0'));
234 464
        $objWriter->writeAttribute('summaryRight', ($worksheet->getShowSummaryRight() ? '1' : '0'));
235 464
        $objWriter->endElement();
236
237
        // pageSetUpPr
238 464
        if ($worksheet->getPageSetup()->getFitToPage()) {
239 6
            $objWriter->startElement('pageSetUpPr');
240 6
            $objWriter->writeAttribute('fitToPage', '1');
241 6
            $objWriter->endElement();
242
        }
243
244 464
        $objWriter->endElement();
245
    }
246
247
    /**
248
     * Write Dimension.
249
     */
250 464
    private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
251
    {
252
        // dimension
253 464
        $objWriter->startElement('dimension');
254 464
        $objWriter->writeAttribute('ref', $worksheet->calculateWorksheetDimension());
255 464
        $objWriter->endElement();
256
    }
257
258
    /**
259
     * Write SheetViews.
260
     */
261 464
    private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
262
    {
263
        // sheetViews
264 464
        $objWriter->startElement('sheetViews');
265
266
        // Sheet selected?
267 464
        $sheetSelected = false;
268 464
        if ($this->getParentWriter()->getSpreadsheet()->getIndex($worksheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) {
269 459
            $sheetSelected = true;
270
        }
271
272
        // sheetView
273 464
        $objWriter->startElement('sheetView');
274 464
        $objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0');
275 464
        $objWriter->writeAttribute('workbookViewId', '0');
276
277
        // Zoom scales
278 464
        $zoomScale = $worksheet->getSheetView()->getZoomScale();
279 464
        if ($zoomScale !== 100 && $zoomScale !== null) {
280 9
            $objWriter->writeAttribute('zoomScale', (string) $zoomScale);
281
        }
282 464
        $zoomScale = $worksheet->getSheetView()->getZoomScaleNormal();
283 464
        if ($zoomScale !== 100 && $zoomScale !== null) {
284 6
            $objWriter->writeAttribute('zoomScaleNormal', (string) $zoomScale);
285
        }
286 464
        $zoomScale = $worksheet->getSheetView()->getZoomScalePageLayoutView();
287 464
        if ($zoomScale !== 100) {
288 4
            $objWriter->writeAttribute('zoomScalePageLayoutView', (string) $zoomScale);
289
        }
290 464
        $zoomScale = $worksheet->getSheetView()->getZoomScaleSheetLayoutView();
291 464
        if ($zoomScale !== 100) {
292 4
            $objWriter->writeAttribute('zoomScaleSheetLayoutView', (string) $zoomScale);
293
        }
294
295
        // Show zeros (Excel also writes this attribute only if set to false)
296 464
        if ($worksheet->getSheetView()->getShowZeros() === false) {
297
            $objWriter->writeAttribute('showZeros', '0');
298
        }
299
300
        // View Layout Type
301 464
        if ($worksheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) {
302 6
            $objWriter->writeAttribute('view', $worksheet->getSheetView()->getView());
303
        }
304
305
        // Gridlines
306 464
        if ($worksheet->getShowGridlines()) {
307 460
            $objWriter->writeAttribute('showGridLines', 'true');
308
        } else {
309 9
            $objWriter->writeAttribute('showGridLines', 'false');
310
        }
311
312
        // Row and column headers
313 464
        if ($worksheet->getShowRowColHeaders()) {
314 464
            $objWriter->writeAttribute('showRowColHeaders', '1');
315
        } else {
316
            $objWriter->writeAttribute('showRowColHeaders', '0');
317
        }
318
319
        // Right-to-left
320 464
        if ($worksheet->getRightToLeft()) {
321 1
            $objWriter->writeAttribute('rightToLeft', 'true');
322
        }
323
324 464
        $topLeftCell = $worksheet->getTopLeftCell();
325 464
        if (!empty($topLeftCell) && $worksheet->getPaneState() !== PhpspreadsheetWorksheet::PANE_FROZEN && $worksheet->getPaneState() !== PhpspreadsheetWorksheet::PANE_FROZENSPLIT) {
326 12
            $objWriter->writeAttribute('topLeftCell', $topLeftCell);
327
        }
328 464
        $activeCell = $worksheet->getActiveCell();
329 464
        $sqref = $worksheet->getSelectedCells();
330
331
        // Pane
332 464
        if ($worksheet->usesPanes()) {
333 10
            $objWriter->startElement('pane');
334 10
            $xSplit = $worksheet->getXSplit();
335 10
            $ySplit = $worksheet->getYSplit();
336 10
            $pane = $worksheet->getActivePane();
337 10
            $paneTopLeftCell = $worksheet->getPaneTopLeftCell();
338 10
            $paneState = $worksheet->getPaneState();
339 10
            $normalFreeze = '';
340 10
            if ($paneState === PhpspreadsheetWorksheet::PANE_FROZEN) {
341 10
                if ($ySplit > 0) {
342 10
                    $normalFreeze = ($xSplit <= 0) ? 'bottomLeft' : 'bottomRight';
343
                } else {
344 1
                    $normalFreeze = 'topRight';
345
                }
346
            }
347 10
            if ($xSplit > 0) {
348 4
                $objWriter->writeAttribute('xSplit', "$xSplit");
349
            }
350 10
            if ($ySplit > 0) {
351 10
                $objWriter->writeAttribute('ySplit', "$ySplit");
352
            }
353 10
            if ($normalFreeze !== '') {
354 10
                $objWriter->writeAttribute('activePane', $normalFreeze);
355 1
            } elseif ($pane !== '') {
356 1
                $objWriter->writeAttribute('activePane', $pane);
357
            }
358 10
            if ($paneState !== '') {
359 10
                $objWriter->writeAttribute('state', $paneState);
360
            }
361 10
            if ($paneTopLeftCell !== '') {
362 10
                $objWriter->writeAttribute('topLeftCell', $paneTopLeftCell);
363
            }
364 10
            $objWriter->endElement(); // pane
365
366 10
            if ($normalFreeze !== '') {
367 10
                $objWriter->startElement('selection');
368 10
                $objWriter->writeAttribute('pane', $normalFreeze);
369 10
                if ($activeCell !== '') {
370 10
                    $objWriter->writeAttribute('activeCell', $activeCell);
371
                }
372 10
                if ($sqref !== '') {
373 10
                    $objWriter->writeAttribute('sqref', $sqref);
374
                }
375 10
                $objWriter->endElement(); // selection
376 10
                $sqref = $activeCell = '';
377
            } else {
378 1
                foreach ($worksheet->getPanes() as $panex) {
379 1
                    if ($panex !== null) {
380 1
                        $sqref = $activeCell = '';
381 1
                        $objWriter->startElement('selection');
382 1
                        $objWriter->writeAttribute('pane', $panex->getPosition());
383 1
                        $activeCellPane = $panex->getActiveCell();
384 1
                        if ($activeCellPane !== '') {
385 1
                            $objWriter->writeAttribute('activeCell', $activeCellPane);
386
                        }
387 1
                        $sqrefPane = $panex->getSqref();
388 1
                        if ($sqrefPane !== '') {
389 1
                            $objWriter->writeAttribute('sqref', $sqrefPane);
390
                        }
391 1
                        $objWriter->endElement(); // selection
392
                    }
393
                }
394
            }
395
        }
396
397
        // Selection
398
        // Only need to write selection element if we have a split pane
399
        // We cheat a little by over-riding the active cell selection, setting it to the split cell
400 464
        if (!empty($sqref) || !empty($activeCell)) {
401 457
            $objWriter->startElement('selection');
402 457
            if (!empty($activeCell)) {
403 457
                $objWriter->writeAttribute('activeCell', $activeCell);
404
            }
405 457
            if (!empty($sqref)) {
406 457
                $objWriter->writeAttribute('sqref', $sqref);
407
            }
408 457
            $objWriter->endElement(); // selection
409
        }
410
411 464
        $objWriter->endElement();
412
413 464
        $objWriter->endElement();
414
    }
415
416
    /**
417
     * Write SheetFormatPr.
418
     */
419 464
    private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
420
    {
421
        // sheetFormatPr
422 464
        $objWriter->startElement('sheetFormatPr');
423
424
        // Default row height
425 464
        if ($worksheet->getDefaultRowDimension()->getRowHeight() >= 0) {
426 16
            $objWriter->writeAttribute('customHeight', 'true');
427 16
            $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($worksheet->getDefaultRowDimension()->getRowHeight()));
428
        } else {
429 449
            $objWriter->writeAttribute('defaultRowHeight', '14.4');
430
        }
431
432
        // Set Zero Height row
433 464
        if ($worksheet->getDefaultRowDimension()->getZeroHeight()) {
434
            $objWriter->writeAttribute('zeroHeight', '1');
435
        }
436
437
        // Default column width
438 464
        if ($worksheet->getDefaultColumnDimension()->getWidth() >= 0) {
439 28
            $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($worksheet->getDefaultColumnDimension()->getWidth()));
440
        }
441
442
        // Outline level - row
443 464
        $outlineLevelRow = 0;
444 464
        foreach ($worksheet->getRowDimensions() as $dimension) {
445 59
            if ($dimension->getOutlineLevel() > $outlineLevelRow) {
446
                $outlineLevelRow = $dimension->getOutlineLevel();
447
            }
448
        }
449 464
        $objWriter->writeAttribute('outlineLevelRow', (string) (int) $outlineLevelRow);
450
451
        // Outline level - column
452 464
        $outlineLevelCol = 0;
453 464
        foreach ($worksheet->getColumnDimensions() as $dimension) {
454 94
            if ($dimension->getOutlineLevel() > $outlineLevelCol) {
455 1
                $outlineLevelCol = $dimension->getOutlineLevel();
456
            }
457
        }
458 464
        $objWriter->writeAttribute('outlineLevelCol', (string) (int) $outlineLevelCol);
459
460 464
        $objWriter->endElement();
461
    }
462
463
    /**
464
     * Write Cols.
465
     */
466 464
    private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
467
    {
468
        // cols
469 464
        if (count($worksheet->getColumnDimensions()) > 0) {
470 94
            $objWriter->startElement('cols');
471
472 94
            $worksheet->calculateColumnWidths();
473
474
            // Loop through column dimensions
475 94
            foreach ($worksheet->getColumnDimensions() as $colDimension) {
476
                // col
477 94
                $objWriter->startElement('col');
478 94
                $objWriter->writeAttribute('min', (string) Coordinate::columnIndexFromString($colDimension->getColumnIndex()));
479 94
                $objWriter->writeAttribute('max', (string) Coordinate::columnIndexFromString($colDimension->getColumnIndex()));
480
481 94
                if ($colDimension->getWidth() < 0) {
482
                    // No width set, apply default of 10
483 3
                    $objWriter->writeAttribute('width', '9.10');
484
                } else {
485
                    // Width set
486 93
                    $objWriter->writeAttribute('width', StringHelper::formatNumber($colDimension->getWidth()));
487
                }
488
489
                // Column visibility
490 94
                if ($colDimension->getVisible() === false) {
491 8
                    $objWriter->writeAttribute('hidden', 'true');
492
                }
493
494
                // Auto size?
495 94
                if ($colDimension->getAutoSize()) {
496 34
                    $objWriter->writeAttribute('bestFit', 'true');
497
                }
498
499
                // Custom width?
500 94
                if ($colDimension->getWidth() != $worksheet->getDefaultColumnDimension()->getWidth()) {
501 91
                    $objWriter->writeAttribute('customWidth', 'true');
502
                }
503
504
                // Collapsed
505 94
                if ($colDimension->getCollapsed() === true) {
506 1
                    $objWriter->writeAttribute('collapsed', 'true');
507
                }
508
509
                // Outline level
510 94
                if ($colDimension->getOutlineLevel() > 0) {
511 1
                    $objWriter->writeAttribute('outlineLevel', (string) $colDimension->getOutlineLevel());
512
                }
513
514
                // Style
515 94
                $objWriter->writeAttribute('style', (string) $colDimension->getXfIndex());
516
517 94
                $objWriter->endElement();
518
            }
519
520 94
            $objWriter->endElement();
521
        }
522
    }
523
524
    /**
525
     * Write SheetProtection.
526
     */
527 463
    private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
528
    {
529 463
        $protection = $worksheet->getProtection();
530 463
        if (!$protection->isProtectionEnabled()) {
531 440
            return;
532
        }
533
        // sheetProtection
534 33
        $objWriter->startElement('sheetProtection');
535
536 33
        if ($protection->getAlgorithm()) {
537 2
            $objWriter->writeAttribute('algorithmName', $protection->getAlgorithm());
538 2
            $objWriter->writeAttribute('hashValue', $protection->getPassword());
539 2
            $objWriter->writeAttribute('saltValue', $protection->getSalt());
540 2
            $objWriter->writeAttribute('spinCount', (string) $protection->getSpinCount());
541 32
        } elseif ($protection->getPassword() !== '') {
542 5
            $objWriter->writeAttribute('password', $protection->getPassword());
543
        }
544
545 33
        self::writeProtectionAttribute($objWriter, 'sheet', $protection->getSheet());
546 33
        self::writeProtectionAttribute($objWriter, 'objects', $protection->getObjects());
547 33
        self::writeProtectionAttribute($objWriter, 'scenarios', $protection->getScenarios());
548 33
        self::writeProtectionAttribute($objWriter, 'formatCells', $protection->getFormatCells());
549 33
        self::writeProtectionAttribute($objWriter, 'formatColumns', $protection->getFormatColumns());
550 33
        self::writeProtectionAttribute($objWriter, 'formatRows', $protection->getFormatRows());
551 33
        self::writeProtectionAttribute($objWriter, 'insertColumns', $protection->getInsertColumns());
552 33
        self::writeProtectionAttribute($objWriter, 'insertRows', $protection->getInsertRows());
553 33
        self::writeProtectionAttribute($objWriter, 'insertHyperlinks', $protection->getInsertHyperlinks());
554 33
        self::writeProtectionAttribute($objWriter, 'deleteColumns', $protection->getDeleteColumns());
555 33
        self::writeProtectionAttribute($objWriter, 'deleteRows', $protection->getDeleteRows());
556 33
        self::writeProtectionAttribute($objWriter, 'sort', $protection->getSort());
557 33
        self::writeProtectionAttribute($objWriter, 'autoFilter', $protection->getAutoFilter());
558 33
        self::writeProtectionAttribute($objWriter, 'pivotTables', $protection->getPivotTables());
559 33
        self::writeProtectionAttribute($objWriter, 'selectLockedCells', $protection->getSelectLockedCells());
560 33
        self::writeProtectionAttribute($objWriter, 'selectUnlockedCells', $protection->getSelectUnlockedCells());
561 33
        $objWriter->endElement();
562
    }
563
564 33
    private static function writeProtectionAttribute(XMLWriter $objWriter, string $name, ?bool $value): void
565
    {
566 33
        if ($value === true) {
567 22
            $objWriter->writeAttribute($name, '1');
568 33
        } elseif ($value === false) {
569 20
            $objWriter->writeAttribute($name, '0');
570
        }
571
    }
572
573 101
    private static function writeAttributeIf(XMLWriter $objWriter, ?bool $condition, string $attr, string $val): void
574
    {
575 101
        if ($condition) {
576 100
            $objWriter->writeAttribute($attr, $val);
577
        }
578
    }
579
580 2
    private static function writeAttributeNotNull(XMLWriter $objWriter, string $attr, ?string $val): void
581
    {
582 2
        if ($val !== null) {
583 2
            $objWriter->writeAttribute($attr, $val);
584
        }
585
    }
586
587 276
    private static function writeElementIf(XMLWriter $objWriter, bool $condition, string $attr, string $val): void
588
    {
589 276
        if ($condition) {
590 258
            $objWriter->writeElement($attr, $val);
591
        }
592
    }
593
594 44
    private static function writeOtherCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void
595
    {
596 44
        $conditions = $conditional->getConditions();
597
        if (
598 44
            $conditional->getConditionType() == Conditional::CONDITION_CELLIS
599 44
            || $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION
600 44
            || !empty($conditions)
601
        ) {
602 33
            foreach ($conditions as $formula) {
603
                // Formula
604 33
                if (is_bool($formula)) {
605 1
                    $formula = $formula ? 'TRUE' : 'FALSE';
606
                }
607 33
                $objWriter->writeElement('formula', FunctionPrefix::addFunctionPrefix("$formula"));
608
            }
609
        } else {
610 11
            if ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSBLANKS) {
611
                // formula copied from ms xlsx xml source file
612 2
                $objWriter->writeElement('formula', 'LEN(TRIM(' . $cellCoordinate . '))=0');
613 9
            } elseif ($conditional->getConditionType() == Conditional::CONDITION_NOTCONTAINSBLANKS) {
614
                // formula copied from ms xlsx xml source file
615 1
                $objWriter->writeElement('formula', 'LEN(TRIM(' . $cellCoordinate . '))>0');
616 8
            } elseif ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSERRORS) {
617
                // formula copied from ms xlsx xml source file
618 1
                $objWriter->writeElement('formula', 'ISERROR(' . $cellCoordinate . ')');
619 7
            } elseif ($conditional->getConditionType() == Conditional::CONDITION_NOTCONTAINSERRORS) {
620
                // formula copied from ms xlsx xml source file
621 1
                $objWriter->writeElement('formula', 'NOT(ISERROR(' . $cellCoordinate . '))');
622
            }
623
        }
624
    }
625
626 12
    private static function writeTimePeriodCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void
627
    {
628 12
        $txt = $conditional->getText();
629 12
        if (!empty($txt)) {
630 12
            $objWriter->writeAttribute('timePeriod', $txt);
631 12
            if (empty($conditional->getConditions())) {
632 10
                if ($conditional->getOperatorType() == Conditional::TIMEPERIOD_TODAY) {
633 1
                    $objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()');
634 9
                } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_TOMORROW) {
635 1
                    $objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()+1');
636 8
                } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_YESTERDAY) {
637 1
                    $objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()-1');
638 7
                } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_7_DAYS) {
639 1
                    $objWriter->writeElement('formula', 'AND(TODAY()-FLOOR(' . $cellCoordinate . ',1)<=6,FLOOR(' . $cellCoordinate . ',1)<=TODAY())');
640 6
                } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_WEEK) {
641 1
                    $objWriter->writeElement('formula', 'AND(TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)>=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)<(WEEKDAY(TODAY())+7))');
642 5
                } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_THIS_WEEK) {
643 1
                    $objWriter->writeElement('formula', 'AND(TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)<=WEEKDAY(TODAY())-1,ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()<=7-WEEKDAY(TODAY()))');
644 4
                } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_NEXT_WEEK) {
645 1
                    $objWriter->writeElement('formula', 'AND(ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()>(7-WEEKDAY(TODAY())),ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()<(15-WEEKDAY(TODAY())))');
646 3
                } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_MONTH) {
647 1
                    $objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(EDATE(TODAY(),0-1)),YEAR(' . $cellCoordinate . ')=YEAR(EDATE(TODAY(),0-1)))');
648 2
                } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_THIS_MONTH) {
649 1
                    $objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(TODAY()),YEAR(' . $cellCoordinate . ')=YEAR(TODAY()))');
650 1
                } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_NEXT_MONTH) {
651 1
                    $objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(EDATE(TODAY(),0+1)),YEAR(' . $cellCoordinate . ')=YEAR(EDATE(TODAY(),0+1)))');
652
                }
653
            } else {
654 2
                $objWriter->writeElement('formula', (string) ($conditional->getConditions()[0]));
655
            }
656
        }
657
    }
658
659 9
    private static function writeTextCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void
660
    {
661 9
        $txt = $conditional->getText();
662 9
        if (!empty($txt)) {
663 8
            $objWriter->writeAttribute('text', $txt);
664 8
            if (empty($conditional->getConditions())) {
665 5
                if ($conditional->getOperatorType() == Conditional::OPERATOR_CONTAINSTEXT) {
666 2
                    $objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $txt . '",' . $cellCoordinate . ')))');
667 4
                } elseif ($conditional->getOperatorType() == Conditional::OPERATOR_BEGINSWITH) {
668 2
                    $objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',LEN("' . $txt . '"))="' . $txt . '"');
669 3
                } elseif ($conditional->getOperatorType() == Conditional::OPERATOR_ENDSWITH) {
670 2
                    $objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',LEN("' . $txt . '"))="' . $txt . '"');
671 2
                } elseif ($conditional->getOperatorType() == Conditional::OPERATOR_NOTCONTAINS) {
672 2
                    $objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $txt . '",' . $cellCoordinate . '))');
673
                }
674
            } else {
675 3
                $objWriter->writeElement('formula', (string) ($conditional->getConditions()[0]));
676
            }
677
        }
678
    }
679
680 1
    private static function writeExtConditionalFormattingElements(XMLWriter $objWriter, ConditionalFormattingRuleExtension $ruleExtension): void
681
    {
682 1
        $prefix = 'x14';
683 1
        $objWriter->startElementNs($prefix, 'conditionalFormatting', null);
684
685 1
        $objWriter->startElementNs($prefix, 'cfRule', null);
686 1
        $objWriter->writeAttribute('type', $ruleExtension->getCfRule());
687 1
        $objWriter->writeAttribute('id', $ruleExtension->getId());
688 1
        $objWriter->startElementNs($prefix, 'dataBar', null);
689 1
        $dataBar = $ruleExtension->getDataBarExt();
690 1
        foreach ($dataBar->getXmlAttributes() as $attrKey => $val) {
691
            /** @var string $val */
692 1
            $objWriter->writeAttribute($attrKey, $val);
693
        }
694 1
        $minCfvo = $dataBar->getMinimumConditionalFormatValueObject();
695
        // Phpstan is wrong about the next statement.
696 1
        if ($minCfvo !== null) { // @phpstan-ignore-line
697 1
            $objWriter->startElementNs($prefix, 'cfvo', null);
698 1
            $objWriter->writeAttribute('type', $minCfvo->getType());
699 1
            if ($minCfvo->getCellFormula()) {
700 1
                $objWriter->writeElement('xm:f', $minCfvo->getCellFormula());
701
            }
702 1
            $objWriter->endElement(); //end cfvo
703
        }
704
705 1
        $maxCfvo = $dataBar->getMaximumConditionalFormatValueObject();
706
        // Phpstan is wrong about the next statement.
707 1
        if ($maxCfvo !== null) { // @phpstan-ignore-line
708 1
            $objWriter->startElementNs($prefix, 'cfvo', null);
709 1
            $objWriter->writeAttribute('type', $maxCfvo->getType());
710 1
            if ($maxCfvo->getCellFormula()) {
711 1
                $objWriter->writeElement('xm:f', $maxCfvo->getCellFormula());
712
            }
713 1
            $objWriter->endElement(); //end cfvo
714
        }
715
716 1
        foreach ($dataBar->getXmlElements() as $elmKey => $elmAttr) {
717
            /** @var string[] $elmAttr */
718 1
            $objWriter->startElementNs($prefix, $elmKey, null);
719 1
            foreach ($elmAttr as $attrKey => $attrVal) {
720 1
                $objWriter->writeAttribute($attrKey, $attrVal);
721
            }
722 1
            $objWriter->endElement(); //end elmKey
723
        }
724 1
        $objWriter->endElement(); //end dataBar
725 1
        $objWriter->endElement(); //end cfRule
726 1
        $objWriter->writeElement('xm:sqref', $ruleExtension->getSqref());
727 1
        $objWriter->endElement(); //end conditionalFormatting
728
    }
729
730 92
    private static function writeDataBarElements(XMLWriter $objWriter, ?ConditionalDataBar $dataBar): void
731
    {
732 92
        if ($dataBar) {
733 2
            $objWriter->startElement('dataBar');
734 2
            self::writeAttributeIf($objWriter, null !== $dataBar->getShowValue(), 'showValue', $dataBar->getShowValue() ? '1' : '0');
735
736 2
            $minCfvo = $dataBar->getMinimumConditionalFormatValueObject();
737 2
            if ($minCfvo) {
738 2
                $objWriter->startElement('cfvo');
739 2
                $objWriter->writeAttribute('type', $minCfvo->getType());
740 2
                self::writeAttributeIf($objWriter, $minCfvo->getValue() !== null, 'val', (string) $minCfvo->getValue());
741 2
                $objWriter->endElement();
742
            }
743 2
            $maxCfvo = $dataBar->getMaximumConditionalFormatValueObject();
744 2
            if ($maxCfvo) {
745 2
                $objWriter->startElement('cfvo');
746 2
                $objWriter->writeAttribute('type', $maxCfvo->getType());
747 2
                self::writeAttributeIf($objWriter, $maxCfvo->getValue() !== null, 'val', (string) $maxCfvo->getValue());
748 2
                $objWriter->endElement();
749
            }
750 2
            if ($dataBar->getColor()) {
751 2
                $objWriter->startElement('color');
752 2
                $objWriter->writeAttribute('rgb', $dataBar->getColor());
753 2
                $objWriter->endElement();
754
            }
755 2
            $objWriter->endElement(); // end dataBar
756
757 2
            if ($dataBar->getConditionalFormattingRuleExt()) {
758 1
                $objWriter->startElement('extLst');
759 1
                $extension = $dataBar->getConditionalFormattingRuleExt();
760 1
                $objWriter->startElement('ext');
761 1
                $objWriter->writeAttribute('uri', '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}');
762 1
                $objWriter->startElementNs('x14', 'id', null);
763 1
                $objWriter->text($extension->getId());
764 1
                $objWriter->endElement();
765 1
                $objWriter->endElement();
766 1
                $objWriter->endElement(); //end extLst
767
            }
768
        }
769
    }
770
771 3
    private static function writeColorScaleElements(XMLWriter $objWriter, ?ConditionalColorScale $colorScale): void
772
    {
773 3
        if ($colorScale) {
774 3
            $objWriter->startElement('colorScale');
775
776 3
            $minCfvo = $colorScale->getMinimumConditionalFormatValueObject();
777 3
            $minArgb = $colorScale->getMinimumColor()?->getARGB();
778 3
            $useMin = $minCfvo !== null || $minArgb !== null;
779 3
            if ($useMin) {
780 3
                $objWriter->startElement('cfvo');
781 3
                $type = 'min';
782 3
                $value = null;
783 3
                if ($minCfvo !== null) {
784 3
                    $typex = $minCfvo->getType();
785 3
                    if ($typex === 'formula') {
786 1
                        $value = $minCfvo->getCellFormula();
787 1
                        if ($value !== null) {
788 1
                            $type = $typex;
789
                        }
790
                    } else {
791 2
                        $type = $typex;
792 2
                        $defaults = ['number' => '0', 'percent' => '0', 'percentile' => '10'];
793 2
                        $value = $minCfvo->getValue() ?? $defaults[$type] ?? null;
794
                    }
795
                }
796 3
                $objWriter->writeAttribute('type', $type);
797 3
                self::writeAttributeIf($objWriter, $value !== null, 'val', (string) $value);
798 3
                $objWriter->endElement();
799
            }
800 3
            $midCfvo = $colorScale->getMidpointConditionalFormatValueObject();
801 3
            $midArgb = $colorScale->getMidpointColor()?->getARGB();
802 3
            $useMid = $midCfvo !== null || $midArgb !== null;
803 3
            if ($useMid) {
804 2
                $objWriter->startElement('cfvo');
805 2
                $type = 'percentile';
806 2
                $value = '50';
807 2
                if ($midCfvo !== null) {
808 2
                    $type = $midCfvo->getType();
809 2
                    if ($type === 'formula') {
810
                        $value = $midCfvo->getCellFormula();
811
                        if ($value === null) {
812
                            $type = 'percentile';
813
                            $value = '50';
814
                        }
815
                    } else {
816 2
                        $defaults = ['number' => '0', 'percent' => '50', 'percentile' => '50'];
817 2
                        $value = $midCfvo->getValue() ?? $defaults[$type] ?? null;
818
                    }
819
                }
820 2
                $objWriter->writeAttribute('type', $type);
821 2
                self::writeAttributeIf($objWriter, $value !== null, 'val', (string) $value);
822 2
                $objWriter->endElement();
823
            }
824 3
            $maxCfvo = $colorScale->getMaximumConditionalFormatValueObject();
825 3
            $maxArgb = $colorScale->getMaximumColor()?->getARGB();
826 3
            $useMax = $maxCfvo !== null || $maxArgb !== null;
827 3
            if ($useMax) {
828 3
                $objWriter->startElement('cfvo');
829 3
                $type = 'max';
830 3
                $value = null;
831 3
                if ($maxCfvo !== null) {
832 3
                    $typex = $maxCfvo->getType();
833 3
                    if ($typex === 'formula') {
834
                        $value = $maxCfvo->getCellFormula();
835
                        if ($value !== null) {
836
                            $type = $typex;
837
                        }
838
                    } else {
839 3
                        $type = $typex;
840 3
                        $defaults = ['number' => '0', 'percent' => '100', 'percentile' => '90'];
841 3
                        $value = $maxCfvo->getValue() ?? $defaults[$type] ?? null;
842
                    }
843
                }
844 3
                $objWriter->writeAttribute('type', $type);
845 3
                self::writeAttributeIf($objWriter, $value !== null, 'val', (string) $value);
846 3
                $objWriter->endElement();
847
            }
848 3
            if ($useMin) {
849 3
                $objWriter->startElement('color');
850 3
                self::writeAttributeIf($objWriter, $minArgb !== null, 'rgb', "$minArgb");
851 3
                $objWriter->endElement();
852
            }
853 3
            if ($useMid) {
854 2
                $objWriter->startElement('color');
855 2
                self::writeAttributeIf($objWriter, $midArgb !== null, 'rgb', "$midArgb");
856 2
                $objWriter->endElement();
857
            }
858 3
            if ($useMax) {
859 3
                $objWriter->startElement('color');
860 3
                self::writeAttributeIf($objWriter, $maxArgb !== null, 'rgb', "$maxArgb");
861 3
                $objWriter->endElement();
862
            }
863 3
            $objWriter->endElement(); // end colorScale
864
        }
865
    }
866
867 26
    private function writeIconSetElements(XMLWriter $objWriter, ?ConditionalIconSet $iconSet): void
868
    {
869 26
        if ($iconSet === null) {
870 1
            return;
871
        }
872
873 26
        $objWriter->startElement('iconSet');
874 26
        if ($iconSet->getIconSetType() !== null) {
875 19
            $objWriter->writeAttribute('iconSet', $iconSet->getIconSetType()->value);
876
        }
877
        foreach (
878 26
            [
879 26
                'reverse' => $iconSet->getReverse(),
880 26
                'showValue' => $iconSet->getShowValue(),
881 26
                'custom' => $iconSet->getCustom(),
882 26
            ] as $attr => $value
883
        ) {
884 26
            self::writeAttributeIf($objWriter, $value !== null, $attr, $value ? '1' : '0');
885
        }
886
887 26
        foreach ($iconSet->getCfvos() as $cfvo) {
888 26
            $objWriter->startElement('cfvo');
889 26
            $objWriter->writeAttribute('type', $cfvo->getType());
890 26
            self::writeAttributeIf(
891 26
                $objWriter,
892 26
                $cfvo->getValue() !== null,
893 26
                'val',
894 26
                (string) $cfvo->getValue(),
895 26
            );
896 26
            self::writeAttributeIf(
897 26
                $objWriter,
898 26
                $cfvo->getGreaterThanOrEqual() !== null,
899 26
                'gte',
900 26
                $cfvo->getGreaterThanOrEqual() ? '1' : '0',
901 26
            );
902 26
            $objWriter->endElement(); // end cfvo
903
        }
904
905 26
        $objWriter->endElement(); // end iconSet
906
    }
907
908
    /**
909
     * Write ConditionalFormatting.
910
     */
911 463
    private function writeConditionalFormatting(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
912
    {
913
        // Conditional id
914 463
        $id = 0;
915 463
        foreach ($worksheet->getConditionalStylesCollection() as $conditionalStyles) {
916 92
            foreach ($conditionalStyles as $conditional) {
917 92
                $id = max($id, $conditional->getPriority());
918
            }
919
        }
920
921
        // Loop through styles in the current worksheet
922 463
        foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
923 92
            $objWriter->startElement('conditionalFormatting');
924
            // N.B. In Excel UI, intersection is space and union is comma.
925
            // But in Xml, intersection is comma and union is space.
926
            // Anyhow, I don't think Excel handles intersection correctly when reading.
927 92
            $outCoordinate = Coordinate::resolveUnionAndIntersection(str_replace('$', '', $cellCoordinate), ' ');
928 92
            $objWriter->writeAttribute('sqref', $outCoordinate);
929
930 92
            foreach ($conditionalStyles as $conditional) {
931
                // WHY was this again?
932
                // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) == '') {
933
                //    continue;
934
                // }
935
                // cfRule
936 92
                $objWriter->startElement('cfRule');
937 92
                $objWriter->writeAttribute('type', $conditional->getConditionType());
938 92
                self::writeAttributeIf(
939 92
                    $objWriter,
940 92
                    ($conditional->getConditionType() !== Conditional::CONDITION_COLORSCALE
941 92
                        && $conditional->getConditionType() !== Conditional::CONDITION_DATABAR
942 92
                        && $conditional->getConditionType() !== Conditional::CONDITION_ICONSET
943 92
                        && $conditional->getNoFormatSet() === false),
944 92
                    'dxfId',
945 92
                    (string) $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode())
946 92
                );
947 92
                $priority = $conditional->getPriority() ?: ++$id;
948 92
                $objWriter->writeAttribute('priority', (string) $priority);
949
950 92
                self::writeAttributeif(
951 92
                    $objWriter,
952 92
                    (
953 92
                        $conditional->getConditionType() === Conditional::CONDITION_CELLIS
954 92
                        || $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT
955 92
                        || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT
956 92
                        || $conditional->getConditionType() === Conditional::CONDITION_BEGINSWITH
957 92
                        || $conditional->getConditionType() === Conditional::CONDITION_ENDSWITH
958 92
                    ) && $conditional->getOperatorType() !== Conditional::OPERATOR_NONE,
959 92
                    'operator',
960 92
                    $conditional->getOperatorType()
961 92
                );
962
963 92
                self::writeAttributeIf($objWriter, $conditional->getStopIfTrue(), 'stopIfTrue', '1');
964
965 92
                $cellRange = Coordinate::splitRange(str_replace('$', '', strtoupper($cellCoordinate)));
966 92
                [$topLeftCell] = $cellRange[0];
967
968
                if (
969 92
                    $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT
970 92
                    || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT
971 92
                    || $conditional->getConditionType() === Conditional::CONDITION_BEGINSWITH
972 92
                    || $conditional->getConditionType() === Conditional::CONDITION_ENDSWITH
973
                ) {
974 9
                    self::writeTextCondElements($objWriter, $conditional, $topLeftCell);
975 85
                } elseif ($conditional->getConditionType() === Conditional::CONDITION_TIMEPERIOD) {
976 12
                    self::writeTimePeriodCondElements($objWriter, $conditional, $topLeftCell);
977 73
                } elseif ($conditional->getConditionType() === Conditional::CONDITION_COLORSCALE) {
978 3
                    self::writeColorScaleElements($objWriter, $conditional->getColorScale());
979 70
                } elseif ($conditional->getConditionType() === Conditional::CONDITION_ICONSET) {
980 26
                    self::writeIconSetElements($objWriter, $conditional->getIconSet());
981
                } else {
982 44
                    self::writeOtherCondElements($objWriter, $conditional, $topLeftCell);
983
                }
984
985
                //<dataBar>
986 92
                self::writeDataBarElements($objWriter, $conditional->getDataBar());
987
988 92
                $objWriter->endElement(); //end cfRule
989
            }
990
991 92
            $objWriter->endElement(); //end conditionalFormatting
992
        }
993
    }
994
995
    /**
996
     * Write DataValidations.
997
     */
998 463
    private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
999
    {
1000
        // Datavalidation collection
1001 463
        $dataValidationCollection = $worksheet->getDataValidationCollection();
1002
1003
        // Write data validations?
1004 463
        if (!empty($dataValidationCollection)) {
1005 16
            $objWriter->startElement('dataValidations');
1006 16
            $objWriter->writeAttribute('count', (string) count($dataValidationCollection));
1007
1008 16
            foreach ($dataValidationCollection as $coordinate => $dv) {
1009 16
                $objWriter->startElement('dataValidation');
1010
1011 16
                if ($dv->getType() != '') {
1012 16
                    $objWriter->writeAttribute('type', $dv->getType());
1013
                }
1014
1015 16
                if ($dv->getErrorStyle() != '') {
1016 9
                    $objWriter->writeAttribute('errorStyle', $dv->getErrorStyle());
1017
                }
1018
1019 16
                if ($dv->getOperator() != '') {
1020 16
                    $objWriter->writeAttribute('operator', $dv->getOperator());
1021
                }
1022
1023 16
                $objWriter->writeAttribute('allowBlank', ($dv->getAllowBlank() ? '1' : '0'));
1024 16
                $objWriter->writeAttribute('showDropDown', (!$dv->getShowDropDown() ? '1' : '0'));
1025 16
                $objWriter->writeAttribute('showInputMessage', ($dv->getShowInputMessage() ? '1' : '0'));
1026 16
                $objWriter->writeAttribute('showErrorMessage', ($dv->getShowErrorMessage() ? '1' : '0'));
1027
1028 16
                if ($dv->getErrorTitle() !== '') {
1029 7
                    $objWriter->writeAttribute('errorTitle', $dv->getErrorTitle());
1030
                }
1031 16
                if ($dv->getError() !== '') {
1032 9
                    $objWriter->writeAttribute('error', $dv->getError());
1033
                }
1034 16
                if ($dv->getPromptTitle() !== '') {
1035 6
                    $objWriter->writeAttribute('promptTitle', $dv->getPromptTitle());
1036
                }
1037 16
                if ($dv->getPrompt() !== '') {
1038 5
                    $objWriter->writeAttribute('prompt', $dv->getPrompt());
1039
                }
1040
1041 16
                $objWriter->writeAttribute('sqref', $dv->getSqref() ?? $coordinate);
1042
1043 16
                if ($dv->getFormula1() !== '') {
1044 16
                    $objWriter->writeElement('formula1', FunctionPrefix::addFunctionPrefix($dv->getFormula1()));
1045
                }
1046 16
                if ($dv->getFormula2() !== '') {
1047 3
                    $objWriter->writeElement('formula2', FunctionPrefix::addFunctionPrefix($dv->getFormula2()));
1048
                }
1049
1050 16
                $objWriter->endElement();
1051
            }
1052
1053 16
            $objWriter->endElement();
1054
        }
1055
    }
1056
1057
    /**
1058
     * Write Hyperlinks.
1059
     */
1060 463
    private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1061
    {
1062
        // Hyperlink collection
1063 463
        $hyperlinkCollection = $worksheet->getHyperlinkCollection();
1064
1065
        // Relation ID
1066 463
        $relationId = 1;
1067
1068
        // Write hyperlinks?
1069 463
        if (!empty($hyperlinkCollection)) {
1070 16
            $objWriter->startElement('hyperlinks');
1071
1072 16
            foreach ($hyperlinkCollection as $coordinate => $hyperlink) {
1073 16
                $objWriter->startElement('hyperlink');
1074
1075 16
                $objWriter->writeAttribute('ref', $coordinate);
1076 16
                if (!$hyperlink->isInternal()) {
1077 16
                    $objWriter->writeAttribute('r:id', 'rId_hyperlink_' . $relationId);
1078 16
                    ++$relationId;
1079
                } else {
1080 10
                    $objWriter->writeAttribute('location', str_replace('sheet://', '', $hyperlink->getUrl()));
1081
                }
1082
1083 16
                if ($hyperlink->getTooltip() !== '') {
1084 10
                    $objWriter->writeAttribute('tooltip', $hyperlink->getTooltip());
1085 10
                    $objWriter->writeAttribute('display', $hyperlink->getTooltip());
1086
                }
1087
1088 16
                $objWriter->endElement();
1089
            }
1090
1091 16
            $objWriter->endElement();
1092
        }
1093
    }
1094
1095
    /**
1096
     * Write ProtectedRanges.
1097
     */
1098 463
    private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1099
    {
1100 463
        if (count($worksheet->getProtectedCellRanges()) > 0) {
1101
            // protectedRanges
1102 9
            $objWriter->startElement('protectedRanges');
1103
1104
            // Loop protectedRanges
1105 9
            foreach ($worksheet->getProtectedCellRanges() as $protectedCell => $protectedRange) {
1106
                // protectedRange
1107 9
                $objWriter->startElement('protectedRange');
1108 9
                $objWriter->writeAttribute('name', $protectedRange->getName());
1109 9
                $objWriter->writeAttribute('sqref', $protectedCell);
1110 9
                $passwordHash = $protectedRange->getPassword();
1111 9
                $this->writeAttributeIf($objWriter, $passwordHash !== '', 'password', $passwordHash);
1112 9
                $securityDescriptor = $protectedRange->getSecurityDescriptor();
1113 9
                $this->writeAttributeIf($objWriter, $securityDescriptor !== '', 'securityDescriptor', $securityDescriptor);
1114 9
                $objWriter->endElement();
1115
            }
1116
1117 9
            $objWriter->endElement();
1118
        }
1119
    }
1120
1121
    /**
1122
     * Write MergeCells.
1123
     */
1124 463
    private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1125
    {
1126 463
        if (count($worksheet->getMergeCells()) > 0) {
1127
            // mergeCells
1128 38
            $objWriter->startElement('mergeCells');
1129
1130
            // Loop mergeCells
1131 38
            foreach ($worksheet->getMergeCells() as $mergeCell) {
1132
                // mergeCell
1133 38
                $objWriter->startElement('mergeCell');
1134 38
                $objWriter->writeAttribute('ref', $mergeCell);
1135 38
                $objWriter->endElement();
1136
            }
1137
1138 38
            $objWriter->endElement();
1139
        }
1140
    }
1141
1142
    /**
1143
     * Write PrintOptions.
1144
     */
1145 463
    private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1146
    {
1147
        // printOptions
1148 463
        $objWriter->startElement('printOptions');
1149
1150 463
        $objWriter->writeAttribute('gridLines', ($worksheet->getPrintGridlines() ? 'true' : 'false'));
1151 463
        $objWriter->writeAttribute('gridLinesSet', 'true');
1152
1153 463
        if ($worksheet->getPageSetup()->getHorizontalCentered()) {
1154 4
            $objWriter->writeAttribute('horizontalCentered', 'true');
1155
        }
1156
1157 463
        if ($worksheet->getPageSetup()->getVerticalCentered()) {
1158 2
            $objWriter->writeAttribute('verticalCentered', 'true');
1159
        }
1160
1161 463
        $objWriter->endElement();
1162
    }
1163
1164
    /**
1165
     * Write PageMargins.
1166
     */
1167 463
    private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1168
    {
1169
        // pageMargins
1170 463
        $objWriter->startElement('pageMargins');
1171 463
        $objWriter->writeAttribute('left', StringHelper::formatNumber($worksheet->getPageMargins()->getLeft()));
1172 463
        $objWriter->writeAttribute('right', StringHelper::formatNumber($worksheet->getPageMargins()->getRight()));
1173 463
        $objWriter->writeAttribute('top', StringHelper::formatNumber($worksheet->getPageMargins()->getTop()));
1174 463
        $objWriter->writeAttribute('bottom', StringHelper::formatNumber($worksheet->getPageMargins()->getBottom()));
1175 463
        $objWriter->writeAttribute('header', StringHelper::formatNumber($worksheet->getPageMargins()->getHeader()));
1176 463
        $objWriter->writeAttribute('footer', StringHelper::formatNumber($worksheet->getPageMargins()->getFooter()));
1177 463
        $objWriter->endElement();
1178
    }
1179
1180
    /**
1181
     * Write AutoFilter.
1182
     */
1183 463
    private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1184
    {
1185 463
        AutoFilter::writeAutoFilter($objWriter, $worksheet);
1186
    }
1187
1188
    /**
1189
     * Write Table.
1190
     */
1191 463
    private function writeTable(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1192
    {
1193 463
        $tableCount = $worksheet->getTableCollection()->count();
1194 463
        if ($tableCount === 0) {
1195 456
            return;
1196
        }
1197
1198 8
        $objWriter->startElement('tableParts');
1199 8
        $objWriter->writeAttribute('count', (string) $tableCount);
1200
1201 8
        for ($t = 1; $t <= $tableCount; ++$t) {
1202 8
            $objWriter->startElement('tablePart');
1203 8
            $objWriter->writeAttribute('r:id', 'rId_table_' . $t);
1204 8
            $objWriter->endElement();
1205
        }
1206
1207 8
        $objWriter->endElement();
1208
    }
1209
1210
    /**
1211
     * Write Background Image.
1212
     */
1213 463
    private function writeBackgroundImage(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1214
    {
1215 463
        if ($worksheet->getBackgroundImage() !== '') {
1216 2
            $objWriter->startElement('picture');
1217 2
            $objWriter->writeAttribute('r:id', 'rIdBg');
1218 2
            $objWriter->endElement();
1219
        }
1220
    }
1221
1222
    /**
1223
     * Write PageSetup.
1224
     */
1225 463
    private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1226
    {
1227
        // pageSetup
1228 463
        $objWriter->startElement('pageSetup');
1229 463
        $objWriter->writeAttribute('paperSize', (string) $worksheet->getPageSetup()->getPaperSize());
1230 463
        $objWriter->writeAttribute('orientation', $worksheet->getPageSetup()->getOrientation());
1231
1232 463
        if ($worksheet->getPageSetup()->getScale() !== null) {
1233 463
            $objWriter->writeAttribute('scale', (string) $worksheet->getPageSetup()->getScale());
1234
        }
1235 463
        if ($worksheet->getPageSetup()->getFitToHeight() !== null) {
1236 463
            $objWriter->writeAttribute('fitToHeight', (string) $worksheet->getPageSetup()->getFitToHeight());
1237
        } else {
1238
            $objWriter->writeAttribute('fitToHeight', '0');
1239
        }
1240 463
        if ($worksheet->getPageSetup()->getFitToWidth() !== null) {
1241 463
            $objWriter->writeAttribute('fitToWidth', (string) $worksheet->getPageSetup()->getFitToWidth());
1242
        } else {
1243
            $objWriter->writeAttribute('fitToWidth', '0');
1244
        }
1245 463
        if (!empty($worksheet->getPageSetup()->getFirstPageNumber())) {
1246 1
            $objWriter->writeAttribute('firstPageNumber', (string) $worksheet->getPageSetup()->getFirstPageNumber());
1247 1
            $objWriter->writeAttribute('useFirstPageNumber', '1');
1248
        }
1249 463
        $objWriter->writeAttribute('pageOrder', $worksheet->getPageSetup()->getPageOrder());
1250
1251
        /** @var string[][][] */
1252 463
        $getUnparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData();
1253 463
        if (isset($getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'])) {
1254 37
            $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId']);
1255
        }
1256
1257 463
        $objWriter->endElement();
1258
    }
1259
1260
    /**
1261
     * Write Header / Footer.
1262
     */
1263 463
    private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1264
    {
1265
        // headerFooter
1266 463
        $headerFooter = $worksheet->getHeaderFooter();
1267 463
        $oddHeader = $headerFooter->getOddHeader();
1268 463
        $oddFooter = $headerFooter->getOddFooter();
1269 463
        $evenHeader = $headerFooter->getEvenHeader();
1270 463
        $evenFooter = $headerFooter->getEvenFooter();
1271 463
        $firstHeader = $headerFooter->getFirstHeader();
1272 463
        $firstFooter = $headerFooter->getFirstFooter();
1273 463
        if ("$oddHeader$oddFooter$evenHeader$evenFooter$firstHeader$firstFooter" === '') {
1274 452
            return;
1275
        }
1276
1277 21
        $objWriter->startElement('headerFooter');
1278 21
        $objWriter->writeAttribute('differentOddEven', ($worksheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false'));
1279 21
        $objWriter->writeAttribute('differentFirst', ($worksheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false'));
1280 21
        $objWriter->writeAttribute('scaleWithDoc', ($worksheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false'));
1281 21
        $objWriter->writeAttribute('alignWithMargins', ($worksheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false'));
1282
1283 21
        self::writeElementIf($objWriter, $oddHeader !== '', 'oddHeader', $oddHeader);
1284 21
        self::writeElementIf($objWriter, $oddFooter !== '', 'oddFooter', $oddFooter);
1285 21
        self::writeElementIf($objWriter, $evenHeader !== '', 'evenHeader', $evenHeader);
1286 21
        self::writeElementIf($objWriter, $evenFooter !== '', 'evenFooter', $evenFooter);
1287 21
        self::writeElementIf($objWriter, $firstHeader !== '', 'firstHeader', $firstHeader);
1288 21
        self::writeElementIf($objWriter, $firstFooter !== '', 'firstFooter', $firstFooter);
1289
1290 21
        $objWriter->endElement(); // headerFooter
1291
    }
1292
1293
    /**
1294
     * Write Breaks.
1295
     */
1296 463
    private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1297
    {
1298
        // Get row and column breaks
1299 463
        $aRowBreaks = [];
1300 463
        $aColumnBreaks = [];
1301 463
        foreach ($worksheet->getRowBreaks() as $cell => $break) {
1302 9
            $aRowBreaks[$cell] = $break;
1303
        }
1304 463
        foreach ($worksheet->getColumnBreaks() as $cell => $break) {
1305 3
            $aColumnBreaks[$cell] = $break;
1306
        }
1307
1308
        // rowBreaks
1309 463
        if (!empty($aRowBreaks)) {
1310 9
            $objWriter->startElement('rowBreaks');
1311 9
            $objWriter->writeAttribute('count', (string) count($aRowBreaks));
1312 9
            $objWriter->writeAttribute('manualBreakCount', (string) count($aRowBreaks));
1313
1314 9
            foreach ($aRowBreaks as $cell => $break) {
1315 9
                $coords = Coordinate::coordinateFromString($cell);
1316
1317 9
                $objWriter->startElement('brk');
1318 9
                $objWriter->writeAttribute('id', $coords[1]);
1319 9
                $objWriter->writeAttribute('man', '1');
1320 9
                $rowBreakMax = $break->getMaxColOrRow();
1321 9
                if ($rowBreakMax >= 0) {
1322 1
                    $objWriter->writeAttribute('max', "$rowBreakMax");
1323 8
                } elseif ($worksheet->getPageSetup()->getPrintArea() !== '') {
1324 5
                    $maxCol = Coordinate::columnIndexFromString($worksheet->getHighestColumn());
1325 5
                    $objWriter->writeAttribute('max', "$maxCol");
1326
                }
1327 9
                $objWriter->endElement();
1328
            }
1329
1330 9
            $objWriter->endElement();
1331
        }
1332
1333
        // Second, write column breaks
1334 463
        if (!empty($aColumnBreaks)) {
1335 3
            $objWriter->startElement('colBreaks');
1336 3
            $objWriter->writeAttribute('count', (string) count($aColumnBreaks));
1337 3
            $objWriter->writeAttribute('manualBreakCount', (string) count($aColumnBreaks));
1338
1339 3
            foreach ($aColumnBreaks as $cell => $break) {
1340 3
                $coords = Coordinate::indexesFromString($cell);
1341
1342 3
                $objWriter->startElement('brk');
1343 3
                $objWriter->writeAttribute('id', (string) ((int) $coords[0] - 1));
1344 3
                $objWriter->writeAttribute('man', '1');
1345 3
                $colBreakMax = $break->getMaxColOrRow();
1346 3
                if ($colBreakMax >= 0) {
1347
                    $objWriter->writeAttribute('max', "$colBreakMax");
1348 3
                } elseif ($worksheet->getPageSetup()->getPrintArea() !== '') {
1349 1
                    $maxRow = $worksheet->getHighestRow();
1350 1
                    $objWriter->writeAttribute('max', "$maxRow");
1351
                }
1352 3
                $objWriter->endElement();
1353
            }
1354
1355 3
            $objWriter->endElement();
1356
        }
1357
    }
1358
1359
    /**
1360
     * Write SheetData.
1361
     *
1362
     * @param string[] $stringTable String table
1363
     */
1364 464
    private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, array $stringTable): void
1365
    {
1366
        // Flipped stringtable, for faster index searching
1367 464
        $aFlippedStringTable = $this->getParentWriter()->getWriterPartstringtable()->flipStringTable($stringTable);
1368
1369
        // sheetData
1370 464
        $objWriter->startElement('sheetData');
1371
1372
        // Get column count
1373 464
        $colCount = Coordinate::columnIndexFromString($worksheet->getHighestColumn());
1374
1375
        // Highest row number
1376 464
        $highestRow = $worksheet->getHighestRow();
1377
1378
        // Loop through cells building a comma-separated list of the columns in each row
1379
        // This is a trade-off between the memory usage that is required for a full array of columns,
1380
        //      and execution speed
1381
        /** @var array<int, string> $cellsByRow */
1382 464
        $cellsByRow = [];
1383 464
        foreach ($worksheet->getCoordinates() as $coordinate) {
1384 384
            [$column, $row] = Coordinate::coordinateFromString($coordinate);
1385 384
            if (!isset($cellsByRow[$row])) {
1386 384
                $pCell = $worksheet->getCell("$column$row");
1387 384
                $xfi = $pCell->getXfIndex();
1388 384
                $cellValue = $pCell->getValue();
1389 384
                $writeValue = $cellValue !== '' && $cellValue !== null;
1390 384
                if (!empty($xfi) || $writeValue) {
1391 367
                    $cellsByRow[$row] = "{$column},";
1392
                }
1393
            } else {
1394 234
                $cellsByRow[$row] .= "{$column},";
1395
            }
1396
        }
1397
1398 464
        $currentRow = 0;
1399 464
        $emptyDimension = new RowDimension();
1400 464
        while ($currentRow++ < $highestRow) {
1401 464
            $isRowSet = isset($cellsByRow[$currentRow]);
1402 464
            if ($isRowSet || $worksheet->rowDimensionExists($currentRow)) {
1403
                // Get row dimension
1404 367
                $rowDimension = $worksheet->rowDimensionExists($currentRow) ? $worksheet->getRowDimension($currentRow) : $emptyDimension;
1405
1406
                // Write current row?
1407 367
                $writeCurrentRow = $isRowSet || $rowDimension->getRowHeight() >= 0 || $rowDimension->getVisible() === false || $rowDimension->getCollapsed() === true || $rowDimension->getOutlineLevel() > 0 || $rowDimension->getXfIndex() !== null;
1408
1409 367
                if ($writeCurrentRow) {
1410
                    // Start a new row
1411 367
                    $objWriter->startElement('row');
1412 367
                    $objWriter->writeAttribute('r', "$currentRow");
1413 367
                    $objWriter->writeAttribute('spans', '1:' . $colCount);
1414
1415
                    // Row dimensions
1416 367
                    if ($rowDimension->getRowHeight() >= 0) {
1417 35
                        $objWriter->writeAttribute('customHeight', '1');
1418 35
                        $objWriter->writeAttribute('ht', StringHelper::formatNumber($rowDimension->getRowHeight()));
1419
                    }
1420
1421
                    // Row visibility
1422 367
                    if (!$rowDimension->getVisible() === true) {
1423 16
                        $objWriter->writeAttribute('hidden', 'true');
1424
                    }
1425
1426
                    // Collapsed
1427 367
                    if ($rowDimension->getCollapsed() === true) {
1428
                        $objWriter->writeAttribute('collapsed', 'true');
1429
                    }
1430
1431
                    // Outline level
1432 367
                    if ($rowDimension->getOutlineLevel() > 0) {
1433
                        $objWriter->writeAttribute('outlineLevel', (string) $rowDimension->getOutlineLevel());
1434
                    }
1435
1436
                    // Style
1437 367
                    if ($rowDimension->getXfIndex() !== null) {
1438 8
                        $objWriter->writeAttribute('s', (string) $rowDimension->getXfIndex());
1439 8
                        $objWriter->writeAttribute('customFormat', '1');
1440
                    }
1441
1442
                    // Write cells
1443 367
                    if (isset($cellsByRow[$currentRow])) {
1444
                        // We have a comma-separated list of column names (with a trailing entry); split to an array
1445 367
                        $columnsInRow = explode(',', $cellsByRow[$currentRow]);
1446 367
                        array_pop($columnsInRow);
1447 367
                        foreach ($columnsInRow as $column) {
1448
                            // Write cell
1449 367
                            $coord = "$column$currentRow";
1450 367
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getNumberStoredAsText()) {
1451 4
                                $this->numberStoredAsText .= " $coord";
1452
                            }
1453 367
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getFormula()) {
1454 1
                                $this->formula .= " $coord";
1455
                            }
1456 367
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getFormulaRange()) {
1457 1
                                $this->formulaRange .= " $coord";
1458
                            }
1459 367
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getTwoDigitTextYear()) {
1460 1
                                $this->twoDigitTextYear .= " $coord";
1461
                            }
1462 367
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getEvalError()) {
1463 1
                                $this->evalError .= " $coord";
1464
                            }
1465 367
                            $this->writeCell($objWriter, $worksheet, $coord, $aFlippedStringTable);
1466
                        }
1467
                    }
1468
1469
                    // End row
1470 366
                    $objWriter->endElement();
1471
                }
1472
            }
1473
        }
1474
1475 463
        $objWriter->endElement();
1476
    }
1477
1478 14
    private function writeCellInlineStr(XMLWriter $objWriter, string $mappedType, RichText|string $cellValue, ?Font $font): void
1479
    {
1480 14
        $objWriter->writeAttribute('t', $mappedType);
1481 14
        if (!$cellValue instanceof RichText) {
1482 3
            $objWriter->startElement('is');
1483 3
            $objWriter->startElement('t');
1484 3
            $textToWrite = StringHelper::controlCharacterPHP2OOXML(
1485 3
                $cellValue
1486 3
            );
1487 3
            if ($textToWrite !== trim($textToWrite)) {
1488 1
                $objWriter->writeAttribute('xml:space', 'preserve');
1489
            }
1490 3
            $objWriter->writeRawData($textToWrite);
1491 3
            $objWriter->endElement(); // t
1492 3
            $objWriter->endElement(); // is
1493
        } else {
1494 13
            $objWriter->startElement('is');
1495 13
            $this->getParentWriter()
1496 13
                ->getWriterPartstringtable()
1497 13
                ->writeRichText($objWriter, $cellValue, null, $font);
1498 13
            $objWriter->endElement();
1499
        }
1500
    }
1501
1502
    /**
1503
     * @param string[] $flippedStringTable
1504
     */
1505 254
    private function writeCellString(XMLWriter $objWriter, string $mappedType, RichText|string $cellValue, array $flippedStringTable): void
1506
    {
1507 254
        $objWriter->writeAttribute('t', $mappedType);
1508 254
        if (!$cellValue instanceof RichText) {
1509 253
            self::writeElementIf($objWriter, isset($flippedStringTable[$cellValue]), 'v', $flippedStringTable[$cellValue] ?? '');
1510
        } else {
1511 9
            $objWriter->writeElement('v', $flippedStringTable[$cellValue->getHashCode()]);
1512
        }
1513
    }
1514
1515 233
    private function writeCellNumeric(XMLWriter $objWriter, float|int $cellValue): void
1516
    {
1517 233
        $result = StringHelper::convertToString($cellValue);
1518 233
        if (is_float($cellValue) && !str_contains($result, '.')) {
1519 29
            $result .= '.0';
1520
        }
1521 233
        $objWriter->writeElement('v', $result);
1522
    }
1523
1524 14
    private function writeCellBoolean(XMLWriter $objWriter, string $mappedType, bool $cellValue): void
1525
    {
1526 14
        $objWriter->writeAttribute('t', $mappedType);
1527 14
        $objWriter->writeElement('v', $cellValue ? '1' : '0');
1528
    }
1529
1530 12
    private function writeCellError(XMLWriter $objWriter, string $mappedType, string $cellValue, string $formulaerr = '#NULL!'): void
1531
    {
1532 12
        $objWriter->writeAttribute('t', $mappedType);
1533 12
        $cellIsFormula = str_starts_with($cellValue, '=');
1534 12
        self::writeElementIf($objWriter, $cellIsFormula, 'f', FunctionPrefix::addFunctionPrefixStripEquals($cellValue));
1535 12
        $objWriter->writeElement('v', $cellIsFormula ? $formulaerr : $cellValue);
1536
    }
1537
1538 113
    private function writeCellFormula(XMLWriter $objWriter, string $cellValue, Cell $cell): void
1539
    {
1540 113
        $attributes = $cell->getFormulaAttributes() ?? [];
1541 113
        $coordinate = $cell->getCoordinate();
1542 113
        $calculatedValue = $this->getParentWriter()->getPreCalculateFormulas() ? $cell->getCalculatedValue() : $cellValue;
1543 112
        if ($calculatedValue === ExcelError::SPILL()) {
1544 1
            $objWriter->writeAttribute('t', 'e');
1545
            //$objWriter->writeAttribute('cm', '1'); // already added
1546 1
            $objWriter->writeAttribute('vm', '1');
1547 1
            $objWriter->startElement('f');
1548 1
            $objWriter->writeAttribute('t', 'array');
1549 1
            $objWriter->writeAttribute('aca', '1');
1550 1
            $objWriter->writeAttribute('ref', $coordinate);
1551 1
            $objWriter->writeAttribute('ca', '1');
1552 1
            $objWriter->text(FunctionPrefix::addFunctionPrefixStripEquals($cellValue));
1553 1
            $objWriter->endElement(); // f
1554 1
            $objWriter->writeElement('v', ExcelError::VALUE()); // note #VALUE! in xml even though error is #SPILL!
1555
1556 1
            return;
1557
        }
1558 111
        $calculatedValueString = $this->getParentWriter()->getPreCalculateFormulas() ? $cell->getCalculatedValueString() : $cellValue;
1559 111
        $result = $calculatedValue;
1560 111
        while (is_array($result)) {
1561 11
            $result = array_shift($result);
1562
        }
1563 111
        if (is_string($result)) {
1564 45
            if (ErrorValue::isError($result)) {
1565 11
                $this->writeCellError($objWriter, 'e', $cellValue, $result);
1566
1567 11
                return;
1568
            }
1569 43
            $objWriter->writeAttribute('t', 'str');
1570 43
            $result = $calculatedValueString = StringHelper::controlCharacterPHP2OOXML($result);
1571 43
            if (is_string($calculatedValue)) {
1572 42
                $calculatedValue = $calculatedValueString;
1573
            }
1574 89
        } elseif (is_bool($result)) {
1575 8
            $objWriter->writeAttribute('t', 'b');
1576 8
            if (is_bool($calculatedValue)) {
1577 8
                $calculatedValue = $result;
1578
            }
1579 8
            $result = (int) $result;
1580 8
            $calculatedValueString = (string) $result;
1581
        }
1582
1583 111
        if (isset($attributes['ref'])) {
1584 28
            $ref = $this->parseRef($coordinate, $attributes['ref']);
1585 28
            if ($ref === "$coordinate:$coordinate") {
1586
                $ref = $coordinate;
1587
            }
1588
        } else {
1589 100
            $ref = $coordinate;
1590
        }
1591 111
        if (is_array($calculatedValue)) {
1592 11
            $attributes['t'] = 'array';
1593
        }
1594 111
        if (($attributes['t'] ?? null) === 'array') {
1595 14
            $objWriter->startElement('f');
1596 14
            $objWriter->writeAttribute('t', 'array');
1597 14
            $objWriter->writeAttribute('ref', $ref);
1598 14
            $objWriter->writeAttribute('aca', '1');
1599 14
            $objWriter->writeAttribute('ca', '1');
1600 14
            $objWriter->text(FunctionPrefix::addFunctionPrefixStripEquals($cellValue));
1601 14
            $objWriter->endElement();
1602
            if (
1603 14
                is_scalar($result)
1604 14
                && $this->getParentWriter()->getOffice2003Compatibility() === false
1605 14
                && $this->getParentWriter()->getPreCalculateFormulas()
1606
            ) {
1607 14
                $objWriter->writeElement('v', (string) $result);
1608
            }
1609
        } else {
1610 98
            $objWriter->writeElement('f', FunctionPrefix::addFunctionPrefixStripEquals($cellValue));
1611 98
            self::writeElementIf(
1612 98
                $objWriter,
1613 98
                $this->getParentWriter()->getOffice2003Compatibility() === false
1614 98
                    && $this->getParentWriter()->getPreCalculateFormulas()
1615 98
                    && $calculatedValue !== null,
1616 98
                'v',
1617 98
                (!is_array($calculatedValue) && !str_starts_with($calculatedValueString, '#'))
1618 98
                    ? StringHelper::formatNumber($calculatedValueString) : '0'
1619 98
            );
1620
        }
1621
    }
1622
1623 28
    private function parseRef(string $coordinate, string $ref): string
1624
    {
1625 28
        if (!Preg::isMatch('/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/', $ref, $matches)) {
1626
            return $ref;
1627
        }
1628 28
        if (!isset($matches[3])) { // single cell, not range
1629 2
            return $coordinate;
1630
        }
1631 28
        $minRow = (int) $matches[2];
1632 28
        $maxRow = (int) $matches[5];
1633 28
        $rows = $maxRow - $minRow + 1;
1634 28
        $minCol = Coordinate::columnIndexFromString($matches[1]);
1635 28
        $maxCol = Coordinate::columnIndexFromString($matches[4]);
1636 28
        $cols = $maxCol - $minCol + 1;
1637 28
        $firstCellArray = Coordinate::indexesFromString($coordinate);
1638 28
        $lastRow = $firstCellArray[1] + $rows - 1;
1639 28
        $lastColumn = $firstCellArray[0] + $cols - 1;
1640 28
        $lastColumnString = Coordinate::stringFromColumnIndex($lastColumn);
1641
1642 28
        return "$coordinate:$lastColumnString$lastRow";
1643
    }
1644
1645
    /**
1646
     * Write Cell.
1647
     *
1648
     * @param string $cellAddress Cell Address
1649
     * @param string[] $flippedStringTable String table (flipped), for faster index searching
1650
     */
1651 367
    private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, string $cellAddress, array $flippedStringTable): void
1652
    {
1653
        // Cell
1654 367
        $pCell = $worksheet->getCell($cellAddress);
1655 367
        $xfi = $pCell->getXfIndex();
1656 367
        $cellValue = $pCell->getValue();
1657 367
        $cellValueString = $pCell->getValueString();
1658 367
        $writeValue = $cellValue !== '' && $cellValue !== null;
1659 367
        if (empty($xfi) && !$writeValue) {
1660 27
            return;
1661
        }
1662 367
        $styleArray = $this->getParentWriter()
1663 367
            ->getSpreadsheet()
1664 367
            ->getCellXfCollection();
1665 367
        $font = $styleArray[$xfi] ?? null;
1666 367
        if ($font !== null) {
1667 367
            $font = $font->getFont();
1668
        }
1669 367
        $objWriter->startElement('c');
1670 367
        $objWriter->writeAttribute('r', $cellAddress);
1671 367
        $mappedType = $pCell->getDataType();
1672 367
        if ($mappedType === DataType::TYPE_FORMULA) {
1673 113
            if ($this->useDynamicArrays) {
1674 11
                if (preg_match(PhpspreadsheetWorksheet::FUNCTION_LIKE_GROUPBY, $cellValueString) === 1) {
1675 1
                    $tempCalc = [];
1676
                } else {
1677 10
                    $tempCalc = $pCell->getCalculatedValue();
1678
                }
1679 11
                if (is_array($tempCalc)) {
1680 10
                    $objWriter->writeAttribute('cm', '1');
1681
                }
1682
            }
1683
        }
1684
1685
        // Sheet styles
1686 367
        if ($xfi) {
1687 128
            $objWriter->writeAttribute('s', "$xfi");
1688 332
        } elseif ($this->explicitStyle0) {
1689 1
            $objWriter->writeAttribute('s', '0');
1690
        }
1691
1692
        // If cell value is supplied, write cell value
1693 367
        if ($writeValue) {
1694
            // Write data depending on its type
1695 360
            switch (strtolower($mappedType)) {
1696 360
                case 'inlinestr':    // Inline string
1697
                    /** @var RichText|string */
1698 14
                    $richText = $cellValue;
1699 14
                    $this->writeCellInlineStr($objWriter, $mappedType, $richText, $font);
1700
1701 14
                    break;
1702 356
                case 's':            // String
1703 254
                    $this->writeCellString($objWriter, $mappedType, ($cellValue instanceof RichText) ? $cellValue : $cellValueString, $flippedStringTable);
1704
1705 254
                    break;
1706 268
                case 'f':            // Formula
1707 113
                    $this->writeCellFormula($objWriter, $cellValueString, $pCell);
1708
1709 112
                    break;
1710 237
                case 'n':            // Numeric
1711 233
                    $cellValueNumeric = is_numeric($cellValue) ? ($cellValue + 0) : 0;
1712 233
                    $this->writeCellNumeric($objWriter, $cellValueNumeric);
1713
1714 233
                    break;
1715 14
                case 'b':            // Boolean
1716 14
                    $this->writeCellBoolean($objWriter, $mappedType, (bool) $cellValue);
1717
1718 14
                    break;
1719 1
                case 'e':            // Error
1720 1
                    $this->writeCellError($objWriter, $mappedType, $cellValueString);
1721
            }
1722
        }
1723
1724 366
        $objWriter->endElement(); // c
1725
    }
1726
1727
    /**
1728
     * Write Drawings.
1729
     *
1730
     * @param bool $includeCharts Flag indicating if we should include drawing details for charts
1731
     */
1732 463
    private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, bool $includeCharts = false): void
1733
    {
1734
        /** @var mixed[][][][] */
1735 463
        $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData();
1736 463
        $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']);
1737 463
        $chartCount = ($includeCharts) ? $worksheet->getChartCollection()->count() : 0;
1738 463
        if ($chartCount == 0 && $worksheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) {
1739 355
            return;
1740
        }
1741
1742
        // If sheet contains drawings, add the relationships
1743 127
        $objWriter->startElement('drawing');
1744
1745 127
        $rId = 'rId1';
1746 127
        if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) {
1747 49
            $drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'];
1748
            // take first. In future can be overriten
1749
            // (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels::writeWorksheetRelationships)
1750 49
            $rId = reset($drawingOriginalIds);
1751
        }
1752
1753
        /** @var string $rId */
1754 127
        $objWriter->writeAttribute('r:id', $rId);
1755 127
        $objWriter->endElement();
1756
    }
1757
1758
    /**
1759
     * Write LegacyDrawing.
1760
     */
1761 463
    private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1762
    {
1763
        // If sheet contains comments, add the relationships
1764
        /** @var mixed[][][][] */
1765 463
        $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData();
1766 463
        if (count($worksheet->getComments()) > 0 || isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing'])) {
1767 28
            $objWriter->startElement('legacyDrawing');
1768 28
            $objWriter->writeAttribute('r:id', 'rId_comments_vml1');
1769 28
            $objWriter->endElement();
1770
        }
1771
    }
1772
1773
    /**
1774
     * Write LegacyDrawingHF.
1775
     */
1776 463
    private function writeLegacyDrawingHF(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1777
    {
1778
        // If sheet contains images, add the relationships
1779 463
        if (count($worksheet->getHeaderFooter()->getImages()) > 0) {
1780 4
            $objWriter->startElement('legacyDrawingHF');
1781 4
            $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1');
1782 4
            $objWriter->endElement();
1783
        }
1784
    }
1785
1786 463
    private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1787
    {
1788
        /** @var string[][][] */
1789 463
        $unparsedSheet = $worksheet->getParentOrThrow()->getUnparsedLoadedData()['sheets'] ?? [];
1790 463
        $unparsedSheet = $unparsedSheet[$worksheet->getCodeName()] ?? [];
1791 463
        $unparsedSheet = $unparsedSheet['AlternateContents'] ?? [];
1792
1793 463
        foreach ($unparsedSheet as $alternateContent) {
1794 4
            $objWriter->writeRaw($alternateContent);
1795
        }
1796
    }
1797
1798
    /**
1799
     * write <ExtLst>
1800
     * only implementation conditionalFormattings.
1801
     *
1802
     * @url https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627
1803
     */
1804 463
    private function writeExtLst(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1805
    {
1806 463
        $conditionalFormattingRuleExtList = [];
1807 463
        foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
1808
            /** @var Conditional $conditional */
1809 92
            foreach ($conditionalStyles as $conditional) {
1810 92
                $dataBar = $conditional->getDataBar();
1811 92
                if ($dataBar && $dataBar->getConditionalFormattingRuleExt()) {
1812 1
                    $conditionalFormattingRuleExtList[] = $dataBar->getConditionalFormattingRuleExt();
1813
                }
1814
            }
1815
        }
1816
1817 463
        if (count($conditionalFormattingRuleExtList) > 0) {
1818 1
            $conditionalFormattingRuleExtNsPrefix = 'x14';
1819 1
            $objWriter->startElement('extLst');
1820 1
            $objWriter->startElement('ext');
1821 1
            $objWriter->writeAttribute('uri', '{78C0D931-6437-407d-A8EE-F0AAD7539E65}');
1822 1
            $objWriter->startElementNs($conditionalFormattingRuleExtNsPrefix, 'conditionalFormattings', null);
1823 1
            foreach ($conditionalFormattingRuleExtList as $extension) {
1824 1
                self::writeExtConditionalFormattingElements($objWriter, $extension);
1825
            }
1826 1
            $objWriter->endElement(); //end conditionalFormattings
1827 1
            $objWriter->endElement(); //end ext
1828 1
            $objWriter->endElement(); //end extLst
1829
        }
1830
    }
1831
}
1832