Passed
Push — master ( d88efc...653645 )
by
unknown
12:43 queued 21s
created

Worksheet::writeConditionalFormatting()   D

Complexity

Conditions 21
Paths 21

Size

Total Lines 81
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 47
CRAP Score 21

Importance

Changes 0
Metric Value
eloc 51
dl 0
loc 81
ccs 47
cts 47
cp 1
rs 4.1666
c 0
b 0
f 0
cc 21
nc 21
nop 2
crap 21

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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