Passed
Pull Request — master (#4283)
by Owen
10:53
created

Worksheet::writeSheetViews()   F

Complexity

Conditions 38
Paths > 20000

Size

Total Lines 153
Code Lines 95

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 90
CRAP Score 38.0147

Importance

Changes 0
Metric Value
eloc 95
c 0
b 0
f 0
dl 0
loc 153
ccs 90
cts 92
cp 0.9783
rs 0
cc 38
nc 9840640
nop 2
crap 38.0147

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 404
    public function writeWorksheet(PhpspreadsheetWorksheet $worksheet, array $stringTable = [], bool $includeCharts = false): string
46
    {
47 404
        $this->useDynamicArrays = $this->getParentWriter()->useDynamicArrays();
48 404
        $this->explicitStyle0 = $this->getParentWriter()->getExplicitStyle0();
49 404
        $worksheet->calculateArrays($this->getParentWriter()->getPreCalculateFormulas());
50 404
        $this->numberStoredAsText = '';
51 404
        $this->formula = '';
52 404
        $this->twoDigitTextYear = '';
53 404
        $this->evalError = '';
54
        // Create XML writer
55 404
        $objWriter = null;
56 404
        if ($this->getParentWriter()->getUseDiskCaching()) {
57
            $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
58
        } else {
59 404
            $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
60
        }
61
62
        // XML header
63 404
        $objWriter->startDocument('1.0', 'UTF-8', 'yes');
64
65
        // Worksheet
66 404
        $objWriter->startElement('worksheet');
67 404
        $objWriter->writeAttribute('xml:space', 'preserve');
68 404
        $objWriter->writeAttribute('xmlns', Namespaces::MAIN);
69 404
        $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT);
70
71 404
        $objWriter->writeAttribute('xmlns:xdr', Namespaces::SPREADSHEET_DRAWING);
72 404
        $objWriter->writeAttribute('xmlns:x14', Namespaces::DATA_VALIDATIONS1);
73 404
        $objWriter->writeAttribute('xmlns:xm', Namespaces::DATA_VALIDATIONS2);
74 404
        $objWriter->writeAttribute('xmlns:mc', Namespaces::COMPATIBILITY);
75 404
        $objWriter->writeAttribute('mc:Ignorable', 'x14ac');
76 404
        $objWriter->writeAttribute('xmlns:x14ac', Namespaces::SPREADSHEETML_AC);
77
78
        // sheetPr
79 404
        $this->writeSheetPr($objWriter, $worksheet);
80
81
        // Dimension
82 404
        $this->writeDimension($objWriter, $worksheet);
83
84
        // sheetViews
85 404
        $this->writeSheetViews($objWriter, $worksheet);
86
87
        // sheetFormatPr
88 404
        $this->writeSheetFormatPr($objWriter, $worksheet);
89
90
        // cols
91 404
        $this->writeCols($objWriter, $worksheet);
92
93
        // sheetData
94 404
        $this->writeSheetData($objWriter, $worksheet, $stringTable);
95
96
        // sheetProtection
97 403
        $this->writeSheetProtection($objWriter, $worksheet);
98
99
        // protectedRanges
100 403
        $this->writeProtectedRanges($objWriter, $worksheet);
101
102
        // autoFilter
103 403
        $this->writeAutoFilter($objWriter, $worksheet);
104
105
        // mergeCells
106 403
        $this->writeMergeCells($objWriter, $worksheet);
107
108
        // conditionalFormatting
109 403
        $this->writeConditionalFormatting($objWriter, $worksheet);
110
111
        // dataValidations
112 403
        $this->writeDataValidations($objWriter, $worksheet);
113
114
        // hyperlinks
115 403
        $this->writeHyperlinks($objWriter, $worksheet);
116
117
        // Print options
118 403
        $this->writePrintOptions($objWriter, $worksheet);
119
120
        // Page margins
121 403
        $this->writePageMargins($objWriter, $worksheet);
122
123
        // Page setup
124 403
        $this->writePageSetup($objWriter, $worksheet);
125
126
        // Header / footer
127 403
        $this->writeHeaderFooter($objWriter, $worksheet);
128
129
        // Breaks
130 403
        $this->writeBreaks($objWriter, $worksheet);
131
132
        // IgnoredErrors
133 403
        $this->writeIgnoredErrors($objWriter);
134
135
        // Drawings and/or Charts
136 403
        $this->writeDrawings($objWriter, $worksheet, $includeCharts);
137
138
        // LegacyDrawing
139 403
        $this->writeLegacyDrawing($objWriter, $worksheet);
140
141
        // LegacyDrawingHF
142 403
        $this->writeLegacyDrawingHF($objWriter, $worksheet);
143
144
        // AlternateContent
145 403
        $this->writeAlternateContent($objWriter, $worksheet);
146
147
        // BackgroundImage must come after ignored, before table
148 403
        $this->writeBackgroundImage($objWriter, $worksheet);
149
150
        // Table
151 403
        $this->writeTable($objWriter, $worksheet);
152
153
        // ConditionalFormattingRuleExtensionList
154
        // (Must be inserted last. Not insert last, an Excel parse error will occur)
155 403
        $this->writeExtLst($objWriter, $worksheet);
156
157 403
        $objWriter->endElement();
158
159
        // Return
160 403
        return $objWriter->getData();
161
    }
162
163 403
    private function writeIgnoredError(XMLWriter $objWriter, bool &$started, string $attr, string $cells): void
