Failed Conditions
Pull Request — master (#4328)
by Owen
15:26 queued 04:43
created

Worksheet::writeProtectionAttribute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

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