Failed Conditions
Pull Request — master (#4314)
by Owen
11:20
created

Worksheet::writeSheetData()   F

Complexity

Conditions 23
Paths 1564

Size

Total Lines 100
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 48
CRAP Score 23.0338

Importance

Changes 0
Metric Value
eloc 48
dl 0
loc 100
ccs 48
cts 50
cp 0.96
rs 0
c 0
b 0
f 0
cc 23
nc 1564
nop 3
crap 23.0338

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