Passed
Push — master ( 68fd71...055281 )
by
unknown
16:29 queued 06:03
created

Worksheet::writeExtLst()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 17
c 0
b 0
f 0
nc 12
nop 2
dl 0
loc 25
ccs 18
cts 18
cp 1
crap 7
rs 8.8333
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\Settings;
14
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
15
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
16
use PhpOffice\PhpSpreadsheet\Style\Conditional;
17
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalColorScale;
18
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar;
19
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormattingRuleExtension;
20
use PhpOffice\PhpSpreadsheet\Worksheet\RowDimension;
21
use PhpOffice\PhpSpreadsheet\Worksheet\SheetView;
22
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as PhpspreadsheetWorksheet;
23
24
class Worksheet extends WriterPart
25
{
26
    private string $numberStoredAsText = '';
27
28
    private string $formula = '';
29
30
    private string $formulaRange = '';
31
32
    private string $twoDigitTextYear = '';
33
34
    private string $evalError = '';
35
36
    private bool $explicitStyle0;
37
38
    private bool $useDynamicArrays = false;
39
40
    /**
41
     * Write worksheet to XML format.
42
     *
43
     * @param string[] $stringTable
44
     * @param bool $includeCharts Flag indicating if we should write charts
45
     *
46
     * @return string XML Output
47
     */
48 423
    public function writeWorksheet(PhpspreadsheetWorksheet $worksheet, array $stringTable = [], bool $includeCharts = false): string
49
    {
50 423
        $this->useDynamicArrays = $this->getParentWriter()->useDynamicArrays();
51 423
        $this->explicitStyle0 = $this->getParentWriter()->getExplicitStyle0();
52 423
        $worksheet->calculateArrays($this->getParentWriter()->getPreCalculateFormulas());
53 423
        $this->numberStoredAsText = '';
54 423
        $this->formula = '';
55 423
        $this->formulaRange = '';
56 423
        $this->twoDigitTextYear = '';
57 423
        $this->evalError = '';
58
        // Create XML writer
59 423
        $objWriter = null;
60 423
        if ($this->getParentWriter()->getUseDiskCaching()) {
61
            $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
62
        } else {
63 423
            $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
64
        }
65
66
        // XML header
67 423
        $objWriter->startDocument('1.0', 'UTF-8', 'yes');
68
69
        // Worksheet
70 423
        $objWriter->startElement('worksheet');
71 423
        $objWriter->writeAttribute('xml:space', 'preserve');
72 423
        $objWriter->writeAttribute('xmlns', Namespaces::MAIN);
73 423
        $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT);
74
75 423
        $objWriter->writeAttribute('xmlns:xdr', Namespaces::SPREADSHEET_DRAWING);
76 423
        $objWriter->writeAttribute('xmlns:x14', Namespaces::DATA_VALIDATIONS1);
77 423
        $objWriter->writeAttribute('xmlns:xm', Namespaces::DATA_VALIDATIONS2);
78 423
        $objWriter->writeAttribute('xmlns:mc', Namespaces::COMPATIBILITY);
79 423
        $objWriter->writeAttribute('mc:Ignorable', 'x14ac');
80 423
        $objWriter->writeAttribute('xmlns:x14ac', Namespaces::SPREADSHEETML_AC);
81
82
        // sheetPr
83 423
        $this->writeSheetPr($objWriter, $worksheet);
84
85
        // Dimension
86 423
        $this->writeDimension($objWriter, $worksheet);
87
88
        // sheetViews
89 423
        $this->writeSheetViews($objWriter, $worksheet);
90
91
        // sheetFormatPr
92 423
        $this->writeSheetFormatPr($objWriter, $worksheet);
93
94
        // cols
95 423
        $this->writeCols($objWriter, $worksheet);
96
97
        // sheetData
98 423
        $this->writeSheetData($objWriter, $worksheet, $stringTable);
99
100
        // sheetProtection
101 422
        $this->writeSheetProtection($objWriter, $worksheet);
102
103
        // protectedRanges
104 422
        $this->writeProtectedRanges($objWriter, $worksheet);
105
106
        // autoFilter
107 422
        $this->writeAutoFilter($objWriter, $worksheet);
108
109
        // mergeCells
110 422
        $this->writeMergeCells($objWriter, $worksheet);
111
112
        // conditionalFormatting
113 422
        $this->writeConditionalFormatting($objWriter, $worksheet);
114
115
        // dataValidations
116 422
        $this->writeDataValidations($objWriter, $worksheet);
117
118
        // hyperlinks
119 422
        $this->writeHyperlinks($objWriter, $worksheet);
120
121
        // Print options
122 422
        $this->writePrintOptions($objWriter, $worksheet);
123
124
        // Page margins
125 422
        $this->writePageMargins($objWriter, $worksheet);
126
127
        // Page setup
128 422
        $this->writePageSetup($objWriter, $worksheet);
129
130
        // Header / footer
131 422
        $this->writeHeaderFooter($objWriter, $worksheet);
132
133
        // Breaks
134 422
        $this->writeBreaks($objWriter, $worksheet);
135
136
        // IgnoredErrors
137 422
        $this->writeIgnoredErrors($objWriter);
138
139
        // Drawings and/or Charts
140 422
        $this->writeDrawings($objWriter, $worksheet, $includeCharts);
141
142
        // LegacyDrawing
143 422
        $this->writeLegacyDrawing($objWriter, $worksheet);
144
145
        // LegacyDrawingHF
146 422
        $this->writeLegacyDrawingHF($objWriter, $worksheet);
147
148
        // AlternateContent
149 422
        $this->writeAlternateContent($objWriter, $worksheet);
150
151
        // BackgroundImage must come after ignored, before table
152 422
        $this->writeBackgroundImage($objWriter, $worksheet);
153
154
        // Table
155 422
        $this->writeTable($objWriter, $worksheet);
156
157
        // ConditionalFormattingRuleExtensionList
158
        // (Must be inserted last. Not insert last, an Excel parse error will occur)
159 422
        $this->writeExtLst($objWriter, $worksheet);
160
161 422
        $objWriter->endElement();
162
163
        // Return
164 422
        return $objWriter->getData();
165
    }
166
167 422
    private function writeIgnoredError(XMLWriter $objWriter, bool &$started, string $attr, string $cells): void