164
    {
165 403
        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 403
    private function writeIgnoredErrors(XMLWriter $objWriter): void
178
    {
179 403
        $started = false;
180 403
        $this->writeIgnoredError($objWriter, $started, 'numberStoredAsText', $this->numberStoredAsText);
181 403
        $this->writeIgnoredError($objWriter, $started, 'formula', $this->formula);
182 403
        $this->writeIgnoredError($objWriter, $started, 'twoDigitTextYear', $this->twoDigitTextYear);
183 403
        $this->writeIgnoredError($objWriter, $started, 'evalError', $this->evalError);
184 403
        if ($started) {
185 4
            $objWriter->endElement();
186
        }
187
    }
188
189
    /**
190
     * Write SheetPr.
191
     */
192 404
    private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
193
    {
194
        // sheetPr
195 404
        $objWriter->startElement('sheetPr');
196 404
        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 404
        $autoFilterRange = $worksheet->getAutoFilter()->getRange();
204 404
        if (!empty($autoFilterRange)) {
205 10
            $objWriter->writeAttribute('filterMode', '1');
206 10
            if (!$worksheet->getAutoFilter()->getEvaluated()) {
207 6
                $worksheet->getAutoFilter()->showHideRows();
208
            }
209
        }
210 404
        $tables = $worksheet->getTableCollection();
211 404
        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 404
        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 404
        $objWriter->startElement('outlinePr');
228 404
        $objWriter->writeAttribute('summaryBelow', ($worksheet->getShowSummaryBelow() ? '1' : '0'));
229 404
        $objWriter->writeAttribute('summaryRight', ($worksheet->getShowSummaryRight() ? '1' : '0'));
230 404
        $objWriter->endElement();
231
232
        // pageSetUpPr
233 404
        if ($worksheet->getPageSetup()->getFitToPage()) {
234 5
            $objWriter->startElement('pageSetUpPr');
235 5
            $objWriter->writeAttribute('fitToPage', '1');
236 5
            $objWriter->endElement();
237
        }
238
239 404
        $objWriter->endElement();
240
    }
241
242
    /**
243
     * Write Dimension.
244
     */
245 404
    private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
246
    {
247
        // dimension
248 404
        $objWriter->startElement('dimension');
249 404
        $objWriter->writeAttribute('ref', $worksheet->calculateWorksheetDimension());
250 404
        $objWriter->endElement();
251
    }
252
253
    /**
254
     * Write SheetViews.
255
     */
256 404
    private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
257
    {
258
        // sheetViews
259 404
        $objWriter->startElement('sheetViews');
260
261
        // Sheet selected?
262 404
        $sheetSelected = false;
263 404
        if ($this->getParentWriter()->getSpreadsheet()->getIndex($worksheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) {
264 399
            $sheetSelected = true;
265
        }
266
267
        // sheetView
268 404
        $objWriter->startElement('sheetView');
269 404
        $objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0');
270 404
        $objWriter->writeAttribute('workbookViewId', '0');
271
272
        // Zoom scales
273 404
        $zoomScale = $worksheet->getSheetView()->getZoomScale();
274 404
        if ($zoomScale !== 100 && $zoomScale !== null) {
275 8
            $objWriter->writeAttribute('zoomScale', (string) $zoomScale);
276
        }
277 404
        $zoomScale = $worksheet->getSheetView()->getZoomScaleNormal();
278 404
        if ($zoomScale !== 100 && $zoomScale !== null) {
279 5
            $objWriter->writeAttribute('zoomScaleNormal', (string) $zoomScale);
280
        }
281 404
        $zoomScale = $worksheet->getSheetView()->getZoomScalePageLayoutView();
282 404
        if ($zoomScale !== 100) {
283 4
            $objWriter->writeAttribute('zoomScalePageLayoutView', (string) $zoomScale);
284
        }
285 404
        $zoomScale = $worksheet->getSheetView()->getZoomScaleSheetLayoutView();
286 404
        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 404
        if ($worksheet->getSheetView()->getShowZeros() === false) {
292
            $objWriter->writeAttribute('showZeros', '0');
293
        }
294
295
        // View Layout Type
296 404
        if ($worksheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) {
297 5
            $objWriter->writeAttribute('view', $worksheet->getSheetView()->getView());
298
        }
299
300
        // Gridlines
301 404
        if ($worksheet->getShowGridlines()) {
302 401
            $objWriter->writeAttribute('showGridLines', 'true');
303
        } else {
304 7
            $objWriter->writeAttribute('showGridLines', 'false');
305
        }
306
307
        // Row and column headers
308 404
        if ($worksheet->getShowRowColHeaders()) {
309 404
            $objWriter->writeAttribute('showRowColHeaders', '1');
310
        } else {
311
            $objWriter->writeAttribute('showRowColHeaders', '0');
312
        }
313
314
        // Right-to-left
315 404
        if ($worksheet->getRightToLeft()) {
316 1
            $objWriter->writeAttribute('rightToLeft', 'true');
317
        }
318
319 404
        $topLeftCell = $worksheet->getTopLeftCell();
320 404
        if (!empty($topLeftCell) && $worksheet->getPaneState() !== PhpspreadsheetWorksheet::PANE_FROZEN && $worksheet->getPaneState() !== PhpspreadsheetWorksheet::PANE_FROZENSPLIT) {
321 12
            $objWriter->writeAttribute('topLeftCell', $topLeftCell);
322
        }
323 404
        $activeCell = $worksheet->getActiveCell();
324 404
        $sqref = $worksheet->getSelectedCells();
325
326
        // Pane
327 404
        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 404
        if (!empty($sqref) || !empty($activeCell)) {
396 397
            $objWriter->startElement('selection');
397 397
            if (!empty($activeCell)) {
398 397
                $objWriter->writeAttribute('activeCell', $activeCell);
399
            }
400 397
            if (!empty($sqref)) {
401 397
                $objWriter->writeAttribute('sqref', $sqref);
402
            }
403 397
            $objWriter->endElement(); // selection
404
        }
405
406 404
        $objWriter->endElement();
407
408 404
        $objWriter->endElement();
409
    }
410
411
    /**
412
     * Write SheetFormatPr.
413
     */
414 404
    private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
415
    {
416
        // sheetFormatPr
417 404
        $objWriter->startElement('sheetFormatPr');
418
419
        // Default row height
420 404
        if ($worksheet->getDefaultRowDimension()->getRowHeight() >= 0) {
421 16
            $objWriter->writeAttribute('customHeight', 'true');
422 16
            $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($worksheet->getDefaultRowDimension()->getRowHeight()));
423
        } else {
424 389
            $objWriter->writeAttribute('defaultRowHeight', '14.4');
425
        }
426
427
        // Set Zero Height row
428 404
        if ($worksheet->getDefaultRowDimension()->getZeroHeight()) {
429
            $objWriter->writeAttribute('zeroHeight', '1');
430
        }
431
432
        // Default column width
433 404
        if ($worksheet->getDefaultColumnDimension()->getWidth() >= 0) {
434 26
            $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($worksheet->getDefaultColumnDimension()->getWidth()));
435
        }
436
437
        // Outline level - row
438 404
        $outlineLevelRow = 0;
439 404
        foreach ($worksheet->getRowDimensions() as $dimension) {
440 57
            if ($dimension->getOutlineLevel() > $outlineLevelRow) {
441
                $outlineLevelRow = $dimension->getOutlineLevel();
442
            }
443
        }
444 404
        $objWriter->writeAttribute('outlineLevelRow', (string) (int) $outlineLevelRow);
445
446
        // Outline level - column
447 404
        $outlineLevelCol = 0;
448 404
        foreach ($worksheet->getColumnDimensions() as $dimension) {
449 86
            if ($dimension->getOutlineLevel() > $outlineLevelCol) {
450 1
                $outlineLevelCol = $dimension->getOutlineLevel();
451
            }
452
        }
453 404
        $objWriter->writeAttribute('outlineLevelCol', (string) (int) $outlineLevelCol);
454
455 404
        $objWriter->endElement();
456
    }
