Passed
Pull Request — master (#4240)
by Owen
27:46 queued 17:34
created

Worksheet::writeCell()   F

Complexity

Conditions 19
Paths 326

Size

Total Lines 67
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 43
CRAP Score 19.0042

Importance

Changes 0
Metric Value
eloc 44
dl 0
loc 67
rs 2.1083
c 0
b 0
f 0
ccs 43
cts 44
cp 0.9773
cc 19
nc 326
nop 4
crap 19.0042

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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