168
    {
169 422
        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 422
    private function writeIgnoredErrors(XMLWriter $objWriter): void
182
    {
183 422
        $started = false;
184 422
        $this->writeIgnoredError($objWriter, $started, 'numberStoredAsText', $this->numberStoredAsText);
185 422
        $this->writeIgnoredError($objWriter, $started, 'formula', $this->formula);
186 422
        $this->writeIgnoredError($objWriter, $started, 'formulaRange', $this->formulaRange);
187 422
        $this->writeIgnoredError($objWriter, $started, 'twoDigitTextYear', $this->twoDigitTextYear);
188 422
        $this->writeIgnoredError($objWriter, $started, 'evalError', $this->evalError);
189 422
        if ($started) {
190 4
            $objWriter->endElement();
191
        }
192
    }
193
194
    /**
195
     * Write SheetPr.
196
     */
197 423
    private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
198
    {
199
        // sheetPr
200 423
        $objWriter->startElement('sheetPr');
201 423
        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 423
        $autoFilterRange = $worksheet->getAutoFilter()->getRange();
209 423
        if (!empty($autoFilterRange)) {
210 10
            $objWriter->writeAttribute('filterMode', '1');
211 10
            if (!$worksheet->getAutoFilter()->getEvaluated()) {
212 6
                $worksheet->getAutoFilter()->showHideRows();
213
            }
214
        }
215 423
        $tables = $worksheet->getTableCollection();
216 423
        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 423
        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 423
        $objWriter->startElement('outlinePr');
233 423
        $objWriter->writeAttribute('summaryBelow', ($worksheet->getShowSummaryBelow() ? '1' : '0'));
234 423
        $objWriter->writeAttribute('summaryRight', ($worksheet->getShowSummaryRight() ? '1' : '0'));
235 423
        $objWriter->endElement();
236
237
        // pageSetUpPr
238 423
        if ($worksheet->getPageSetup()->getFitToPage()) {
239 6
            $objWriter->startElement('pageSetUpPr');
240 6
            $objWriter->writeAttribute('fitToPage', '1');
241 6
            $objWriter->endElement();
242
        }
243
244 423
        $objWriter->endElement();
245
    }
246
247
    /**
248
     * Write Dimension.
249
     */
250 423
    private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
251
    {
252
        // dimension
253 423
        $objWriter->startElement('dimension');
254 423
        $objWriter->writeAttribute('ref', $worksheet->calculateWorksheetDimension());
255 423
        $objWriter->endElement();
256
    }
257
258
    /**
259
     * Write SheetViews.
260
     */
261 423
    private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
262
    {
263
        // sheetViews
264 423
        $objWriter->startElement('sheetViews');
265
266
        // Sheet selected?
267 423
        $sheetSelected = false;
268 423
        if ($this->getParentWriter()->getSpreadsheet()->getIndex($worksheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) {
269 418
            $sheetSelected = true;
270
        }
271
272
        // sheetView
273 423
        $objWriter->startElement('sheetView');
274 423
        $objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0');
275 423
        $objWriter->writeAttribute('workbookViewId', '0');
276
277
        // Zoom scales
278 423
        $zoomScale = $worksheet->getSheetView()->getZoomScale();
279 423
        if ($zoomScale !== 100 && $zoomScale !== null) {
280 9
            $objWriter->writeAttribute('zoomScale', (string) $zoomScale);
281
        }
282 423
        $zoomScale = $worksheet->getSheetView()->getZoomScaleNormal();
283 423
        if ($zoomScale !== 100 && $zoomScale !== null) {
284 6
            $objWriter->writeAttribute('zoomScaleNormal', (string) $zoomScale);
285
        }
286 423
        $zoomScale = $worksheet->getSheetView()->getZoomScalePageLayoutView();
287 423
        if ($zoomScale !== 100) {
288 4
            $objWriter->writeAttribute('zoomScalePageLayoutView', (string) $zoomScale);
289
        }
290 423
        $zoomScale = $worksheet->getSheetView()->getZoomScaleSheetLayoutView();
291 423
        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 423
        if ($worksheet->getSheetView()->getShowZeros() === false) {
297
            $objWriter->writeAttribute('showZeros', '0');
298
        }
299
300
        // View Layout Type
301 423
        if ($worksheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) {
302 5
            $objWriter->writeAttribute('view', $worksheet->getSheetView()->getView());
303
        }
304
305
        // Gridlines
306 423
        if ($worksheet->getShowGridlines()) {
307 419
            $objWriter->writeAttribute('showGridLines', 'true');
308
        } else {
309 9
            $objWriter->writeAttribute('showGridLines', 'false');
310
        }
311
312
        // Row and column headers
313 423
        if ($worksheet->getShowRowColHeaders()) {
314 423
            $objWriter->writeAttribute('showRowColHeaders', '1');
315
        } else {
316
            $objWriter->writeAttribute('showRowColHeaders', '0');
317
        }
318
319
        // Right-to-left
320 423
        if ($worksheet->getRightToLeft()) {
321 1
            $objWriter->writeAttribute('rightToLeft', 'true');
322
        }
323
324 423
        $topLeftCell = $worksheet->getTopLeftCell();
325 423
        if (!empty($topLeftCell) && $worksheet->getPaneState() !== PhpspreadsheetWorksheet::PANE_FROZEN && $worksheet->getPaneState() !== PhpspreadsheetWorksheet::PANE_FROZENSPLIT) {
326 12
            $objWriter->writeAttribute('topLeftCell', $topLeftCell);
327
        }
328 423
        $activeCell = $worksheet->getActiveCell();
329 423
        $sqref = $worksheet->getSelectedCells();
330
331
        // Pane
332 423
        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 423
        if (!empty($sqref) || !empty($activeCell)) {
401 416
            $objWriter->startElement('selection');
402 416
            if (!empty($activeCell)) {
403 416
                $objWriter->writeAttribute('activeCell', $activeCell);
404
            }
405 416
            if (!empty($sqref)) {
406 416
                $objWriter->writeAttribute('sqref', $sqref);
407
            }
408 416
            $objWriter->endElement(); // selection
409
        }
410
411 423
        $objWriter->endElement();
412
413 423
        $objWriter->endElement();
414
    }
415
416
    /**
417
     * Write SheetFormatPr.
418
     */
419 423
    private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
420
    {
421
        // sheetFormatPr
422 423
        $objWriter->startElement('sheetFormatPr');
423
424
        // Default row height
425 423
        if ($worksheet->getDefaultRowDimension()->getRowHeight() >= 0) {
426 16
            $objWriter->writeAttribute('customHeight', 'true');
427 16
            $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($worksheet->getDefaultRowDimension()->getRowHeight()));
428
        } else {
429 408
            $objWriter->writeAttribute('defaultRowHeight', '14.4');
430
        }
431
432
        // Set Zero Height row
433 423
        if ($worksheet->getDefaultRowDimension()->getZeroHeight()) {
434
            $objWriter->writeAttribute('zeroHeight', '1');
435
        }
436
437
        // Default column width
438 423
        if ($worksheet->getDefaultColumnDimension()->getWidth() >= 0) {
439 28
            $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($worksheet->getDefaultColumnDimension()->getWidth()));
440
        }
441
442
        // Outline level - row
443 423
        $outlineLevelRow = 0;
444 423
        foreach ($worksheet->getRowDimensions() as $dimension) {
445 58
            if ($dimension->getOutlineLevel() > $outlineLevelRow) {
446
                $outlineLevelRow = $dimension->getOutlineLevel();
447
            }
448
        }
449 423
        $objWriter->writeAttribute('outlineLevelRow', (string) (int) $outlineLevelRow);
450
451
        // Outline level - column
452 423
        $outlineLevelCol = 0;
453 423
        foreach ($worksheet->getColumnDimensions() as $dimension) {
454 94
            if ($dimension->getOutlineLevel() > $outlineLevelCol) {
455 1
                $outlineLevelCol = $dimension->getOutlineLevel();
456
            }
457
        }
458 423
        $objWriter->writeAttribute('outlineLevelCol', (string) (int) $outlineLevelCol);
459
460 423
        $objWriter->endElement();
461
    }