457
458
    /**
459
     * Write Cols.
460
     */
461 404
    private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
462
    {
463
        // cols
464 404
        if (count($worksheet->getColumnDimensions()) > 0) {
465 86
            $objWriter->startElement('cols');
466
467 86
            $worksheet->calculateColumnWidths();
468
469
            // Loop through column dimensions
470 86
            foreach ($worksheet->getColumnDimensions() as $colDimension) {
471
                // col
472 86
                $objWriter->startElement('col');
473 86
                $objWriter->writeAttribute('min', (string) Coordinate::columnIndexFromString($colDimension->getColumnIndex()));
474 86
                $objWriter->writeAttribute('max', (string) Coordinate::columnIndexFromString($colDimension->getColumnIndex()));
475
476 86
                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 85
                    $objWriter->writeAttribute('width', StringHelper::formatNumber($colDimension->getWidth()));
482
                }
483
484
                // Column visibility
485 86
                if ($colDimension->getVisible() === false) {
486 7
                    $objWriter->writeAttribute('hidden', 'true');
487
                }
488
489
                // Auto size?
490 86
                if ($colDimension->getAutoSize()) {
491 30
                    $objWriter->writeAttribute('bestFit', 'true');
492
                }
493
494
                // Custom width?
495 86
                if ($colDimension->getWidth() != $worksheet->getDefaultColumnDimension()->getWidth()) {
496 83
                    $objWriter->writeAttribute('customWidth', 'true');
497
                }
498
499
                // Collapsed
500 86
                if ($colDimension->getCollapsed() === true) {
501 1
                    $objWriter->writeAttribute('collapsed', 'true');
502
                }
503
504
                // Outline level
505 86
                if ($colDimension->getOutlineLevel() > 0) {
506 1
                    $objWriter->writeAttribute('outlineLevel', (string) $colDimension->getOutlineLevel());
507
                }
508
509
                // Style
510 86
                $objWriter->writeAttribute('style', (string) $colDimension->getXfIndex());
511
512 86
                $objWriter->endElement();
513
            }
514
515 86
            $objWriter->endElement();
516
        }
517
    }
518
519
    /**
520
     * Write SheetProtection.
521
     */
522 403
    private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
523
    {
524 403
        $protection = $worksheet->getProtection();
525 403
        if (!$protection->isProtectionEnabled()) {
526 380
            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 255
    private static function writeElementIf(XMLWriter $objWriter, bool $condition, string $attr, string $val): void
583
    {
584 255
        if ($condition) {
585 242
            $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 403
    private function writeConditionalFormatting(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
862
    {
863
        // Conditional id
864 403
        $id = 1;
865
866
        // Loop through styles in the current worksheet
867 403
        foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
868 63
            $objWriter->startElement('conditionalFormatting');
869
            // N.B. In Excel UI, intersection is space and union is comma.
870
            // But in Xml, intersection is comma and union is space.
871
            // Anyhow, I don't think Excel handles intersection correctly when reading.
872 63
            $outCoordinate = Coordinate::resolveUnionAndIntersection(str_replace('$', '', $cellCoordinate), ' ');
873 63
            $objWriter->writeAttribute('sqref', $outCoordinate);
874
875 63
            foreach ($conditionalStyles as $conditional) {
876
                // WHY was this again?
877
                // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) == '') {
878
                //    continue;
879
                // }
880
                // cfRule
881 63
                $objWriter->startElement('cfRule');
882 63
                $objWriter->writeAttribute('type', $conditional->getConditionType());
883 63
                self::writeAttributeIf(
884 63
                    $objWriter,
885 63
                    ($conditional->getConditionType() !== Conditional::CONDITION_COLORSCALE
886 63
                        && $conditional->getConditionType() !== Conditional::CONDITION_DATABAR
887 63
                        && $conditional->getNoFormatSet() === false),
888 63
                    'dxfId',
889 63
                    (string) $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode())
890 63
                );
891 63
                $objWriter->writeAttribute('priority', (string) $id++);
892
893 63
                self::writeAttributeif(
894 63
                    $objWriter,
895 63
                    (
896 63
                        $conditional->getConditionType() === Conditional::CONDITION_CELLIS
897 63
                        || $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT
898 63
                        || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT
899 63
                        || $conditional->getConditionType() === Conditional::CONDITION_BEGINSWITH
900 63
                        || $conditional->getConditionType() === Conditional::CONDITION_ENDSWITH
901 63
                    ) && $conditional->getOperatorType() !== Conditional::OPERATOR_NONE,
902 63
                    'operator',
903 63
                    $conditional->getOperatorType()
904 63
                );
905
906 63
                self::writeAttributeIf($objWriter, $conditional->getStopIfTrue(), 'stopIfTrue', '1');
907
908 63
                $cellRange = Coordinate::splitRange(str_replace('$', '', strtoupper($cellCoordinate)));
909 63
                [$topLeftCell] = $cellRange[0];
910
911
                if (
912 63
                    $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT
913 63
                    || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT
914 63
                    || $conditional->getConditionType() === Conditional::CONDITION_BEGINSWITH
915 63
                    || $conditional->getConditionType() === Conditional::CONDITION_ENDSWITH
916
                ) {
917 9
                    self::writeTextCondElements($objWriter, $conditional, $topLeftCell);
918 56
                } elseif ($conditional->getConditionType() === Conditional::CONDITION_TIMEPERIOD) {
919 12
                    self::writeTimePeriodCondElements($objWriter, $conditional, $topLeftCell);
920 44
                } elseif ($conditional->getConditionType() === Conditional::CONDITION_COLORSCALE) {
921 3
                    self::writeColorScaleElements($objWriter, $conditional->getColorScale());
922
                } else {
923 41
                    self::writeOtherCondElements($objWriter, $conditional, $topLeftCell);
924
                }
925
926
                //<dataBar>
927 63
                self::writeDataBarElements($objWriter, $conditional->getDataBar());
928
929 63
                $objWriter->endElement(); //end cfRule
930
            }
931
932 63
            $objWriter->endElement(); //end conditionalFormatting
933
        }
934
    }
935
936
    /**
937
     * Write DataValidations.
938
     */
939 403
    private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
940
    {
941
        // Datavalidation collection
942 403
        $dataValidationCollection = $worksheet->getDataValidationCollection();
943
944
        // Write data validations?
945 403
        if (!empty($dataValidationCollection)) {
946 11
            $dataValidationCollection = Coordinate::mergeRangesInCollection($dataValidationCollection);
947 11
            $objWriter->startElement('dataValidations');
948 11
            $objWriter->writeAttribute('count', (string) count($dataValidationCollection));
949
950 11
            foreach ($dataValidationCollection as $coordinate => $dv) {
951 11
                $objWriter->startElement('dataValidation');
952
953 11
                if ($dv->getType() != '') {
954 11
                    $objWriter->writeAttribute('type', $dv->getType());
955
                }
956
957 11
                if ($dv->getErrorStyle() != '') {
958 6
                    $objWriter->writeAttribute('errorStyle', $dv->getErrorStyle());
959
                }
960
961 11
                if ($dv->getOperator() != '') {
962 11
                    $objWriter->writeAttribute('operator', $dv->getOperator());
963
                }
964
965 11
                $objWriter->writeAttribute('allowBlank', ($dv->getAllowBlank() ? '1' : '0'));
966 11
                $objWriter->writeAttribute('showDropDown', (!$dv->getShowDropDown() ? '1' : '0'));
967 11
                $objWriter->writeAttribute('showInputMessage', ($dv->getShowInputMessage() ? '1' : '0'));
968 11
                $objWriter->writeAttribute('showErrorMessage', ($dv->getShowErrorMessage() ? '1' : '0'));
969
970 11
                if ($dv->getErrorTitle() !== '') {
971 4
                    $objWriter->writeAttribute('errorTitle', $dv->getErrorTitle());
972
                }
973 11
                if ($dv->getError() !== '') {
974 6
                    $objWriter->writeAttribute('error', $dv->getError());
975
                }
976 11
                if ($dv->getPromptTitle() !== '') {
977 6
                    $objWriter->writeAttribute('promptTitle', $dv->getPromptTitle());
978
                }
979 11
                if ($dv->getPrompt() !== '') {
980 5
                    $objWriter->writeAttribute('prompt', $dv->getPrompt());
981
                }
982
983 11
                $objWriter->writeAttribute('sqref', $dv->getSqref() ?? $coordinate);
984
985 11
                if ($dv->getFormula1() !== '') {
986 11
                    $objWriter->writeElement('formula1', FunctionPrefix::addFunctionPrefix($dv->getFormula1()));
987
                }
988 11
                if ($dv->getFormula2() !== '') {
989 3
                    $objWriter->writeElement('formula2', FunctionPrefix::addFunctionPrefix($dv->getFormula2()));
990
                }
991
992 11
                $objWriter->endElement();
993
            }
994
995 11
            $objWriter->endElement();
996
        }
997
    }
998
999
    /**
1000
     * Write Hyperlinks.
1001
     */
1002 403
    private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1003
    {
1004
        // Hyperlink collection
1005 403
        $hyperlinkCollection = $worksheet->getHyperlinkCollection();
1006
1007
        // Relation ID
1008 403
        $relationId = 1;
1009
1010
        // Write hyperlinks?
1011 403
        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 403
    private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1041
    {
1042 403
        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 403
    private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1067
    {
1068 403
        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 403
    private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1088
    {
1089
        // printOptions
1090 403
        $objWriter->startElement('printOptions');
1091
1092 403
        $objWriter->writeAttribute('gridLines', ($worksheet->getPrintGridlines() ? 'true' : 'false'));
1093 403
        $objWriter->writeAttribute('gridLinesSet', 'true');
1094
1095 403
        if ($worksheet->getPageSetup()->getHorizontalCentered()) {
1096 3
            $objWriter->writeAttribute('horizontalCentered', 'true');
1097
        }
1098
1099 403
        if ($worksheet->getPageSetup()->getVerticalCentered()) {
1100 2
            $objWriter->writeAttribute('verticalCentered', 'true');
1101
        }
1102
1103 403
        $objWriter->endElement();
1104
    }
1105
1106
    /**
1107
     * Write PageMargins.
1108
     */
1109 403
    private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1110
    {
1111
        // pageMargins
1112 403
        $objWriter->startElement('pageMargins');
1113 403
        $objWriter->writeAttribute('left', StringHelper::formatNumber($worksheet->getPageMargins()->getLeft()));
1114 403
        $objWriter->writeAttribute('right', StringHelper::formatNumber($worksheet->getPageMargins()->getRight()));
1115 403
        $objWriter->writeAttribute('top', StringHelper::formatNumber($worksheet->getPageMargins()->getTop()));
1116 403
        $objWriter->writeAttribute('bottom', StringHelper::formatNumber($worksheet->getPageMargins()->getBottom()));
1117 403
        $objWriter->writeAttribute('header', StringHelper::formatNumber($worksheet->getPageMargins()->getHeader()));
1118 403
        $objWriter->writeAttribute('footer', StringHelper::formatNumber($worksheet->getPageMargins()->getFooter()));
1119 403
        $objWriter->endElement();
1120
    }
1121
1122
    /**
1123
     * Write AutoFilter.
1124
     */
1125 403
    private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1126
    {
1127 403
        AutoFilter::writeAutoFilter($objWriter, $worksheet);
1128
    }
1129
1130
    /**
1131
     * Write Table.
1132
     */
1133 403
    private function writeTable(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1134
    {
1135 403
        $tableCount = $worksheet->getTableCollection()->count();
1136 403
        if ($tableCount === 0) {
1137 396
            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 403
    private function writeBackgroundImage(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1156
    {
1157 403
        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 403
    private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1168
    {
1169
        // pageSetup
1170 403
        $objWriter->startElement('pageSetup');
1171 403
        $objWriter->writeAttribute('paperSize', (string) $worksheet->getPageSetup()->getPaperSize());
1172 403
        $objWriter->writeAttribute('orientation', $worksheet->getPageSetup()->getOrientation());
1173
1174 403
        if ($worksheet->getPageSetup()->getScale() !== null) {
1175 403
            $objWriter->writeAttribute('scale', (string) $worksheet->getPageSetup()->getScale());
1176
        }
1177 403
        if ($worksheet->getPageSetup()->getFitToHeight() !== null) {
1178 403
            $objWriter->writeAttribute('fitToHeight', (string) $worksheet->getPageSetup()->getFitToHeight());
1179
        } else {
1180
            $objWriter->writeAttribute('fitToHeight', '0');
1181
        }
1182 403
        if ($worksheet->getPageSetup()->getFitToWidth() !== null) {
1183 403
            $objWriter->writeAttribute('fitToWidth', (string) $worksheet->getPageSetup()->getFitToWidth());
1184
        } else {
1185
            $objWriter->writeAttribute('fitToWidth', '0');
1186
        }
1187 403
        if (!empty($worksheet->getPageSetup()->getFirstPageNumber())) {
1188 1
            $objWriter->writeAttribute('firstPageNumber', (string) $worksheet->getPageSetup()->getFirstPageNumber());
1189 1
            $objWriter->writeAttribute('useFirstPageNumber', '1');
1190
        }
1191 403
        $objWriter->writeAttribute('pageOrder', $worksheet->getPageSetup()->getPageOrder());
1192
1193 403
        $getUnparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData();
1194 403
        if (isset($getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'])) {
1195 36
            $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId']);
1196
        }
1197
1198 403
        $objWriter->endElement();
1199
    }
1200
1201
    /**
1202
     * Write Header / Footer.
1203
     */
1204 403
    private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1205
    {
1206
        // headerFooter
1207 403
        $headerFooter = $worksheet->getHeaderFooter();
1208 403
        $oddHeader = $headerFooter->getOddHeader();
1209 403
        $oddFooter = $headerFooter->getOddFooter();
1210 403
        $evenHeader = $headerFooter->getEvenHeader();
1211 403
        $evenFooter = $headerFooter->getEvenFooter();
1212 403
        $firstHeader = $headerFooter->getFirstHeader();
1213 403
        $firstFooter = $headerFooter->getFirstFooter();
1214 403
        if ("$oddHeader$oddFooter$evenHeader$evenFooter$firstHeader$firstFooter" === '') {
1215 393
            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 403
    private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1238
    {
1239
        // Get row and column breaks
1240 403
        $aRowBreaks = [];
1241 403
        $aColumnBreaks = [];
1242 403
        foreach ($worksheet->getRowBreaks() as $cell => $break) {
1243 7
            $aRowBreaks[$cell] = $break;
1244
        }
1245 403
        foreach ($worksheet->getColumnBreaks() as $cell => $break) {
1246 1
            $aColumnBreaks[$cell] = $break;
1247
        }
1248
1249
        // rowBreaks
1250 403
        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 403
        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 404
    private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, array $stringTable): void
1296
    {
1297
        // Flipped stringtable, for faster index searching
1298 404
        $aFlippedStringTable = $this->getParentWriter()->getWriterPartstringtable()->flipStringTable($stringTable);
1299
1300
        // sheetData
1301 404
        $objWriter->startElement('sheetData');
1302
1303
        // Get column count
1304 404
        $colCount = Coordinate::columnIndexFromString($worksheet->getHighestColumn());
1305
1306
        // Highest row number
1307 404
        $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 404
        $cellsByRow = [];
1314 404
        foreach ($worksheet->getCoordinates() as $coordinate) {
1315 351
            [$column, $row] = Coordinate::coordinateFromString($coordinate);
1316 351
            $cellsByRow[$row] = $cellsByRow[$row] ?? '';
1317 351
            $cellsByRow[$row] .= "{$column},";
1318
        }
1319
1320 404
        $currentRow = 0;
1321 404
        $emptyDimension = new RowDimension();
1322 404
        while ($currentRow++ < $highestRow) {
1323 404
            $isRowSet = isset($cellsByRow[$currentRow]);
1324 404
            if ($isRowSet || $worksheet->rowDimensionExists($currentRow)) {
1325
                // Get row dimension
1326 351
                $rowDimension = $worksheet->rowDimensionExists($currentRow) ? $worksheet->getRowDimension($currentRow) : $emptyDimension;
1327
1328
                // Write current row?
1329 351
                $writeCurrentRow = $isRowSet || $rowDimension->getRowHeight() >= 0 || $rowDimension->getVisible() === false || $rowDimension->getCollapsed() === true || $rowDimension->getOutlineLevel() > 0 || $rowDimension->getXfIndex() !== null;
1330
1331 351
                if ($writeCurrentRow) {
1332
                    // Start a new row
1333 351
                    $objWriter->startElement('row');
1334 351
                    $objWriter->writeAttribute('r', "$currentRow");
1335 351
                    $objWriter->writeAttribute('spans', '1:' . $colCount);
1336
1337
                    // Row dimensions
1338 351
                    if ($rowDimension->getRowHeight() >= 0) {
1339 33
                        $objWriter->writeAttribute('customHeight', '1');
1340 33
                        $objWriter->writeAttribute('ht', StringHelper::formatNumber($rowDimension->getRowHeight()));
1341
                    }
1342
1343
                    // Row visibility
1344 351
                    if (!$rowDimension->getVisible() === true) {
1345 16
                        $objWriter->writeAttribute('hidden', 'true');
1346
                    }
1347
1348
                    // Collapsed
1349 351
                    if ($rowDimension->getCollapsed() === true) {
1350
                        $objWriter->writeAttribute('collapsed', 'true');
1351
                    }
1352
1353
                    // Outline level
1354 351
                    if ($rowDimension->getOutlineLevel() > 0) {
1355
                        $objWriter->writeAttribute('outlineLevel', (string) $rowDimension->getOutlineLevel());
1356
                    }
1357
1358
                    // Style
1359 351
                    if ($rowDimension->getXfIndex() !== null) {
1360 8
                        $objWriter->writeAttribute('s', (string) $rowDimension->getXfIndex());
1361 8
                        $objWriter->writeAttribute('customFormat', '1');
1362
                    }
1363
1364
                    // Write cells
1365 351
                    if (isset($cellsByRow[$currentRow])) {
1366
                        // We have a comma-separated list of column names (with a trailing entry); split to an array
1367 351
                        $columnsInRow = explode(',', $cellsByRow[$currentRow]);
1368 351
                        array_pop($columnsInRow);
1369 351
                        foreach ($columnsInRow as $column) {
1370
                            // Write cell
1371 351
                            $coord = "$column$currentRow";
1372 351
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getNumberStoredAsText()) {
1373 4
                                $this->numberStoredAsText .= " $coord";
1374
                            }
1375 351
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getFormula()) {
1376 1
                                $this->formula .= " $coord";
1377
                            }
1378 351
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getTwoDigitTextYear()) {
1379 1
                                $this->twoDigitTextYear .= " $coord";
1380
                            }
1381 351
                            if ($worksheet->getCell($coord)->getIgnoredErrors()->getEvalError()) {
1382 1
                                $this->evalError .= " $coord";
1383
                            }
1384 351
                            $this->writeCell($objWriter, $worksheet, $coord, $aFlippedStringTable);
1385
                        }
1386
                    }
1387
1388
                    // End row
1389 350
                    $objWriter->endElement();
1390
                }
1391
            }
1392
        }
1393
1394 403
        $objWriter->endElement();
1395
    }
1396
1397 10
    private function writeCellInlineStr(XMLWriter $objWriter, string $mappedType, RichText|string $cellValue): void
1398
    {
1399 10
        $objWriter->writeAttribute('t', $mappedType);
1400 10
        if (!$cellValue instanceof RichText) {
1401 1
            $objWriter->startElement('is');
1402 1
            $objWriter->writeElement(
1403 1
                't',
1404 1
                StringHelper::controlCharacterPHP2OOXML(htmlspecialchars($cellValue, Settings::htmlEntityFlags()))
1405 1
            );
1406 1
            $objWriter->endElement();
1407
        } else {
1408 10
            $objWriter->startElement('is');
1409 10
            $this->getParentWriter()->getWriterPartstringtable()->writeRichText($objWriter, $cellValue);
1410 10
            $objWriter->endElement();
1411
        }
1412
    }
1413
1414
    /**
1415
     * @param string[] $flippedStringTable
1416
     */
1417 236
    private function writeCellString(XMLWriter $objWriter, string $mappedType, RichText|string $cellValue, array $flippedStringTable): void
1418
    {
1419 236
        $objWriter->writeAttribute('t', $mappedType);
1420 236
        if (!$cellValue instanceof RichText) {
1421 235
            self::writeElementIf($objWriter, isset($flippedStringTable[$cellValue]), 'v', $flippedStringTable[$cellValue] ?? '');
1422
        } else {
1423 9
            $objWriter->writeElement('v', $flippedStringTable[$cellValue->getHashCode()]);
1424
        }
1425
    }
1426
1427 220
    private function writeCellNumeric(XMLWriter $objWriter, float|int $cellValue): void
1428
    {
1429
        //force a decimal to be written if the type is float
1430 220
        if (is_float($cellValue)) {
1431
            // force point as decimal separator in case current locale uses comma
1432 68
            $cellValue = str_replace(',', '.', (string) $cellValue);
1433 68
            if (!str_contains($cellValue, '.')) {
1434 29
                $cellValue = $cellValue . '.0';
1435
            }
1436
        }
1437 220
        $objWriter->writeElement('v', "$cellValue");
1438
    }
1439
1440 14
    private function writeCellBoolean(XMLWriter $objWriter, string $mappedType, bool $cellValue): void
1441
    {
1442 14
        $objWriter->writeAttribute('t', $mappedType);
1443 14
        $objWriter->writeElement('v', $cellValue ? '1' : '0');
1444
    }
1445
1446 11
    private function writeCellError(XMLWriter $objWriter, string $mappedType, string $cellValue, string $formulaerr = '#NULL!'): void
1447
    {
1448 11
        $objWriter->writeAttribute('t', $mappedType);
1449 11
        $cellIsFormula = str_starts_with($cellValue, '=');
1450 11
        self::writeElementIf($objWriter, $cellIsFormula, 'f', FunctionPrefix::addFunctionPrefixStripEquals($cellValue));
1451 11
        $objWriter->writeElement('v', $cellIsFormula ? $formulaerr : $cellValue);
1452
    }
1453
1454 106
    private function writeCellFormula(XMLWriter $objWriter, string $cellValue, Cell $cell): void
1455
    {
1456 106
        $attributes = $cell->getFormulaAttributes() ?? [];
1457 106
        $coordinate = $cell->getCoordinate();
1458 106
        $calculatedValue = $this->getParentWriter()->getPreCalculateFormulas() ? $cell->getCalculatedValue() : $cellValue;
1459 105
        if ($calculatedValue === ExcelError::SPILL()) {
1460 1
            $objWriter->writeAttribute('t', 'e');
1461
            //$objWriter->writeAttribute('cm', '1'); // already added
1462 1
            $objWriter->writeAttribute('vm', '1');
1463 1
            $objWriter->startElement('f');
1464 1
            $objWriter->writeAttribute('t', 'array');
1465 1
            $objWriter->writeAttribute('aca', '1');
1466 1
            $objWriter->writeAttribute('ref', $coordinate);
1467 1
            $objWriter->writeAttribute('ca', '1');
1468 1
            $objWriter->text(FunctionPrefix::addFunctionPrefixStripEquals($cellValue));
1469 1
            $objWriter->endElement(); // f
1470 1
            $objWriter->writeElement('v', ExcelError::VALUE()); // note #VALUE! in xml even though error is #SPILL!
1471
1472 1
            return;
1473
        }
1474 104
        $calculatedValueString = $this->getParentWriter()->getPreCalculateFormulas() ? $cell->getCalculatedValueString() : $cellValue;
1475 104
        $result = $calculatedValue;
1476 104
        while (is_array($result)) {
1477 7
            $result = array_shift($result);
1478
        }
1479 104
        if (is_string($result)) {
1480 42
            if (ErrorValue::isError($result)) {
1481 10
                $this->writeCellError($objWriter, 'e', $cellValue, $result);
1482
1483 10
                return;
1484
            }
1485 41
            $objWriter->writeAttribute('t', 'str');
1486 41
            $result = $calculatedValueString = StringHelper::controlCharacterPHP2OOXML($result);
1487 41
            if (is_string($calculatedValue)) {
1488 40
                $calculatedValue = $calculatedValueString;
1489
            }
1490 83
        } elseif (is_bool($result)) {
1491 8
            $objWriter->writeAttribute('t', 'b');
1492 8
            if (is_bool($calculatedValue)) {
1493 8
                $calculatedValue = $result;
1494
            }
1495 8
            $result = (int) $result;
1496 8
            $calculatedValueString = (string) $result;
1497
        }
1498
1499 104
        if (isset($attributes['ref'])) {
1500 24
            $ref = $this->parseRef($coordinate, $attributes['ref']);
1501
        } else {
1502 95
            $ref = $coordinate;
1503
        }
1504 104
        if (is_array($calculatedValue)) {
1505 7
            $attributes['t'] = 'array';
1506
        }
1507 104
        if (($attributes['t'] ?? null) === 'array') {
1508 11
            $objWriter->startElement('f');
1509 11
            $objWriter->writeAttribute('t', 'array');
1510 11
            $objWriter->writeAttribute('ref', $ref);
1511 11
            $objWriter->writeAttribute('aca', '1');
1512 11
            $objWriter->writeAttribute('ca', '1');
1513 11
            $objWriter->text(FunctionPrefix::addFunctionPrefixStripEquals($cellValue));
1514 11
            $objWriter->endElement();
1515
            if (
1516 11
                is_scalar($result)
1517 11
                && $this->getParentWriter()->getOffice2003Compatibility() === false
1518 11
                && $this->getParentWriter()->getPreCalculateFormulas()
1519
            ) {
1520 11
                $objWriter->writeElement('v', (string) $result);
1521
            }
1522
        } else {
1523 93
            $objWriter->writeElement('f', FunctionPrefix::addFunctionPrefixStripEquals($cellValue));
1524 93
            self::writeElementIf(
1525 93
                $objWriter,
1526 93
                $this->getParentWriter()->getOffice2003Compatibility() === false
1527 93
                && $this->getParentWriter()->getPreCalculateFormulas()
1528 93
                && $calculatedValue !== null,
1529 93
                'v',
1530 93
                (!is_array($calculatedValue) && !str_starts_with($calculatedValueString, '#'))
1531 93
                    ? StringHelper::formatNumber($calculatedValueString) : '0'
1532 93
            );
1533
        }
1534
    }
1535
1536 24
    private function parseRef(string $coordinate, string $ref): string
1537
    {
1538 24
        if (preg_match('/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/', $ref, $matches) !== 1) {
1539
            return $ref;
1540
        }
1541 24
        if (!isset($matches[3])) { // single cell, not range
1542 1
            return $coordinate;
1543
        }
1544 24
        $minRow = (int) $matches[2];
1545
        // https://github.com/phpstan/phpstan/issues/11602
1546 24
        $maxRow = (int) $matches[5]; // @phpstan-ignore-line
1547 24
        $rows = $maxRow - $minRow + 1;
1548 24
        $minCol = Coordinate::columnIndexFromString($matches[1]);
1549 24
        $maxCol = Coordinate::columnIndexFromString($matches[4]); // @phpstan-ignore-line
1550 24
        $cols = $maxCol - $minCol + 1;
1551 24
        $firstCellArray = Coordinate::indexesFromString($coordinate);
1552 24
        $lastRow = $firstCellArray[1] + $rows - 1;
1553 24
        $lastColumn = $firstCellArray[0] + $cols - 1;
1554 24
        $lastColumnString = Coordinate::stringFromColumnIndex($lastColumn);
1555
1556 24
        return "$coordinate:$lastColumnString$lastRow";
1557
    }
1558
1559
    /**
1560
     * Write Cell.
1561
     *
1562
     * @param string $cellAddress Cell Address
1563
     * @param string[] $flippedStringTable String table (flipped), for faster index searching
1564
     */
1565 351
    private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, string $cellAddress, array $flippedStringTable): void
1566
    {
1567
        // Cell
1568 351
        $pCell = $worksheet->getCell($cellAddress);
1569 351
        $xfi = $pCell->getXfIndex();
1570 351
        $cellValue = $pCell->getValue();
1571 351
        $cellValueString = $pCell->getValueString();
1572 351
        $writeValue = $cellValue !== '' && $cellValue !== null;
1573 351
        if (empty($xfi) && !$writeValue) {
1574 63
            return;
1575
        }
1576 334
        $objWriter->startElement('c');
1577 334
        $objWriter->writeAttribute('r', $cellAddress);
1578 334
        $mappedType = $pCell->getDataType();
1579 334
        if ($mappedType === DataType::TYPE_FORMULA) {
1580 106
            if ($this->useDynamicArrays) {
1581 7
                if (preg_match(PhpspreadsheetWorksheet::FUNCTION_LIKE_GROUPBY, $cellValue) === 1) {
1582
                    $tempCalc = [];
1583
                } else {
1584 7
                    $tempCalc = $pCell->getCalculatedValue();
1585
                }
1586 7
                if (is_array($tempCalc)) {
1587 6
                    $objWriter->writeAttribute('cm', '1');
1588
                }
1589
            }
1590
        }
1591
1592
        // Sheet styles
1593 334
        if ($xfi) {
1594 117
            $objWriter->writeAttribute('s', "$xfi");
1595 306
        } elseif ($this->explicitStyle0) {
1596 1
            $objWriter->writeAttribute('s', '0');
1597
        }
1598
1599
        // If cell value is supplied, write cell value
1600 334
        if ($writeValue) {
1601
            // Write data depending on its type
1602 328
            switch (strtolower($mappedType)) {
1603 328
                case 'inlinestr':    // Inline string
1604
                    /** @var RichText|string */
1605 10
                    $richText = $cellValue;
1606 10
                    $this->writeCellInlineStr($objWriter, $mappedType, $richText);
1607
1608 10
                    break;
1609 326
                case 's':            // String
1610 236
                    $this->writeCellString($objWriter, $mappedType, ($cellValue instanceof RichText) ? $cellValue : $cellValueString, $flippedStringTable);
1611
1612 236
                    break;
1613 251
                case 'f':            // Formula
1614 106
                    $this->writeCellFormula($objWriter, $cellValueString, $pCell);
1615
1616 105
                    break;
1617 224
                case 'n':            // Numeric
1618 220
                    $cellValueNumeric = is_numeric($cellValue) ? ($cellValue + 0) : 0;
1619 220
                    $this->writeCellNumeric($objWriter, $cellValueNumeric);
1620
1621 220
                    break;
1622 14
                case 'b':            // Boolean
1623 14
                    $this->writeCellBoolean($objWriter, $mappedType, (bool) $cellValue);
1624
1625 14
                    break;
1626 1
                case 'e':            // Error
1627 1
                    $this->writeCellError($objWriter, $mappedType, $cellValueString);
1628
            }
1629
        }
1630
1631 333
        $objWriter->endElement(); // c
1632
    }
1633
1634
    /**
1635
     * Write Drawings.
1636
     *
1637
     * @param bool $includeCharts Flag indicating if we should include drawing details for charts
1638
     */
1639 403
    private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, bool $includeCharts = false): void
1640
    {
1641 403
        $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData();
1642 403
        $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']);
1643 403
        $chartCount = ($includeCharts) ? $worksheet->getChartCollection()->count() : 0;
1644 403
        if ($chartCount == 0 && $worksheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) {
1645 296
            return;
1646
        }
1647
1648
        // If sheet contains drawings, add the relationships
1649 126
        $objWriter->startElement('drawing');
1650
1651 126
        $rId = 'rId1';
1652 126
        if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) {
1653 49
            $drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'];
1654
            // take first. In future can be overriten
1655
            // (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels::writeWorksheetRelationships)
1656 49
            $rId = reset($drawingOriginalIds);
1657
        }
1658
1659 126
        $objWriter->writeAttribute('r:id', $rId);
1660 126
        $objWriter->endElement();
1661
    }
1662
1663
    /**
1664
     * Write LegacyDrawing.
1665
     */
1666 403
    private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1667
    {
1668
        // If sheet contains comments, add the relationships
1669 403
        $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData();
1670 403
        if (count($worksheet->getComments()) > 0 || isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing'])) {
1671 28
            $objWriter->startElement('legacyDrawing');
1672 28
            $objWriter->writeAttribute('r:id', 'rId_comments_vml1');
1673 28
            $objWriter->endElement();
1674
        }
1675
    }
1676
1677
    /**
1678
     * Write LegacyDrawingHF.
1679
     */
1680 403
    private function writeLegacyDrawingHF(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1681
    {
1682
        // If sheet contains images, add the relationships
1683 403
        if (count($worksheet->getHeaderFooter()->getImages()) > 0) {
1684 3
            $objWriter->startElement('legacyDrawingHF');
1685 3
            $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1');
1686 3
            $objWriter->endElement();
1687
        }
1688
    }
1689
1690 403
    private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1691
    {
1692 403
        if (empty($worksheet->getParentOrThrow()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'])) {
1693 402
            return;
1694
        }
1695
1696 4
        foreach ($worksheet->getParentOrThrow()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'] as $alternateContent) {
1697 4
            $objWriter->writeRaw($alternateContent);
1698
        }
1699
    }
1700
1701
    /**
1702
     * write <ExtLst>
1703
     * only implementation conditionalFormattings.
1704
     *
1705
     * @url https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627
1706
     */
1707 403
    private function writeExtLst(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
1708
    {
1709 403
        $conditionalFormattingRuleExtList = [];
1710 403
        foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
1711
            /** @var Conditional $conditional */
1712 63
            foreach ($conditionalStyles as $conditional) {
1713 63
                $dataBar = $conditional->getDataBar();
1714 63
                if ($dataBar && $dataBar->getConditionalFormattingRuleExt()) {
1715 1
                    $conditionalFormattingRuleExtList[] = $dataBar->getConditionalFormattingRuleExt();
1716
                }
1717
            }
1718
        }
1719
1720 403
        if (count($conditionalFormattingRuleExtList) > 0) {
1721 1
            $conditionalFormattingRuleExtNsPrefix = 'x14';
1722 1
            $objWriter->startElement('extLst');
1723 1
            $objWriter->startElement('ext');
1724 1
            $objWriter->writeAttribute('uri', '{78C0D931-6437-407d-A8EE-F0AAD7539E65}');
1725 1
            $objWriter->startElementNs($conditionalFormattingRuleExtNsPrefix, 'conditionalFormattings', null);
1726 1
            foreach ($conditionalFormattingRuleExtList as $extension) {
1727 1
                self::writeExtConditionalFormattingElements($objWriter, $extension);
1728
            }
1729 1
            $objWriter->endElement(); //end conditionalFormattings
1730 1
            $objWriter->endElement(); //end ext
1731 1
            $objWriter->endElement(); //end extLst
1732
        }
1733
    }
1734
}
1735