462
463
    /**
464
     * Write Cols.
465
     */
466 423
    private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
467
    {
468
        // cols
469 423
        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 422
    private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
528
    {
529 422
        $protection = $worksheet->getProtection();
530 422
        if (!$protection->isProtectionEnabled()) {
531 399
            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 75
    private static function writeAttributeIf(XMLWriter $objWriter, ?bool $condition, string $attr, string $val): void
574
    {
575 75
        if ($condition) {
576 74
            $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 268
    private static function writeElementIf(XMLWriter $objWriter, bool $condition, string $attr, string $val): void
588
    {
589 268
        if ($condition) {
590 251
            $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 66
    private static function writeDataBarElements(XMLWriter $objWriter, ?ConditionalDataBar $dataBar): void
731
    {
732 66
        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
    /**
868
     * Write ConditionalFormatting.
869
     */
870 422
    private function writeConditionalFormatting(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
871
    {
872
        // Conditional id
873 422
        $id = 0;
874 422
        foreach ($worksheet->getConditionalStylesCollection() as $conditionalStyles) {
875 66
            foreach ($conditionalStyles as $conditional) {
876 66
                $id = max($id, $conditional->getPriority());
877
            }
878
        }
879
880
        // Loop through styles in the current worksheet
881 422
        foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
882 66
            $objWriter->startElement('conditionalFormatting');
883
            // N.B. In Excel UI, intersection is space and union is comma.
884
            // But in Xml, intersection is comma and union is space.
885
            // Anyhow, I don't think Excel handles intersection correctly when reading.
886 66
            $outCoordinate = Coordinate::resolveUnionAndIntersection(str_replace('$', '', $cellCoordinate), ' ');
887 66
            $objWriter->writeAttribute('sqref', $outCoordinate);
888
889 66
            foreach ($conditionalStyles as $conditional) {
890
                // WHY was this again?
891
                // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) == '') {
892
                //    continue;
893
                // }
894
                // cfRule
895 66
                $objWriter->startElement('cfRule');
896 66
                $objWriter->writeAttribute('type', $conditional->getConditionType());
897 66
                self::writeAttributeIf(
898 66
                    $objWriter,
899 66
                    ($conditional->getConditionType() !== Conditional::CONDITION_COLORSCALE
900 66
                        && $conditional->getConditionType() !== Conditional::CONDITION_DATABAR
901 66
                        && $conditional->getNoFormatSet() === false),
902 66
                    'dxfId',
903 66
                    (string) $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode())
904 66
                );
905 66
                $priority = $conditional->getPriority() ?: ++$id;
906 66
                $objWriter->writeAttribute('priority', (string) $priority);
907
908 66
                self::writeAttributeif(
909 66
                    $objWriter,
910 66
                    (
911 66
                        $conditional->getConditionType() === Conditional::CONDITION_CELLIS
912 66
                        || $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT
913 66
                        || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT
914 66
                        || $conditional->getConditionType() === Conditional::CONDITION_BEGINSWITH
915 66
                        || $conditional->getConditionType() === Conditional::CONDITION_ENDSWITH
916 66
                    ) && $conditional->getOperatorType() !== Conditional::OPERATOR_NONE,
917 66
                    'operator',
918 66
                    $conditional->getOperatorType()
919 66
                );
920
921 66
                self::writeAttributeIf($objWriter, $conditional->getStopIfTrue(), 'stopIfTrue', '1');
922
923 66
                $cellRange = Coordinate::splitRange(str_replace('$', '', strtoupper($cellCoordinate)));
924 66
                [$topLeftCell] = $cellRange[0];
925
926
                if (
927 66
                    $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT
928 66
                    || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT
929 66
                    || $conditional->getConditionType() === Conditional::CONDITION_BEGINSWITH
930 66
                    || $conditional->getConditionType() === Conditional::CONDITION_ENDSWITH
931
                ) {
932 9
                    self::writeTextCondElements($objWriter, $conditional, $topLeftCell);
933 59
                } elseif ($conditional->getConditionType() === Conditional::CONDITION_TIMEPERIOD) {
934 12
                    self::writeTimePeriodCondElements($objWriter, $conditional, $topLeftCell);
935 47
                } elseif ($conditional->getConditionType() === Conditional::CONDITION_COLORSCALE) {
936 3
                    self::writeColorScaleElements($objWriter, $conditional->getColorScale());
937
                } else {
938 44
                    self::writeOtherCondElements($objWriter, $conditional, $topLeftCell);
939
                }
940
941
                //<dataBar>
942 66
                self::writeDataBarElements($objWriter, $conditional->getDataBar());
943
944 66
                $objWriter->endElement(); //end cfRule
945
            }
946
947 66
            $objWriter->endElement(); //end conditionalFormatting
948
        }
949
    }
950
951
    /**
952
     * Write DataValidations.
953
     */
954 422
    private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
955
    {
956
        // Datavalidation collection
957 422
        $dataValidationCollection = $worksheet->getDataValidationCollection();
958
959
        // Write data validations?
960 422
        if (!empty($dataValidationCollection)) {
961 16
            $objWriter->startElement('dataValidations');
962 16
            $objWriter->writeAttribute('count', (string) count($dataValidationCollection));
963
964 16
            foreach ($dataValidationCollection as $coordinate => $dv) {
965 16
                $objWriter->startElement('dataValidation');
966
967 16
                if ($dv->getType() != '') {
968 16
                    $objWriter->writeAttribute('type', $dv->getType());
969
                }
970
971 16
                if ($dv->getErrorStyle() != '') {
972 9
                    $objWriter->writeAttribute('errorStyle', $dv->getErrorStyle());
973
                }
974
975 16
                if ($dv->getOperator() != '') {
976 16
                    $objWriter->writeAttribute('operator', $dv->getOperator());
977
                }
978
979 16
                $objWriter->writeAttribute('allowBlank', ($dv->getAllowBlank() ? '1' : '0'));
980 16
                $objWriter->writeAttribute('showDropDown', (!$dv->getShowDropDown() ? '1' : '0'));
981 16
                $objWriter->writeAttribute('showInputMessage', ($dv->getShowInputMessage() ? '1' : '0'));
982 16
                $objWriter->writeAttribute('showErrorMessage', ($dv->getShowErrorMessage() ? '1' : '0'));
983
984 16
                if ($dv->getErrorTitle() !== '') {
985 7
                    $objWriter->writeAttribute('errorTitle', $dv->getErrorTitle());
986
                }
987 16
                if ($dv->getError() !== '') {
988 9
                    $objWriter->writeAttribute('error', $dv->getError());
989
                }
990 16
                if ($dv->getPromptTitle() !== '') {
991 6
                    $objWriter->writeAttribute('promptTitle', $dv->getPromptTitle());
992
                }
993 16
                if ($dv->getPrompt() !== '') {
994 5
                    $objWriter->writeAttribute('prompt', $dv->getPrompt());
995
                }
996
997 16
                $objWriter->writeAttribute('sqref', $dv->getSqref() ?? $coordinate);
998
999 16
                if ($dv->getFormula1() !== '') {
1000 16
                    $objWriter->writeElement('formula1', FunctionPrefix::addFunctionPrefix($dv->getFormula1()));
1001
                }
1002 16
                if ($dv->getFormula2() !== '') {
1003 3
                    $objWriter->writeElement('formula2', FunctionPrefix::addFunctionPrefix($dv->getFormula2()));
1004
                }
1005
1006 16
                $objWriter->endElement();
1007
            }
1008
1009 16
            $objWriter->endElement();
1010
        }
1011
    }
1012
1013
    /**
1014
     * Write Hyperlinks.
1015
     */
1016 422
    private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1017
    {
1018
        // Hyperlink collection
1019 422
        $hyperlinkCollection = $worksheet->getHyperlinkCollection();
1020
1021
        // Relation ID
1022 422
        $relationId = 1;
1023
1024
        // Write hyperlinks?
1025 422
        if (!empty($hyperlinkCollection)) {
1026 16
            $objWriter->startElement('hyperlinks');
1027
1028 16
            foreach ($hyperlinkCollection as $coordinate => $hyperlink) {
1029 16
                $objWriter->startElement('hyperlink');
1030
1031 16
                $objWriter->writeAttribute('ref', $coordinate);
1032 16
                if (!$hyperlink->isInternal()) {
1033 16
                    $objWriter->writeAttribute('r:id', 'rId_hyperlink_' . $relationId);
1034 16
                    ++$relationId;
1035
                } else {
1036 10
                    $objWriter->writeAttribute('location', str_replace('sheet://', '', $hyperlink->getUrl()));
1037
                }
1038
1039 16
                if ($hyperlink->getTooltip() !== '') {
1040 10
                    $objWriter->writeAttribute('tooltip', $hyperlink->getTooltip());
1041 10
                    $objWriter->writeAttribute('display', $hyperlink->getTooltip());
1042
                }
1043
1044 16
                $objWriter->endElement();
1045
            }
1046
1047 16
            $objWriter->endElement();
1048
        }
1049
    }
1050
1051
    /**
1052
     * Write ProtectedRanges.
1053
     */
1054 422
    private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1055
    {
1056 422
        if (count($worksheet->getProtectedCellRanges()) > 0) {
1057
            // protectedRanges
1058 9
            $objWriter->startElement('protectedRanges');
1059
1060
            // Loop protectedRanges
1061 9
            foreach ($worksheet->getProtectedCellRanges() as $protectedCell => $protectedRange) {
1062
                // protectedRange
1063 9
                $objWriter->startElement('protectedRange');
1064 9
                $objWriter->writeAttribute('name', $protectedRange->getName());
1065 9
                $objWriter->writeAttribute('sqref', $protectedCell);
1066 9
                $passwordHash = $protectedRange->getPassword();
1067 9
                $this->writeAttributeIf($objWriter, $passwordHash !== '', 'password', $passwordHash);
1068 9
                $securityDescriptor = $protectedRange->getSecurityDescriptor();
1069 9
                $this->writeAttributeIf($objWriter, $securityDescriptor !== '', 'securityDescriptor', $securityDescriptor);
1070 9
                $objWriter->endElement();
1071
            }
1072
1073 9
            $objWriter->endElement();
1074
        }
1075
    }
1076
1077
    /**
1078
     * Write MergeCells.
1079
     */
1080 422
    private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1081
    {
1082 422
        if (count($worksheet->getMergeCells()) > 0) {
1083
            // mergeCells
1084 38
            $objWriter->startElement('mergeCells');
1085
1086
            // Loop mergeCells
1087 38
            foreach ($worksheet->getMergeCells() as $mergeCell) {
1088
                // mergeCell
1089 38
                $objWriter->startElement('mergeCell');
1090 38
                $objWriter->writeAttribute('ref', $mergeCell);
1091 38
                $objWriter->endElement();
1092
            }
1093
1094 38
            $objWriter->endElement();
1095
        }
1096
    }
1097
1098
    /**
1099
     * Write PrintOptions.
1100
     */
1101 422
    private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1102
    {
1103
        // printOptions
1104 422
        $objWriter->startElement('printOptions');
1105
1106 422
        $objWriter->writeAttribute('gridLines', ($worksheet->getPrintGridlines() ? 'true' : 'false'));
1107 422
        $objWriter->writeAttribute('gridLinesSet', 'true');
1108
1109 422
        if ($worksheet->getPageSetup()->getHorizontalCentered()) {
1110 4
            $objWriter->writeAttribute('horizontalCentered', 'true');
1111
        }
1112
1113 422
        if ($worksheet->getPageSetup()->getVerticalCentered()) {
1114 2
            $objWriter->writeAttribute('verticalCentered', 'true');
1115
        }
1116
1117 422
        $objWriter->endElement();
1118
    }
1119
1120
    /**
1121
     * Write PageMargins.
1122
     */
1123 422
    private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1124
    {
1125
        // pageMargins
1126 422
        $objWriter->startElement('pageMargins');
1127 422
        $objWriter->writeAttribute('left', StringHelper::formatNumber($worksheet->getPageMargins()->getLeft()));
1128 422
        $objWriter->writeAttribute('right', StringHelper::formatNumber($worksheet->getPageMargins()->getRight()));
1129 422
        $objWriter->writeAttribute('top', StringHelper::formatNumber($worksheet->getPageMargins()->getTop()));
1130 422
        $objWriter->writeAttribute('bottom', StringHelper::formatNumber($worksheet->getPageMargins()->getBottom()));
1131 422
        $objWriter->writeAttribute('header', StringHelper::formatNumber($worksheet->getPageMargins()->getHeader()));
1132 422
        $objWriter->writeAttribute('footer', StringHelper::formatNumber($worksheet->getPageMargins()->getFooter()));
1133 422
        $objWriter->endElement();
1134
    }
1135
1136
    /**
1137
     * Write AutoFilter.
1138
     */
1139 422
    private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1140
    {
1141 422
        AutoFilter::writeAutoFilter($objWriter, $worksheet);
1142
    }
1143
1144
    /**
1145
     * Write Table.
1146
     */
1147 422
    private function writeTable(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1148
    {
1149 422
        $tableCount = $worksheet->getTableCollection()->count();
1150 422
        if ($tableCount === 0) {
1151 415
            return;
1152
        }
1153
1154 8
        $objWriter->startElement('tableParts');
1155 8
        $objWriter->writeAttribute('count', (string) $tableCount);
1156
1157 8
        for ($t = 1; $t <= $tableCount; ++$t) {
1158 8
            $objWriter->startElement('tablePart');
1159 8
            $objWriter->writeAttribute('r:id', 'rId_table_' . $t);
1160 8
            $objWriter->endElement();
1161
        }
1162
1163 8
        $objWriter->endElement();
1164
    }
1165
1166
    /**
1167
     * Write Background Image.
1168
     */
1169 422
    private function writeBackgroundImage(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1170
    {
1171 422
        if ($worksheet->getBackgroundImage() !== '') {
1172 2
            $objWriter->startElement('picture');
1173 2
            $objWriter->writeAttribute('r:id', 'rIdBg');
1174 2
            $objWriter->endElement();
1175
        }
1176
    }
1177
1178
    /**
1179
     * Write PageSetup.
1180
     */
1181 422
    private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1182
    {
1183
        // pageSetup
1184 422
        $objWriter->startElement('pageSetup');
1185 422
        $objWriter->writeAttribute('paperSize', (string) $worksheet->getPageSetup()->getPaperSize());
1186 422
        $objWriter->writeAttribute('orientation', $worksheet->getPageSetup()->getOrientation());
1187
1188 422
        if ($worksheet->getPageSetup()->getScale() !== null) {
1189 422
            $objWriter->writeAttribute('scale', (string) $worksheet->getPageSetup()->getScale());
1190
        }
1191 422
        if ($worksheet->getPageSetup()->getFitToHeight() !== null) {
1192 422
            $objWriter->writeAttribute('fitToHeight', (string) $worksheet->getPageSetup()->getFitToHeight());
1193
        } else {
1194
            $objWriter->writeAttribute('fitToHeight', '0');
1195
        }
1196 422
        if ($worksheet->getPageSetup()->getFitToWidth() !== null) {
1197 422
            $objWriter->writeAttribute('fitToWidth', (string) $worksheet->getPageSetup()->getFitToWidth());
1198
        } else {
1199
            $objWriter->writeAttribute('fitToWidth', '0');
1200
        }
1201 422
        if (!empty($worksheet->getPageSetup()->getFirstPageNumber())) {
1202 1
            $objWriter->writeAttribute('firstPageNumber', (string) $worksheet->getPageSetup()->getFirstPageNumber());
1203 1
            $objWriter->writeAttribute('useFirstPageNumber', '1');
1204
        }
1205 422
        $objWriter->writeAttribute('pageOrder', $worksheet->getPageSetup()->getPageOrder());
1206
1207
        /** @var string[][][] */
1208 422
        $getUnparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData();
1209 422
        if (isset($getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'])) {
1210 36
            $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId']);
1211
        }
1212
1213 422
        $objWriter->endElement();
1214
    }
1215
1216
    /**
1217
     * Write Header / Footer.
1218
     */
1219 422
    private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1220
    {
1221
        // headerFooter
1222 422
        $headerFooter = $worksheet->getHeaderFooter();
1223 422
        $oddHeader = $headerFooter->getOddHeader();
1224 422
        $oddFooter = $headerFooter->getOddFooter();
1225 422
        $evenHeader = $headerFooter->getEvenHeader();
1226 422
        $evenFooter = $headerFooter->getEvenFooter();
1227 422
        $firstHeader = $headerFooter->getFirstHeader();
1228 422
        $firstFooter = $headerFooter->getFirstFooter();
1229 422
        if ("$oddHeader$oddFooter$evenHeader$evenFooter$firstHeader$firstFooter" === '') {
1230 412
            return;
1231
        }
1232
1233 20
        $objWriter->startElement('headerFooter');
1234 20
        $objWriter->writeAttribute('differentOddEven', ($worksheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false'));
1235 20
        $objWriter->writeAttribute('differentFirst', ($worksheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false'));
1236 20
        $objWriter->writeAttribute('scaleWithDoc', ($worksheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false'));
1237 20
        $objWriter->writeAttribute('alignWithMargins', ($worksheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false'));
1238
1239 20
        self::writeElementIf($objWriter, $oddHeader !== '', 'oddHeader', $oddHeader);
1240 20
        self::writeElementIf($objWriter, $oddFooter !== '', 'oddFooter', $oddFooter);
1241 20
        self::writeElementIf($objWriter, $evenHeader !== '', 'evenHeader', $evenHeader);
1242 20
        self::writeElementIf($objWriter, $evenFooter !== '', 'evenFooter', $evenFooter);
1243 20
        self::writeElementIf($objWriter, $firstHeader !== '', 'firstHeader', $firstHeader);
1244 20
        self::writeElementIf($objWriter, $firstFooter !== '', 'firstFooter', $firstFooter);
1245
1246 20
        $objWriter->endElement(); // headerFooter
1247
    }
1248
1249
    /**
1250
     * Write Breaks.
1251
     */
1252 422
    private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1253
    {
1254
        // Get row and column breaks
1255 422
        $aRowBreaks = [];
1256 422
        $aColumnBreaks = [];
1257 422
        foreach ($worksheet->getRowBreaks() as $cell => $break) {
1258 9
            $aRowBreaks[$cell] = $break;
1259
        }
1260 422
        foreach ($worksheet->getColumnBreaks() as $cell => $break) {
1261 3
            $aColumnBreaks[$cell] = $break;
1262
        }
1263
1264
        // rowBreaks
1265 422
        if (!empty($aRowBreaks)) {
1266 9
            $objWriter->startElement('rowBreaks');
1267 9
            $objWriter->writeAttribute('count', (string) count($aRowBreaks));
1268 9
            $objWriter->writeAttribute('manualBreakCount', (string) count($aRowBreaks));
1269
1270 9
            foreach ($aRowBreaks as $cell => $break) {
1271 9
                $coords = Coordinate::coordinateFromString($cell);
1272
1273 9
                $objWriter->startElement('brk');
1274 9
                $objWriter->writeAttribute('id', $coords[1]);
1275 9
                $objWriter->writeAttribute('man', '1');
1276 9
                $rowBreakMax = $break->getMaxColOrRow();
1277 9
                if ($rowBreakMax >= 0) {
1278 1
                    $objWriter->writeAttribute('max', "$rowBreakMax");
1279 8
                } elseif ($worksheet->getPageSetup()->getPrintArea() !== '') {
1280 5
                    $maxCol = Coordinate::columnIndexFromString($worksheet->getHighestColumn());
1281 5
                    $objWriter->writeAttribute('max', "$maxCol");
1282
                }
1283 9
                $objWriter->endElement();
1284
            }
1285
1286 9
            $objWriter->endElement();
1287
        }
1288
1289
        // Second, write column breaks
1290 422
        if (!empty($aColumnBreaks)) {
1291 3
            $objWriter->startElement('colBreaks');
1292 3
            $objWriter->writeAttribute('count', (string) count($aColumnBreaks));
1293 3
            $objWriter->writeAttribute('manualBreakCount', (string) count($aColumnBreaks));
1294
1295 3
            foreach ($aColumnBreaks as $cell => $break) {
1296 3
                $coords = Coordinate::indexesFromString($cell);
1297
1298 3
                $objWriter->startElement('brk');
1299 3
                $objWriter->writeAttribute('id', (string) ((int) $coords[0] - 1));
1300 3
                $objWriter->writeAttribute('man', '1');
1301 3
                $colBreakMax = $break->getMaxColOrRow();
1302 3
                if ($colBreakMax >= 0) {
1303
                    $objWriter->writeAttribute('max', "$colBreakMax");
1304 3
                } elseif ($worksheet->getPageSetup()->getPrintArea() !== '') {
1305 1
                    $maxRow = $worksheet->getHighestRow();
1306 1
                    $objWriter->writeAttribute('max', "$maxRow");
1307
                }
1308 3
                $objWriter->endElement();
1309
            }
1310
1311 3
            $objWriter->endElement();
1312
        }
1313
    }
1314
1315
    /**
1316
     * Write SheetData.
1317
     *
1318
     * @param string[] $stringTable String table
1319
     */
1320 423
    private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, array $stringTable): void
1321
    {
1322
        // Flipped stringtable, for faster index searching
1323 423
        $aFlippedStringTable = $this->getParentWriter()->getWriterPartstringtable()->flipStringTable($stringTable);
1324
1325
        // sheetData
1326 423
        $objWriter->startElement('sheetData');
1327
1328
        // Get column count
1329 423
        $colCount = Coordinate::columnIndexFromString($worksheet->getHighestColumn());
1330
1331
        // Highest row number
1332 423
        $highestRow = $worksheet->getHighestRow();
1333
1334
        // Loop through cells building a comma-separated list of the columns in each row
1335
        // This is a trade-off between the memory usage that is required for a full array of columns,
1336
        //      and execution speed
1337
        /** @var array<int, string> $cellsByRow */
1338 423
        $cellsByRow = [];
1339 423
        foreach ($worksheet->getCoordinates() as $coordinate) {
1340 369
            [$column, $row] = Coordinate::coordinateFromString($coordinate);
1341 369
            if (!isset($cellsByRow[$row])) {
1342 369
                $pCell = $worksheet->getCell("$column$row");
1343 369
                $xfi = $pCell->getXfIndex();
1344 369
                $cellValue = $pCell->getValue();
1345 369
                $writeValue = $cellValue !== '' && $cellValue !== null;
1346 369
                if (!empty($xfi) || $writeValue) {
1347 352
                    $cellsByRow[$row] = "{$column},";
1348
                }
1349
            } else {
1350 226
                $cellsByRow[$row] .= "{$column},";
1351
            }
1352
        }
1353
1354 423
        $currentRow = 0;
1355 423
        $emptyDimension = new RowDimension();
1356 423
        while ($currentRow++ < $highestRow) {
1357 423
            $isRowSet = isset($cellsByRow[$currentRow]);
1358 423
            if ($isRowSet || $worksheet->rowDimensionExists($currentRow)) {
1359
                // Get row dimension
1360 352
                $rowDimension = $worksheet->rowDimensionExists($currentRow) ? $worksheet->getRowDimension($currentRow) : $emptyDimension;
1361
1362
                // Write current row?
1363 352
                $writeCurrentRow = $isRowSet || $rowDimension->getRowHeight() >= 0 || $rowDimension->getVisible() === false || $rowDimension->getCollapsed() === true || $rowDimension->getOutlineLevel() > 0 || $rowDimension->getXfIndex() !== null;
1364
1365 352
                if ($writeCurrentRow) {
1366
                    // Start a new row
1367 352
                    $objWriter->startElement('row');
1368 352
                    $objWriter->writeAttribute('r', "$currentRow");
1369 352
                    $objWriter->writeAttribute('spans', '1:' . $colCount);
1370
1371
                    // Row dimensions
1372 352
                    if ($rowDimension->getRowHeight() >= 0) {
1373 34
                        $objWriter->writeAttribute('customHeight', '1');
1374 34
                        $objWriter->writeAttribute('ht', StringHelper::formatNumber($rowDimension->getRowHeight()));
1375
                    }
1376
1377
                    // Row visibility
1378 352
                    if (!$rowDimension->getVisible() === true) {
1379 16
                        $objWriter->writeAttribute('hidden', 'true');
1380
                    }
1381
1382
                    // Collapsed
1383 352
                    if ($rowDimension->getCollapsed() === true) {
1384
                        $objWriter->writeAttribute('collapsed', 'true');
1385
                    }
1386
1387
                    // Outline level
1388 352
                    if ($rowDimension->getOutlineLevel() > 0) {
1389
                        $objWriter->writeAttribute('outlineLevel', (string) $rowDimension->getOutlineLevel());
1390
                    }
1391
1392
                    // Style
1393 352
                    if ($rowDimension->getXfIndex() !== null) {
1394 8
                        $objWriter->writeAttribute('s', (string) $rowDimension->getXfIndex());
1395 8
                        $objWriter->writeAttribute('customFormat', '1');
1396
                    }
1397
1398
                    // Write cells
1399 352
                    if (isset($cellsByRow[$currentRow])) {
1400
                        // We have a comma-separated list of column names (with a trailing entry); split to an array
1401 352
                        $columnsInRow = explode(',', $cellsByRow[$currentRow]);
1402 352
                        array_pop($columnsInRow);
1403 352
                        foreach ($columnsInRow as $column) {
1404
                            // Write cell
1405 352
                            $coord = "$column$currentRow";
1406 352
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getNumberStoredAsText()) {
1407 4
                                $this->numberStoredAsText .= " $coord";
1408
                            }
1409 352
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getFormula()) {
1410 1
                                $this->formula .= " $coord";
1411
                            }
1412 352
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getFormulaRange()) {
1413 1
                                $this->formulaRange .= " $coord";
1414
                            }
1415 352
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getTwoDigitTextYear()) {
1416 1
                                $this->twoDigitTextYear .= " $coord";
1417
                            }
1418 352
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getEvalError()) {
1419 1
                                $this->evalError .= " $coord";
1420
                            }
1421 352
                            $this->writeCell($objWriter, $worksheet, $coord, $aFlippedStringTable);
1422
                        }
1423
                    }
1424
1425
                    // End row
1426 351
                    $objWriter->endElement();
1427
                }
1428
            }
1429
        }
1430
1431 422
        $objWriter->endElement();
1432
    }
1433
1434 10
    private function writeCellInlineStr(XMLWriter $objWriter, string $mappedType, RichText|string $cellValue): void
1435
    {
1436 10
        $objWriter->writeAttribute('t', $mappedType);
1437 10
        if (!$cellValue instanceof RichText) {
1438 1
            $objWriter->startElement('is');
1439 1
            $objWriter->writeElement(
1440 1
                't',
1441 1
                StringHelper::controlCharacterPHP2OOXML(htmlspecialchars($cellValue, Settings::htmlEntityFlags()))
1442 1
            );
1443 1
            $objWriter->endElement();
1444
        } else {
1445 10
            $objWriter->startElement('is');
1446 10
            $this->getParentWriter()->getWriterPartstringtable()->writeRichText($objWriter, $cellValue);
1447 10
            $objWriter->endElement();
1448
        }
1449
    }
1450
1451
    /**
1452
     * @param string[] $flippedStringTable
1453
     */
1454 246
    private function writeCellString(XMLWriter $objWriter, string $mappedType, RichText|string $cellValue, array $flippedStringTable): void
1455
    {
1456 246
        $objWriter->writeAttribute('t', $mappedType);
1457 246
        if (!$cellValue instanceof RichText) {
1458 245
            self::writeElementIf($objWriter, isset($flippedStringTable[$cellValue]), 'v', $flippedStringTable[$cellValue] ?? '');
1459
        } else {
1460 9
            $objWriter->writeElement('v', $flippedStringTable[$cellValue->getHashCode()]);
1461
        }
1462
    }
1463
1464 228
    private function writeCellNumeric(XMLWriter $objWriter, float|int $cellValue): void
1465
    {
1466 228
        $result = StringHelper::convertToString($cellValue);
1467 228
        if (is_float($cellValue) && !str_contains($result, '.')) {
1468 29
            $result .= '.0';
1469
        }
1470 228
        $objWriter->writeElement('v', $result);
1471
    }
1472
1473 14
    private function writeCellBoolean(XMLWriter $objWriter, string $mappedType, bool $cellValue): void
1474
    {
1475 14
        $objWriter->writeAttribute('t', $mappedType);
1476 14
        $objWriter->writeElement('v', $cellValue ? '1' : '0');
1477
    }
1478
1479 12
    private function writeCellError(XMLWriter $objWriter, string $mappedType, string $cellValue, string $formulaerr = '#NULL!'): void
1480
    {
1481 12
        $objWriter->writeAttribute('t', $mappedType);
1482 12
        $cellIsFormula = str_starts_with($cellValue, '=');
1483 12
        self::writeElementIf($objWriter, $cellIsFormula, 'f', FunctionPrefix::addFunctionPrefixStripEquals($cellValue));
1484 12
        $objWriter->writeElement('v', $cellIsFormula ? $formulaerr : $cellValue);
1485
    }
1486
1487 111
    private function writeCellFormula(XMLWriter $objWriter, string $cellValue, Cell $cell): void
1488
    {
1489 111
        $attributes = $cell->getFormulaAttributes() ?? [];
1490 111
        $coordinate = $cell->getCoordinate();
1491 111
        $calculatedValue = $this->getParentWriter()->getPreCalculateFormulas() ? $cell->getCalculatedValue() : $cellValue;
1492 110
        if ($calculatedValue === ExcelError::SPILL()) {
1493 1
            $objWriter->writeAttribute('t', 'e');
1494
            //$objWriter->writeAttribute('cm', '1'); // already added
1495 1
            $objWriter->writeAttribute('vm', '1');
1496 1
            $objWriter->startElement('f');
1497 1
            $objWriter->writeAttribute('t', 'array');
1498 1
            $objWriter->writeAttribute('aca', '1');
1499 1
            $objWriter->writeAttribute('ref', $coordinate);
1500 1
            $objWriter->writeAttribute('ca', '1');
1501 1
            $objWriter->text(FunctionPrefix::addFunctionPrefixStripEquals($cellValue));
1502 1
            $objWriter->endElement(); // f
1503 1
            $objWriter->writeElement('v', ExcelError::VALUE()); // note #VALUE! in xml even though error is #SPILL!
1504
1505 1
            return;
1506
        }
1507 109
        $calculatedValueString = $this->getParentWriter()->getPreCalculateFormulas() ? $cell->getCalculatedValueString() : $cellValue;
1508 109
        $result = $calculatedValue;
1509 109
        while (is_array($result)) {
1510 8
            $result = array_shift($result);
1511
        }
1512 109
        if (is_string($result)) {
1513 45
            if (ErrorValue::isError($result)) {
1514 11
                $this->writeCellError($objWriter, 'e', $cellValue, $result);
1515
1516 11
                return;
1517
            }
1518 43
            $objWriter->writeAttribute('t', 'str');
1519 43
            $result = $calculatedValueString = StringHelper::controlCharacterPHP2OOXML($result);
1520 43
            if (is_string($calculatedValue)) {
1521 42
                $calculatedValue = $calculatedValueString;
1522
            }
1523 87
        } elseif (is_bool($result)) {
1524 8
            $objWriter->writeAttribute('t', 'b');
1525 8
            if (is_bool($calculatedValue)) {
1526 8
                $calculatedValue = $result;
1527
            }
1528 8
            $result = (int) $result;
1529 8
            $calculatedValueString = (string) $result;
1530
        }
1531
1532 109
        if (isset($attributes['ref'])) {
1533 26
            $ref = $this->parseRef($coordinate, $attributes['ref']);
1534 26
            if ($ref === "$coordinate:$coordinate") {
1535
                $ref = $coordinate;
1536
            }
1537
        } else {
1538 100
            $ref = $coordinate;
1539
        }
1540 109
        if (is_array($calculatedValue)) {
1541 8
            $attributes['t'] = 'array';
1542
        }
1543 109
        if (($attributes['t'] ?? null) === 'array') {
1544 12
            $objWriter->startElement('f');
1545 12
            $objWriter->writeAttribute('t', 'array');
1546 12
            $objWriter->writeAttribute('ref', $ref);
1547 12
            $objWriter->writeAttribute('aca', '1');
1548 12
            $objWriter->writeAttribute('ca', '1');
1549 12
            $objWriter->text(FunctionPrefix::addFunctionPrefixStripEquals($cellValue));
1550 12
            $objWriter->endElement();
1551
            if (
1552 12
                is_scalar($result)
1553 12
                && $this->getParentWriter()->getOffice2003Compatibility() === false
1554 12
                && $this->getParentWriter()->getPreCalculateFormulas()
1555
            ) {
1556 12
                $objWriter->writeElement('v', (string) $result);
1557
            }
1558
        } else {
1559 98
            $objWriter->writeElement('f', FunctionPrefix::addFunctionPrefixStripEquals($cellValue));
1560 98
            self::writeElementIf(
1561 98
                $objWriter,
1562 98
                $this->getParentWriter()->getOffice2003Compatibility() === false
1563 98
                && $this->getParentWriter()->getPreCalculateFormulas()
1564 98
                && $calculatedValue !== null,
1565 98
                'v',
1566 98
                (!is_array($calculatedValue) && !str_starts_with($calculatedValueString, '#'))
1567 98
                    ? StringHelper::formatNumber($calculatedValueString) : '0'
1568 98
            );
1569
        }
1570
    }
1571
1572 26
    private function parseRef(string $coordinate, string $ref): string
1573
    {
1574 26
        if (!Preg::isMatch('/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/', $ref, $matches)) {
1575
            return $ref;
1576
        }
1577 26
        if (!isset($matches[3])) { // single cell, not range
1578 2
            return $coordinate;
1579
        }
1580 26
        $minRow = (int) $matches[2];
1581 26
        $maxRow = (int) $matches[5];
1582 26
        $rows = $maxRow - $minRow + 1;
1583 26
        $minCol = Coordinate::columnIndexFromString($matches[1]);
1584 26
        $maxCol = Coordinate::columnIndexFromString($matches[4]);
1585 26
        $cols = $maxCol - $minCol + 1;
1586 26
        $firstCellArray = Coordinate::indexesFromString($coordinate);
1587 26
        $lastRow = $firstCellArray[1] + $rows - 1;
1588 26
        $lastColumn = $firstCellArray[0] + $cols - 1;
1589 26
        $lastColumnString = Coordinate::stringFromColumnIndex($lastColumn);
1590
1591 26
        return "$coordinate:$lastColumnString$lastRow";
1592
    }
1593
1594
    /**
1595
     * Write Cell.
1596
     *
1597
     * @param string $cellAddress Cell Address
1598
     * @param string[] $flippedStringTable String table (flipped), for faster index searching
1599
     */
1600 352
    private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, string $cellAddress, array $flippedStringTable): void
1601
    {
1602
        // Cell
1603 352
        $pCell = $worksheet->getCell($cellAddress);
1604 352
        $xfi = $pCell->getXfIndex();
1605 352
        $cellValue = $pCell->getValue();
1606 352
        $cellValueString = $pCell->getValueString();
1607 352
        $writeValue = $cellValue !== '' && $cellValue !== null;
1608 352
        if (empty($xfi) && !$writeValue) {
1609 27
            return;
1610
        }
1611 352
        $objWriter->startElement('c');
1612 352
        $objWriter->writeAttribute('r', $cellAddress);
1613 352
        $mappedType = $pCell->getDataType();
1614 352
        if ($mappedType === DataType::TYPE_FORMULA) {
1615 111
            if ($this->useDynamicArrays) {
1616 8
                if (preg_match(PhpspreadsheetWorksheet::FUNCTION_LIKE_GROUPBY, $cellValueString) === 1) {
1617
                    $tempCalc = [];
1618
                } else {
1619 8
                    $tempCalc = $pCell->getCalculatedValue();
1620
                }
1621 8
                if (is_array($tempCalc)) {
1622 7
                    $objWriter->writeAttribute('cm', '1');
1623
                }
1624
            }
1625
        }
1626
1627
        // Sheet styles
1628 352
        if ($xfi) {
1629 122
            $objWriter->writeAttribute('s', "$xfi");
1630 321
        } elseif ($this->explicitStyle0) {
1631 1
            $objWriter->writeAttribute('s', '0');
1632
        }
1633
1634
        // If cell value is supplied, write cell value
1635 352
        if ($writeValue) {
1636
            // Write data depending on its type
1637 346
            switch (strtolower($mappedType)) {
1638 346
                case 'inlinestr':    // Inline string
1639
                    /** @var RichText|string */
1640 10
                    $richText = $cellValue;
1641 10
                    $this->writeCellInlineStr($objWriter, $mappedType, $richText);
1642
1643 10
                    break;
1644 344
                case 's':            // String
1645 246
                    $this->writeCellString($objWriter, $mappedType, ($cellValue instanceof RichText) ? $cellValue : $cellValueString, $flippedStringTable);
1646
1647 246
                    break;
1648 263
                case 'f':            // Formula
1649 111
                    $this->writeCellFormula($objWriter, $cellValueString, $pCell);
1650
1651 110
                    break;
1652 232
                case 'n':            // Numeric
1653 228
                    $cellValueNumeric = is_numeric($cellValue) ? ($cellValue + 0) : 0;
1654 228
                    $this->writeCellNumeric($objWriter, $cellValueNumeric);
1655
1656 228
                    break;
1657 14
                case 'b':            // Boolean
1658 14
                    $this->writeCellBoolean($objWriter, $mappedType, (bool) $cellValue);
1659
1660 14
                    break;
1661 1
                case 'e':            // Error
1662 1
                    $this->writeCellError($objWriter, $mappedType, $cellValueString);
1663
            }
1664
        }
1665
1666 351
        $objWriter->endElement(); // c
1667
    }
1668
1669
    /**
1670
     * Write Drawings.
1671
     *
1672
     * @param bool $includeCharts Flag indicating if we should include drawing details for charts
1673
     */
1674 422
    private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, bool $includeCharts = false): void
1675
    {
1676
        /** @var mixed[][][][] */
1677 422
        $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData();
1678 422
        $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']);
1679 422
        $chartCount = ($includeCharts) ? $worksheet->getChartCollection()->count() : 0;
1680 422
        if ($chartCount == 0 && $worksheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) {
1681 314
            return;
1682
        }
1683
1684
        // If sheet contains drawings, add the relationships
1685 127
        $objWriter->startElement('drawing');
1686
1687 127
        $rId = 'rId1';
1688 127
        if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) {
1689 49
            $drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'];
1690
            // take first. In future can be overriten
1691
            // (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels::writeWorksheetRelationships)
1692 49
            $rId = reset($drawingOriginalIds);
1693
        }
1694
1695
        /** @var string $rId */
1696 127
        $objWriter->writeAttribute('r:id', $rId);
1697 127
        $objWriter->endElement();
1698
    }
1699
1700
    /**
1701
     * Write LegacyDrawing.
1702
     */
1703 422
    private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1704
    {
1705
        // If sheet contains comments, add the relationships
1706
        /** @var mixed[][][][] */
1707 422
        $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData();
1708 422
        if (count($worksheet->getComments()) > 0 || isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing'])) {
1709 28
            $objWriter->startElement('legacyDrawing');
1710 28
            $objWriter->writeAttribute('r:id', 'rId_comments_vml1');
1711 28
            $objWriter->endElement();
1712
        }
1713
    }
1714
1715
    /**
1716
     * Write LegacyDrawingHF.
1717
     */
1718 422
    private function writeLegacyDrawingHF(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1719
    {
1720
        // If sheet contains images, add the relationships
1721 422
        if (count($worksheet->getHeaderFooter()->getImages()) > 0) {
1722 3
            $objWriter->startElement('legacyDrawingHF');
1723 3
            $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1');
1724 3
            $objWriter->endElement();
1725
        }
1726
    }
1727
1728 422
    private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1729
    {
1730
        /** @var string[][][] */
1731 422
        $unparsedSheet = $worksheet->getParentOrThrow()->getUnparsedLoadedData()['sheets'] ?? [];
1732 422
        $unparsedSheet = $unparsedSheet[$worksheet->getCodeName()] ?? [];
1733 422
        $unparsedSheet = $unparsedSheet['AlternateContents'] ?? [];
1734
1735 422
        foreach ($unparsedSheet as $alternateContent) {
1736 4
            $objWriter->writeRaw($alternateContent);
1737
        }
1738
    }
1739
1740
    /**
1741
     * write <ExtLst>
1742
     * only implementation conditionalFormattings.
1743
     *
1744
     * @url https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627
1745
     */
1746 422
    private function writeExtLst(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1747
    {
1748 422
        $conditionalFormattingRuleExtList = [];
1749 422
        foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
1750
            /** @var Conditional $conditional */
1751 66
            foreach ($conditionalStyles as $conditional) {
1752 66
                $dataBar = $conditional->getDataBar();
1753 66
                if ($dataBar && $dataBar->getConditionalFormattingRuleExt()) {
1754 1
                    $conditionalFormattingRuleExtList[] = $dataBar->getConditionalFormattingRuleExt();
1755
                }
1756
            }
1757
        }
1758
1759 422
        if (count($conditionalFormattingRuleExtList) > 0) {
1760 1
            $conditionalFormattingRuleExtNsPrefix = 'x14';
1761 1
            $objWriter->startElement('extLst');
1762 1
            $objWriter->startElement('ext');
1763 1
            $objWriter->writeAttribute('uri', '{78C0D931-6437-407d-A8EE-F0AAD7539E65}');
1764 1
            $objWriter->startElementNs($conditionalFormattingRuleExtNsPrefix, 'conditionalFormattings', null);
1765 1
            foreach ($conditionalFormattingRuleExtList as $extension) {
1766 1
                self::writeExtConditionalFormattingElements($objWriter, $extension);
1767
            }
1768 1
            $objWriter->endElement(); //end conditionalFormattings
1769 1
            $objWriter->endElement(); //end ext
1770 1
            $objWriter->endElement(); //end extLst
1771
        }
1772
    }
1773
}
1774