• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PHPOffice / PhpSpreadsheet / 19356117742

14 Nov 2025 06:14AM UTC coverage: 95.959% (+0.005%) from 95.954%
19356117742

Pull #4711

github

web-flow
Merge 8108c12c3 into dcf475eec
Pull Request #4711: Limited PrintArea Support for Html/Pdf

56 of 57 new or added lines in 2 files covered. (98.25%)

8 existing lines in 1 file now uncovered.

45449 of 47363 relevant lines covered (95.96%)

373.76 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

99.14
/src/PhpSpreadsheet/Writer/Html.php
1
<?php
2

3
namespace PhpOffice\PhpSpreadsheet\Writer;
4

5
use Composer\Pcre\Preg;
6
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
7
use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalculationException;
8
use PhpOffice\PhpSpreadsheet\Cell\Cell;
9
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
10
use PhpOffice\PhpSpreadsheet\Cell\DataType;
11
use PhpOffice\PhpSpreadsheet\Chart\Chart;
12
use PhpOffice\PhpSpreadsheet\Comment;
13
use PhpOffice\PhpSpreadsheet\Document\Properties;
14
use PhpOffice\PhpSpreadsheet\RichText\RichText;
15
use PhpOffice\PhpSpreadsheet\RichText\Run;
16
use PhpOffice\PhpSpreadsheet\Settings;
17
use PhpOffice\PhpSpreadsheet\Shared\Date;
18
use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing;
19
use PhpOffice\PhpSpreadsheet\Shared\File;
20
use PhpOffice\PhpSpreadsheet\Shared\Font as SharedFont;
21
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
22
use PhpOffice\PhpSpreadsheet\Spreadsheet;
23
use PhpOffice\PhpSpreadsheet\Style\Alignment;
24
use PhpOffice\PhpSpreadsheet\Style\Border;
25
use PhpOffice\PhpSpreadsheet\Style\Borders;
26
use PhpOffice\PhpSpreadsheet\Style\Conditional;
27
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\CellStyleAssessor;
28
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\StyleMerger;
29
use PhpOffice\PhpSpreadsheet\Style\Fill;
30
use PhpOffice\PhpSpreadsheet\Style\Font;
31
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
32
use PhpOffice\PhpSpreadsheet\Style\Style;
33
use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing;
34
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
35
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
36
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
37
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
38
use PhpOffice\PhpSpreadsheet\Worksheet\Table\TableDxfsStyle;
39
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
40

41
class Html extends BaseWriter
42
{
43
    private const DEFAULT_CELL_WIDTH_POINTS = 42;
44

45
    private const DEFAULT_CELL_WIDTH_PIXELS = 56;
46

47
    /**
48
     * Migration aid to tell if html tags will be treated as plaintext in comments.
49
     *     if (
50
     *         defined(
51
     *             \PhpOffice\PhpSpreadsheet\Writer\Html::class
52
     *             . '::COMMENT_HTML_TAGS_PLAINTEXT'
53
     *         )
54
     *     ) {
55
     *         new logic with styling in TextRun elements
56
     *     } else {
57
     *         old logic with styling via Html tags
58
     *     }.
59
     */
60
    public const COMMENT_HTML_TAGS_PLAINTEXT = true;
61

62
    /**
63
     * Spreadsheet object.
64
     */
65
    protected Spreadsheet $spreadsheet;
66

67
    /**
68
     * Sheet index to write.
69
     */
70
    private ?int $sheetIndex = 0;
71

72
    /**
73
     * Images root.
74
     */
75
    private string $imagesRoot = '';
76

77
    /**
78
     * embed images, or link to images.
79
     */
80
    protected bool $embedImages = false;
81

82
    /**
83
     * Use inline CSS?
84
     */
85
    private bool $useInlineCss = false;
86

87
    /**
88
     * Array of CSS styles.
89
     *
90
     * @var string[][]
91
     */
92
    private ?array $cssStyles = null;
93

94
    /**
95
     * Array of column widths in points.
96
     *
97
     * @var array<array<float|int>>
98
     */
99
    private array $columnWidths;
100

101
    /**
102
     * Default font.
103
     */
104
    private Font $defaultFont;
105

106
    /**
107
     * Flag whether spans have been calculated.
108
     */
109
    private bool $spansAreCalculated = false;
110

111
    /**
112
     * Excel cells that should not be written as HTML cells.
113
     *
114
     * @var mixed[][][][]
115
     */
116
    private array $isSpannedCell = [];
117

118
    /**
119
     * Excel cells that are upper-left corner in a cell merge.
120
     *
121
     * @var int[][][][]
122
     */
123
    private array $isBaseCell = [];
124

125
    /**
126
     * Excel rows that should not be written as HTML rows.
127
     *
128
     * @var mixed[][]
129
     */
130
    private array $isSpannedRow = [];
131

132
    /**
133
     * Is the current writer creating PDF?
134
     */
135
    protected bool $isPdf = false;
136

137
    /**
138
     * Generate the Navigation block.
139
     */
140
    private bool $generateSheetNavigationBlock = true;
141

142
    /**
143
     * Callback for editing generated html.
144
     *
145
     * @var null|callable(string): string
146
     */
147
    private $editHtmlCallback;
148

149
    /** @var BaseDrawing[] */
150
    private $sheetDrawings;
151

152
    /** @var Chart[] */
153
    private $sheetCharts;
154

155
    private bool $betterBoolean = true;
156

157
    private string $getTrue = 'TRUE';
158

159
    private string $getFalse = 'FALSE';
160

161
    protected bool $rtlSheets = false;
162

163
    protected bool $ltrSheets = false;
164

165
    /**
166
     * Table formats
167
     * Enables table formats in writer, disabled here, must be enabled in writer via a setter.
168
     */
169
    protected bool $tableFormats = false;
170

171
    /**
172
     * Conditional Formatting
173
     * Enables conditional formatting in writer, disabled here, must be enabled in writer via a setter.
174
     */
175
    protected bool $conditionalFormatting = false;
176

177
    /**
178
     * Create a new HTML.
179
     */
180
    public function __construct(Spreadsheet $spreadsheet)
571✔
181
    {
182
        $this->spreadsheet = $spreadsheet;
571✔
183
        $this->defaultFont = $this->spreadsheet->getDefaultStyle()->getFont();
571✔
184
        $calc = Calculation::getInstance($this->spreadsheet);
571✔
185
        $this->getTrue = $calc->getTRUE();
571✔
186
        $this->getFalse = $calc->getFALSE();
571✔
187
    }
188

189
    /**
190
     * Save Spreadsheet to file.
191
     *
192
     * @param resource|string $filename
193
     */
194
    public function save($filename, int $flags = 0): void
468✔
195
    {
196
        $this->processFlags($flags);
468✔
197
        // Open file
198
        $this->openFileHandle($filename);
468✔
199
        // Write html
200
        fwrite($this->fileHandle, $this->generateHTMLAll());
467✔
201
        // Close file
202
        $this->maybeCloseFileHandle();
467✔
203
    }
204

205
    protected function checkRtlAndLtr(): void
557✔
206
    {
207
        $this->rtlSheets = false;
557✔
208
        $this->ltrSheets = false;
557✔
209
        if ($this->sheetIndex === null) {
557✔
210
            foreach ($this->spreadsheet->getAllSheets() as $sheet) {
18✔
211
                if ($sheet->getRightToLeft()) {
18✔
212
                    $this->rtlSheets = true;
3✔
213
                } else {
214
                    $this->ltrSheets = true;
17✔
215
                }
216
            }
217
        } else {
218
            if ($this->spreadsheet->getSheet($this->sheetIndex)->getRightToLeft()) {
546✔
219
                $this->rtlSheets = true;
2✔
220
            }
221
        }
222
    }
223

224
    /**
225
     * Save Spreadsheet as html to variable.
226
     */
227
    public function generateHtmlAll(): string
557✔
228
    {
229
        $this->checkRtlAndLtr();
557✔
230
        $sheets = $this->generateSheetPrep();
557✔
231
        foreach ($sheets as $sheet) {
557✔
232
            $sheet->calculateArrays($this->preCalculateFormulas);
557✔
233
        }
234
        // garbage collect
235
        $this->spreadsheet->garbageCollect();
557✔
236

237
        $saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog();
557✔
238
        Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false);
557✔
239

240
        // Build CSS
241
        $this->buildCSS(!$this->useInlineCss);
557✔
242

243
        $html = '';
557✔
244

245
        // Write headers
246
        $html .= $this->generateHTMLHeader(!$this->useInlineCss);
557✔
247

248
        // Write navigation (tabs)
249
        if ((!$this->isPdf) && ($this->generateSheetNavigationBlock)) {
557✔
250
            $html .= $this->generateNavigation();
523✔
251
        }
252

253
        // Write data
254
        $html .= $this->generateSheetData();
557✔
255

256
        // Write footer
257
        $html .= $this->generateHTMLFooter();
557✔
258
        $callback = $this->editHtmlCallback;
557✔
259
        if ($callback) {
557✔
260
            $html = $callback($html);
6✔
261
        }
262

263
        Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
557✔
264

265
        return $html;
557✔
266
    }
267

268
    /**
269
     * Set a callback to edit the entire HTML.
270
     *
271
     * The callback must accept the HTML as string as first parameter,
272
     * and it must return the edited HTML as string.
273
     */
274
    public function setEditHtmlCallback(?callable $callback): void
6✔
275
    {
276
        $this->editHtmlCallback = $callback;
6✔
277
    }
278

279
    /**
280
     * Map VAlign.
281
     *
282
     * @param string $vAlign Vertical alignment
283
     */
284
    private function mapVAlign(string $vAlign): string
559✔
285
    {
286
        return Alignment::VERTICAL_ALIGNMENT_FOR_HTML[$vAlign] ?? '';
559✔
287
    }
288

289
    /**
290
     * Map HAlign.
291
     *
292
     * @param string $hAlign Horizontal alignment
293
     */
294
    private function mapHAlign(string $hAlign): string
559✔
295
    {
296
        return Alignment::HORIZONTAL_ALIGNMENT_FOR_HTML[$hAlign] ?? '';
559✔
297
    }
298

299
    const BORDER_NONE = 'none';
300
    const BORDER_ARR = [
301
        Border::BORDER_NONE => self::BORDER_NONE,
302
        Border::BORDER_DASHDOT => '1px dashed',
303
        Border::BORDER_DASHDOTDOT => '1px dotted',
304
        Border::BORDER_DASHED => '1px dashed',
305
        Border::BORDER_DOTTED => '1px dotted',
306
        Border::BORDER_DOUBLE => '3px double',
307
        Border::BORDER_HAIR => '1px solid',
308
        Border::BORDER_MEDIUM => '2px solid',
309
        Border::BORDER_MEDIUMDASHDOT => '2px dashed',
310
        Border::BORDER_MEDIUMDASHDOTDOT => '2px dotted',
311
        Border::BORDER_SLANTDASHDOT => '2px dashed',
312
        Border::BORDER_THICK => '3px solid',
313
    ];
314

315
    /**
316
     * Map border style.
317
     *
318
     * @param int|string $borderStyle Sheet index
319
     */
320
    private function mapBorderStyle($borderStyle): string
546✔
321
    {
322
        return self::BORDER_ARR[$borderStyle] ?? '1px solid';
546✔
323
    }
324

325
    /**
326
     * Get sheet index.
327
     */
328
    public function getSheetIndex(): ?int
21✔
329
    {
330
        return $this->sheetIndex;
21✔
331
    }
332

333
    /**
334
     * Set sheet index.
335
     *
336
     * @param int $sheetIndex Sheet index
337
     *
338
     * @return $this
339
     */
340
    public function setSheetIndex(int $sheetIndex): static
1✔
341
    {
342
        $this->sheetIndex = $sheetIndex;
1✔
343

344
        return $this;
1✔
345
    }
346

347
    /**
348
     * Get sheet index.
349
     */
350
    public function getGenerateSheetNavigationBlock(): bool
1✔
351
    {
352
        return $this->generateSheetNavigationBlock;
1✔
353
    }
354

355
    /**
356
     * Set sheet index.
357
     *
358
     * @param bool $generateSheetNavigationBlock Flag indicating whether the sheet navigation block should be generated or not
359
     *
360
     * @return $this
361
     */
362
    public function setGenerateSheetNavigationBlock(bool $generateSheetNavigationBlock): static
1✔
363
    {
364
        $this->generateSheetNavigationBlock = (bool) $generateSheetNavigationBlock;
1✔
365

366
        return $this;
1✔
367
    }
368

369
    /**
370
     * Write all sheets (resets sheetIndex to NULL).
371
     *
372
     * @return $this
373
     */
374
    public function writeAllSheets(): static
19✔
375
    {
376
        $this->sheetIndex = null;
19✔
377

378
        return $this;
19✔
379
    }
380

381
    private static function generateMeta(?string $val, string $desc): string
559✔
382
    {
383
        return ($val || $val === '0')
559✔
384
            ? ('      <meta name="' . $desc . '" content="' . htmlspecialchars($val, Settings::htmlEntityFlags()) . '" />' . PHP_EOL)
559✔
385
            : '';
559✔
386
    }
387

388
    public const BODY_LINE = '  <body>' . PHP_EOL;
389

390
    private const CUSTOM_TO_META = [
391
        Properties::PROPERTY_TYPE_BOOLEAN => 'bool',
392
        Properties::PROPERTY_TYPE_DATE => 'date',
393
        Properties::PROPERTY_TYPE_FLOAT => 'float',
394
        Properties::PROPERTY_TYPE_INTEGER => 'int',
395
        Properties::PROPERTY_TYPE_STRING => 'string',
396
    ];
397

398
    /**
399
     * Generate HTML header.
400
     *
401
     * @param bool $includeStyles Include styles?
402
     */
403
    public function generateHTMLHeader(bool $includeStyles = false): string
559✔
404
    {
405
        // Construct HTML
406
        $properties = $this->spreadsheet->getProperties();
559✔
407
        $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . PHP_EOL;
559✔
408
        $rtl = ($this->rtlSheets && !$this->ltrSheets) ? " dir='rtl'" : '';
559✔
409
        $html .= '<html xmlns="http://www.w3.org/1999/xhtml"' . $rtl . '>' . PHP_EOL;
559✔
410
        $html .= '  <head>' . PHP_EOL;
559✔
411
        $html .= '      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . PHP_EOL;
559✔
412
        $html .= '      <meta name="generator" content="PhpSpreadsheet, https://github.com/PHPOffice/PhpSpreadsheet" />' . PHP_EOL;
559✔
413
        $title = $properties->getTitle();
559✔
414
        if ($title === '') {
559✔
415
            $title = $this->spreadsheet->getActiveSheet()->getTitle();
20✔
416
        }
417
        $html .= '      <title>' . htmlspecialchars($title, Settings::htmlEntityFlags()) . '</title>' . PHP_EOL;
559✔
418
        $html .= self::generateMeta($properties->getCreator(), 'author');
559✔
419
        $html .= self::generateMeta($properties->getTitle(), 'title');
559✔
420
        $html .= self::generateMeta($properties->getDescription(), 'description');
559✔
421
        $html .= self::generateMeta($properties->getSubject(), 'subject');
559✔
422
        $html .= self::generateMeta($properties->getKeywords(), 'keywords');
559✔
423
        $html .= self::generateMeta($properties->getCategory(), 'category');
559✔
424
        $html .= self::generateMeta($properties->getCompany(), 'company');
559✔
425
        $html .= self::generateMeta($properties->getManager(), 'manager');
559✔
426
        $html .= self::generateMeta($properties->getLastModifiedBy(), 'lastModifiedBy');
559✔
427
        $html .= self::generateMeta($properties->getViewport(), 'viewport');
559✔
428
        $date = Date::dateTimeFromTimestamp((string) $properties->getCreated());
559✔
429
        $date->setTimeZone(Date::getDefaultOrLocalTimeZone());
559✔
430
        $html .= self::generateMeta($date->format(DATE_W3C), 'created');
559✔
431
        $date = Date::dateTimeFromTimestamp((string) $properties->getModified());
559✔
432
        $date->setTimeZone(Date::getDefaultOrLocalTimeZone());
559✔
433
        $html .= self::generateMeta($date->format(DATE_W3C), 'modified');
559✔
434

435
        $customProperties = $properties->getCustomProperties();
559✔
436
        foreach ($customProperties as $customProperty) {
559✔
437
            $propertyValue = $properties->getCustomPropertyValue($customProperty);
4✔
438
            $propertyType = $properties->getCustomPropertyType($customProperty);
4✔
439
            $propertyQualifier = self::CUSTOM_TO_META[$propertyType] ?? null;
4✔
440
            if ($propertyQualifier !== null) {
4✔
441
                if ($propertyType === Properties::PROPERTY_TYPE_BOOLEAN) {
4✔
442
                    $propertyValue = $propertyValue ? '1' : '0';
1✔
443
                } elseif ($propertyType === Properties::PROPERTY_TYPE_DATE) {
4✔
444
                    $date = Date::dateTimeFromTimestamp((string) $propertyValue);
1✔
445
                    $date->setTimeZone(Date::getDefaultOrLocalTimeZone());
1✔
446
                    $propertyValue = $date->format(DATE_W3C);
1✔
447
                } else {
448
                    $propertyValue = (string) $propertyValue;
4✔
449
                }
450
                $html .= self::generateMeta($propertyValue, htmlspecialchars("custom.$propertyQualifier.$customProperty"));
4✔
451
            }
452
        }
453

454
        if (!empty($properties->getHyperlinkBase())) {
559✔
455
            $html .= '      <base href="' . htmlspecialchars($properties->getHyperlinkBase()) . '" />' . PHP_EOL;
2✔
456
        }
457

458
        $html .= $includeStyles ? $this->generateStyles(true) : $this->generatePageDeclarations(true);
559✔
459

460
        $html .= '  </head>' . PHP_EOL;
559✔
461
        $html .= '' . PHP_EOL;
559✔
462
        $html .= self::BODY_LINE;
559✔
463

464
        return $html;
559✔
465
    }
466

467
    /** @return Worksheet[] */
468
    private function generateSheetPrep(): array
557✔
469
    {
470
        // Fetch sheets
471
        if ($this->sheetIndex === null) {
557✔
472
            $sheets = $this->spreadsheet->getAllSheets();
18✔
473
        } else {
474
            $sheets = [$this->spreadsheet->getSheet($this->sheetIndex)];
546✔
475
        }
476

477
        return $sheets;
557✔
478
    }
479

480
    /** @return array{int, int, int} */
481
    private function generateSheetStarts(Worksheet $sheet, int $rowMin): array
557✔
482
    {
483
        // calculate start of <tbody>, <thead>
484
        $tbodyStart = $rowMin;
557✔
485
        $theadStart = $theadEnd = 0; // default: no <thead>    no </thead>
557✔
486
        if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
557✔
487
            $rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop();
2✔
488

489
            // we can only support repeating rows that start at top row
490
            if ($rowsToRepeatAtTop[0] == 1) {
2✔
491
                $theadStart = $rowsToRepeatAtTop[0];
2✔
492
                $theadEnd = $rowsToRepeatAtTop[1];
2✔
493
                $tbodyStart = $rowsToRepeatAtTop[1] + 1;
2✔
494
            }
495
        }
496

497
        return [$theadStart, $theadEnd, $tbodyStart];
557✔
498
    }
499

500
    /** @return array{string, string, string} */
501
    private function generateSheetTags(int $row, int $theadStart, int $theadEnd, int $tbodyStart): array
557✔
502
    {
503
        // <thead> ?
504
        $startTag = ($row == $theadStart) ? ('        <thead>' . PHP_EOL) : '';
557✔
505
        if (!$startTag) {
557✔
506
            $startTag = ($row == $tbodyStart) ? ('        <tbody>' . PHP_EOL) : '';
557✔
507
        }
508
        $endTag = ($row == $theadEnd) ? ('        </thead>' . PHP_EOL) : '';
557✔
509
        $cellType = ($row >= $tbodyStart) ? 'td' : 'th';
557✔
510

511
        return [$cellType, $startTag, $endTag];
557✔
512
    }
513

514
    private int $printAreaLowRow = -1;
515

516
    private int $printAreaHighRow = -1;
517

518
    private int $printAreaLowCol = -1;
519

520
    private int $printAreaHighCol = -1;
521

522
    /**
523
     * Generate sheet data.
524
     */
525
    public function generateSheetData(): string
557✔
526
    {
527
        // Ensure that Spans have been calculated?
528
        $this->calculateSpans();
557✔
529
        $sheets = $this->generateSheetPrep();
557✔
530

531
        // Construct HTML
532
        $html = '';
557✔
533

534
        // Loop all sheets
535
        $sheetId = 0;
557✔
536

537
        $activeSheet = $this->spreadsheet->getActiveSheetIndex();
557✔
538

539
        foreach ($sheets as $sheet) {
557✔
540
            $this->printAreaLowRow = -1;
557✔
541
            $this->printAreaHighRow = -1;
557✔
542
            $this->printAreaLowCol = -1;
557✔
543
            $this->printAreaHighCol = -1;
557✔
544
            $printArea = $sheet->getPageSetup()->getPrintArea();
557✔
545
            if (Preg::isMatch('/^([a-z]+)([0-9]+):([a-z]+)([0-9]+)$/i', $printArea, $matches)) {
557✔
546
                $this->printAreaLowCol = Coordinate::columnIndexFromString($matches[1]);
5✔
547
                $this->printAreaHighCol = Coordinate::columnIndexFromString($matches[3]);
5✔
548
                $this->printAreaLowRow = (int) $matches[2];
5✔
549
                $this->printAreaHighRow = (int) $matches[4];
5✔
550
            }
551
            // save active cells
552
            $selectedCells = $sheet->getSelectedCells();
557✔
553
            // Write table header
554
            $html .= $this->generateTableHeader($sheet);
557✔
555
            $this->sheetCharts = [];
557✔
556
            $this->sheetDrawings = [];
557✔
557
            $condStylesCollection = $sheet->getConditionalStylesCollection();
557✔
558
            foreach ($condStylesCollection as $condStyles) {
557✔
559
                foreach ($condStyles as $key => $cs) {
12✔
560
                    if ($cs->getConditionType() === Conditional::CONDITION_COLORSCALE) {
12✔
561
                        $cs->getColorScale()?->setScaleArray();
3✔
562
                    }
563
                }
564
            }
565
            // Get worksheet dimension
566
            [$min, $max] = explode(':', $sheet->calculateWorksheetDataDimension());
557✔
567
            [$minCol, $minRow, $minColString] = Coordinate::indexesFromString($min);
557✔
568
            [$maxCol, $maxRow] = Coordinate::indexesFromString($max);
557✔
569
            $this->extendRowsAndColumns($sheet, $maxCol, $maxRow);
557✔
570

571
            [$theadStart, $theadEnd, $tbodyStart] = $this->generateSheetStarts($sheet, $minRow);
557✔
572
            // Loop through cells
573
            $row = $minRow - 1;
557✔
574
            while ($row++ < $maxRow) {
557✔
575
                [$cellType, $startTag, $endTag] = $this->generateSheetTags($row, $theadStart, $theadEnd, $tbodyStart);
557✔
576
                $html .= StringHelper::convertToString($startTag);
557✔
577

578
                // Write row if there are HTML table cells in it
579
                if ($this->shouldGenerateRow($sheet, $row) && !isset($this->isSpannedRow[$sheet->getParentOrThrow()->getIndex($sheet)][$row])) {
557✔
580
                    // Start a new rowData
581
                    $rowData = [];
557✔
582
                    // Loop through columns
583
                    $column = $minCol;
557✔
584
                    $colStr = $minColString;
557✔
585
                    while ($column <= $maxCol) {
557✔
586
                        // Cell exists?
587
                        $cellAddress = Coordinate::stringFromColumnIndex($column) . $row;
557✔
588
                        if ($this->shouldGenerateColumn($sheet, $colStr)) {
557✔
589
                            $rowData[$column] = ($sheet->getCellCollection()->has($cellAddress)) ? $cellAddress : '';
557✔
590
                        }
591
                        ++$column;
557✔
592
                        /** @var string $colStr */
593
                        StringHelper::stringIncrement($colStr);
557✔
594
                    }
595
                    $html .= $this->generateRow($sheet, $rowData, $row - 1, $cellType);
557✔
596
                }
597

598
                $html .= StringHelper::convertToString($endTag);
557✔
599
            }
600
            // Write table footer
601
            $html .= $this->generateTableFooter();
557✔
602
            // Writing PDF?
603
            if ($this->isPdf && $this->useInlineCss) {
557✔
604
                if ($this->sheetIndex === null && $sheetId + 1 < $this->spreadsheet->getSheetCount()) {
9✔
605
                    $html .= '<div style="page-break-before:always" ></div>';
1✔
606
                }
607
            }
608

609
            // Next sheet
610
            ++$sheetId;
557✔
611
            $sheet->setSelectedCells($selectedCells);
557✔
612
        }
613
        $this->spreadsheet->setActiveSheetIndex($activeSheet);
557✔
614

615
        return $html;
557✔
616
    }
617

618
    /**
619
     * Generate sheet tabs.
620
     */
621
    public function generateNavigation(): string
523✔
622
    {
623
        // Fetch sheets
624
        $sheets = [];
523✔
625
        if ($this->sheetIndex === null) {
523✔
626
            $sheets = $this->spreadsheet->getAllSheets();
12✔
627
        } else {
628
            $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex);
517✔
629
        }
630

631
        // Construct HTML
632
        $html = '';
523✔
633

634
        // Only if there are more than 1 sheets
635
        if (count($sheets) > 1) {
523✔
636
            // Loop all sheets
637
            $sheetId = 0;
12✔
638

639
            $html .= '<ul class="navigation">' . PHP_EOL;
12✔
640

641
            foreach ($sheets as $sheet) {
12✔
642
                $html .= '  <li class="sheet' . $sheetId . '"><a href="#sheet' . $sheetId . '">' . htmlspecialchars($sheet->getTitle()) . '</a></li>' . PHP_EOL;
12✔
643
                ++$sheetId;
12✔
644
            }
645

646
            $html .= '</ul>' . PHP_EOL;
12✔
647
        }
648

649
        return $html;
523✔
650
    }
651

652
    private function extendRowsAndColumns(Worksheet $worksheet, int &$colMax, int &$rowMax): void
557✔
653
    {
654
        if ($this->includeCharts) {
557✔
655
            foreach ($worksheet->getChartCollection() as $chart) {
4✔
656
                $chartCoordinates = $chart->getTopLeftPosition();
4✔
657
                $this->sheetCharts[$chartCoordinates['cell']] = $chart;
4✔
658
                $chartTL = Coordinate::indexesFromString($chartCoordinates['cell']);
4✔
659
                if ($chartTL[1] > $rowMax) {
4✔
660
                    $rowMax = $chartTL[1];
1✔
661
                }
662
                if ($chartTL[0] > $colMax) {
4✔
663
                    $colMax = $chartTL[0];
2✔
664
                }
665
            }
666
        }
667
        foreach ($worksheet->getDrawingCollection() as $drawing) {
557✔
668
            if ($drawing instanceof Drawing && $drawing->getPath() === '') {
28✔
669
                continue;
2✔
670
            }
671
            $imageTL = Coordinate::indexesFromString($drawing->getCoordinates());
27✔
672
            $this->sheetDrawings[$drawing->getCoordinates()] = $drawing;
27✔
673
            if ($imageTL[1] > $rowMax) {
27✔
674
                $rowMax = $imageTL[1];
×
675
            }
676
            if ($imageTL[0] > $colMax) {
27✔
677
                $colMax = $imageTL[0];
×
678
            }
679
        }
680
    }
681

682
    /**
683
     * Convert Windows file name to file protocol URL.
684
     *
685
     * @param string $filename file name on local system
686
     */
687
    public static function winFileToUrl(string $filename, bool $mpdf = false): string
20✔
688
    {
689
        // Windows filename
690
        if (substr($filename, 1, 2) === ':\\') {
20✔
691
            $protocol = $mpdf ? '' : 'file:///';
1✔
692
            $filename = $protocol . str_replace('\\', '/', $filename);
1✔
693
        }
694

695
        return $filename;
20✔
696
    }
697

698
    /**
699
     * Generate image tag in cell.
700
     *
701
     * @param string $coordinates Cell coordinates
702
     */
703
    private function writeImageInCell(string $coordinates): string
557✔
704
    {
705
        // Construct HTML
706
        $html = '';
557✔
707

708
        // Write images
709
        $drawing = $this->sheetDrawings[$coordinates] ?? null;
557✔
710
        if ($drawing !== null) {
557✔
711
            $opacity = '';
27✔
712
            $opacityValue = $drawing->getOpacity();
27✔
713
            if ($opacityValue !== null) {
27✔
714
                $opacityValue = $opacityValue / 100000;
3✔
715
                if ($opacityValue >= 0.0 && $opacityValue <= 1.0) {
3✔
716
                    $opacity = "opacity:$opacityValue; ";
3✔
717
                }
718
            }
719
            $filedesc = $drawing->getDescription();
27✔
720
            $filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded image';
27✔
721
            if ($drawing instanceof Drawing && $drawing->getPath() !== '') {
27✔
722
                $filename = $drawing->getPath();
19✔
723

724
                // Strip off eventual '.'
725
                $filename = Preg::replace('/^[.]/', '', $filename);
19✔
726

727
                // Prepend images root
728
                $filename = $this->getImagesRoot() . $filename;
19✔
729

730
                // Strip off eventual '.' if followed by non-/
731
                $filename = Preg::replace('@^[.]([^/])@', '$1', $filename);
19✔
732

733
                // Convert UTF8 data to PCDATA
734
                $filename = htmlspecialchars($filename, Settings::htmlEntityFlags());
19✔
735

736
                $html .= PHP_EOL;
19✔
737
                $imageData = self::winFileToUrl($filename, $this instanceof Pdf\Mpdf);
19✔
738

739
                if ($this->embedImages || str_starts_with($imageData, 'zip://')) {
19✔
740
                    $imageData = 'data:,';
11✔
741
                    $picture = @file_get_contents($filename);
11✔
742
                    if ($picture !== false) {
11✔
743
                        $mimeContentType = (string) @mime_content_type($filename);
11✔
744
                        if (str_starts_with($mimeContentType, 'image/')) {
11✔
745
                            // base64 encode the binary data
746
                            $base64 = base64_encode($picture);
11✔
747
                            $imageData = 'data:' . $mimeContentType . ';base64,' . $base64;
11✔
748
                        }
749
                    }
750
                }
751

752
                $html .= '<img style="' . $opacity . 'position: absolute; z-index: 1; left: '
19✔
753
                    . $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px; width: '
19✔
754
                    . $drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="'
19✔
755
                    . $imageData . '" alt="' . $filedesc . '" />';
19✔
756
            } elseif ($drawing instanceof MemoryDrawing) {
8✔
757
                $imageResource = $drawing->getImageResource();
8✔
758
                if ($imageResource) {
8✔
759
                    ob_start(); //  Let's start output buffering.
8✔
760
                    imagepng($imageResource); //  This will normally output the image, but because of ob_start(), it won't.
8✔
761
                    $contents = (string) ob_get_contents(); //  Instead, output above is saved to $contents
8✔
762
                    ob_end_clean(); //  End the output buffer.
8✔
763

764
                    $dataUri = 'data:image/png;base64,' . base64_encode($contents);
8✔
765

766
                    //  Because of the nature of tables, width is more important than height.
767
                    //  max-width: 100% ensures that image doesn't overflow containing cell
768
                    //    However, PR #3535 broke test
769
                    //    25_In_memory_image, apparently because
770
                    //    of the use of max-with. In addition,
771
                    //    non-memory-drawings don't use max-width.
772
                    //    Its use here is suspect and is being eliminated.
773
                    //  width: X sets width of supplied image.
774
                    //  As a result, images bigger than cell will be contained and images smaller will not get stretched
775
                    $html .= '<img alt="' . $filedesc . '" src="' . $dataUri . '" style="' . $opacity . 'width:' . $drawing->getWidth() . 'px;left: '
8✔
776
                        . $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px;position: absolute; z-index: 1;" />';
8✔
777
                }
778
            }
779
        }
780

781
        return $html;
557✔
782
    }
783

784
    /**
785
     * Generate chart tag in cell.
786
     * This code should be exercised by sample:
787
     * Chart/32_Chart_read_write_PDF.php.
788
     */
789
    private function writeChartInCell(Worksheet $worksheet, string $coordinates): string
4✔
790
    {
791
        // Construct HTML
792
        $html = '';
4✔
793

794
        // Write charts
795
        $chart = $this->sheetCharts[$coordinates] ?? null;
4✔
796
        if ($chart !== null) {
4✔
797
            $chartCoordinates = $chart->getTopLeftPosition();
4✔
798
            $chartFileName = File::sysGetTempDir() . '/' . uniqid('', true) . '.png';
4✔
799
            $renderedWidth = $chart->getRenderedWidth();
4✔
800
            $renderedHeight = $chart->getRenderedHeight();
4✔
801
            if ($renderedWidth === null || $renderedHeight === null) {
4✔
802
                $this->adjustRendererPositions($chart, $worksheet);
4✔
803
            }
804
            $title = $chart->getTitle();
4✔
805
            $caption = null;
4✔
806
            $filedesc = '';
4✔
807
            if ($title !== null) {
4✔
808
                $calculatedTitle = $title->getCalculatedTitle($worksheet->getParent());
4✔
809
                if ($calculatedTitle !== null) {
4✔
810
                    $caption = $title->getCaption();
2✔
811
                    $title->setCaption($calculatedTitle);
2✔
812
                }
813
                $filedesc = $title->getCaptionText($worksheet->getParent());
4✔
814
            }
815
            $renderSuccessful = $chart->render($chartFileName);
4✔
816
            $chart->setRenderedWidth($renderedWidth);
4✔
817
            $chart->setRenderedHeight($renderedHeight);
4✔
818
            if (isset($title, $caption)) {
4✔
819
                $title->setCaption($caption);
2✔
820
            }
821
            if (!$renderSuccessful) {
4✔
822
                return '';
×
823
            }
824

825
            $html .= PHP_EOL;
4✔
826
            $imageDetails = getimagesize($chartFileName) ?: ['', '', 'mime' => ''];
4✔
827

828
            $filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded chart';
4✔
829
            $picture = file_get_contents($chartFileName);
4✔
830
            unlink($chartFileName);
4✔
831
            if ($picture !== false) {
4✔
832
                $base64 = base64_encode($picture);
4✔
833
                $imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64;
4✔
834

835
                $html .= '<img style="position: absolute; z-index: 1; left: ' . $chartCoordinates['xOffset'] . 'px; top: ' . $chartCoordinates['yOffset'] . 'px; width: ' . $imageDetails[0] . 'px; height: ' . $imageDetails[1] . 'px;" src="' . $imageData . '" alt="' . $filedesc . '" />' . PHP_EOL;
4✔
836
            }
837
        }
838

839
        // Return
840
        return $html;
4✔
841
    }
842

843
    private function adjustRendererPositions(Chart $chart, Worksheet $sheet): void
4✔
844
    {
845
        $topLeft = $chart->getTopLeftPosition();
4✔
846
        $bottomRight = $chart->getBottomRightPosition();
4✔
847
        $tlCell = $topLeft['cell'];
4✔
848
        /** @var string */
849
        $brCell = $bottomRight['cell'];
4✔
850
        if ($tlCell !== '' && $brCell !== '') {
4✔
851
            $tlCoordinate = Coordinate::indexesFromString($tlCell);
4✔
852
            $brCoordinate = Coordinate::indexesFromString($brCell);
4✔
853
            $totalHeight = 0.0;
4✔
854
            $totalWidth = 0.0;
4✔
855
            $defaultRowHeight = $sheet->getDefaultRowDimension()->getRowHeight();
4✔
856
            $defaultRowHeight = SharedDrawing::pointsToPixels(($defaultRowHeight >= 0) ? $defaultRowHeight : SharedFont::getDefaultRowHeightByFont($this->defaultFont));
4✔
857
            if ($tlCoordinate[1] <= $brCoordinate[1] && $tlCoordinate[0] <= $brCoordinate[0]) {
4✔
858
                for ($row = $tlCoordinate[1]; $row <= $brCoordinate[1]; ++$row) {
4✔
859
                    $height = $sheet->getRowDimension($row)->getRowHeight('pt');
4✔
860
                    $totalHeight += ($height >= 0) ? $height : $defaultRowHeight;
4✔
861
                }
862
                $rightEdge = $brCoordinate[2];
4✔
863
                StringHelper::stringIncrement($rightEdge);
4✔
864
                for ($column = $tlCoordinate[2]; $column !== $rightEdge;) {
4✔
865
                    $width = $sheet->getColumnDimension($column)->getWidth();
4✔
866
                    $width = ($width < 0) ? self::DEFAULT_CELL_WIDTH_PIXELS : SharedDrawing::cellDimensionToPixels($sheet->getColumnDimension($column)->getWidth(), $this->defaultFont);
4✔
867
                    $totalWidth += $width;
4✔
868
                    StringHelper::stringIncrement($column);
4✔
869
                }
870
                $chart->setRenderedWidth($totalWidth);
4✔
871
                $chart->setRenderedHeight($totalHeight);
4✔
872
            }
873
        }
874
    }
875

876
    /**
877
     * Generate CSS styles.
878
     *
879
     * @param bool $generateSurroundingHTML Generate surrounding HTML tags? (&lt;style&gt; and &lt;/style&gt;)
880
     */
881
    public function generateStyles(bool $generateSurroundingHTML = true): string
549✔
882
    {
883
        // Build CSS
884
        $css = $this->buildCSS($generateSurroundingHTML);
549✔
885

886
        // Construct HTML
887
        $html = '';
549✔
888

889
        // Start styles
890
        if ($generateSurroundingHTML) {
549✔
891
            $html .= '    <style type="text/css">' . PHP_EOL;
549✔
892
            $html .= (array_key_exists('html', $css)) ? ('      html { ' . $this->assembleCSS($css['html']) . ' }' . PHP_EOL) : '';
549✔
893
        }
894

895
        // Write all other styles
896
        foreach ($css as $styleName => $styleDefinition) {
549✔
897
            if ($styleName != 'html') {
549✔
898
                $html .= '      ' . $styleName . ' { ' . $this->assembleCSS($styleDefinition) . ' }' . PHP_EOL;
549✔
899
            }
900
        }
901
        $html .= $this->generatePageDeclarations(false);
549✔
902

903
        // End styles
904
        if ($generateSurroundingHTML) {
549✔
905
            $html .= '    </style>' . PHP_EOL;
549✔
906
        }
907

908
        // Return
909
        return $html;
549✔
910
    }
911

912
    /** @param string[][] $css */
913
    private function buildCssRowHeights(Worksheet $sheet, array &$css, int $sheetIndex): void
559✔
914
    {
915
        // Calculate row heights
916
        foreach ($sheet->getRowDimensions() as $rowDimension) {
559✔
917
            $row = $rowDimension->getRowIndex() - 1;
33✔
918

919
            // table.sheetN tr.rowYYYYYY { }
920
            $css['table.sheet' . $sheetIndex . ' tr.row' . $row] = [];
33✔
921

922
            if ($rowDimension->getRowHeight() != -1) {
33✔
923
                $pt_height = $rowDimension->getRowHeight();
23✔
924
                $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'] = $pt_height . 'pt';
23✔
925
            }
926
            if ($rowDimension->getVisible() === false) {
33✔
927
                $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['display'] = 'none';
8✔
928
                $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['visibility'] = 'hidden';
8✔
929
            }
930
        }
931
    }
932

933
    /** @param string[][] $css */
934
    private function buildCssPerSheet(Worksheet $sheet, array &$css): void
559✔
935
    {
936
        // Calculate hash code
937
        $sheetIndex = $sheet->getParentOrThrow()->getIndex($sheet);
559✔
938
        $setup = $sheet->getPageSetup();
559✔
939
        if ($setup->getFitToPage() && $setup->getFitToHeight() === 1) {
559✔
940
            $css["table.sheet$sheetIndex"]['page-break-inside'] = 'avoid';
11✔
941
            $css["table.sheet$sheetIndex"]['break-inside'] = 'avoid';
11✔
942
        }
943
        $picture = $sheet->getBackgroundImage();
559✔
944
        if ($picture !== '') {
559✔
945
            $base64 = base64_encode($picture);
1✔
946
            $css["table.sheet$sheetIndex"]['background-image'] = 'url(data:' . $sheet->getBackgroundMime() . ';base64,' . $base64 . ')';
1✔
947
        }
948

949
        // Build styles
950
        // Calculate column widths
951
        $sheet->calculateColumnWidths();
559✔
952

953
        // col elements, initialize
954
        $highestColumnIndex = Coordinate::columnIndexFromString($sheet->getHighestColumn()) - 1;
559✔
955
        $column = -1;
559✔
956
        $colStr = 'A';
559✔
957
        while ($column++ < $highestColumnIndex) {
559✔
958
            $this->columnWidths[$sheetIndex][$column] = self::DEFAULT_CELL_WIDTH_POINTS; // approximation
559✔
959
            if ($this->shouldGenerateColumn($sheet, $colStr)) {
559✔
960
                $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = self::DEFAULT_CELL_WIDTH_POINTS . 'pt';
559✔
961
            }
962
            StringHelper::stringIncrement($colStr);
559✔
963
        }
964

965
        // col elements, loop through columnDimensions and set width
966
        foreach ($sheet->getColumnDimensions() as $columnDimension) {
559✔
967
            $column = Coordinate::columnIndexFromString($columnDimension->getColumnIndex()) - 1;
40✔
968
            $width = SharedDrawing::cellDimensionToPixels($columnDimension->getWidth(), $this->defaultFont);
40✔
969
            $width = SharedDrawing::pixelsToPoints($width);
40✔
970
            if ($columnDimension->getVisible() === false) {
40✔
971
                $css['table.sheet' . $sheetIndex . ' .column' . $column]['display'] = 'none';
10✔
972
                // This would be better but Firefox has an 11-year-old bug.
973
                // https://bugzilla.mozilla.org/show_bug.cgi?id=819045
974
                //$css['table.sheet' . $sheetIndex . ' col.col' . $column]['visibility'] = 'collapse';
975
            }
976
            if ($width >= 0) {
40✔
977
                $this->columnWidths[$sheetIndex][$column] = $width;
29✔
978
                $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = $width . 'pt';
29✔
979
            }
980
        }
981

982
        // Default row height
983
        $rowDimension = $sheet->getDefaultRowDimension();
559✔
984

985
        // table.sheetN tr { }
986
        $css['table.sheet' . $sheetIndex . ' tr'] = [];
559✔
987

988
        if ($rowDimension->getRowHeight() == -1) {
559✔
989
            $pt_height = SharedFont::getDefaultRowHeightByFont($this->spreadsheet->getDefaultStyle()->getFont());
540✔
990
        } else {
991
            $pt_height = $rowDimension->getRowHeight();
19✔
992
        }
993
        $css['table.sheet' . $sheetIndex . ' tr']['height'] = $pt_height . 'pt';
559✔
994
        if ($rowDimension->getVisible() === false) {
559✔
995
            $css['table.sheet' . $sheetIndex . ' tr']['display'] = 'none';
1✔
996
            $css['table.sheet' . $sheetIndex . ' tr']['visibility'] = 'hidden';
1✔
997
        }
998

999
        $this->buildCssRowHeights($sheet, $css, $sheetIndex);
559✔
1000
    }
1001

1002
    /**
1003
     * Build CSS styles.
1004
     *
1005
     * @param bool $generateSurroundingHTML Generate surrounding HTML style? (html { })
1006
     *
1007
     * @return string[][]
1008
     */
1009
    public function buildCSS(bool $generateSurroundingHTML = true): array
559✔
1010
    {
1011
        // Cached?
1012
        if ($this->cssStyles !== null) {
559✔
1013
            return $this->cssStyles;
547✔
1014
        }
1015

1016
        // Ensure that spans have been calculated
1017
        $this->calculateSpans();
559✔
1018

1019
        // Construct CSS
1020
        /** @var string[][] */
1021
        $css = [];
559✔
1022

1023
        // Start styles
1024
        if ($generateSurroundingHTML) {
559✔
1025
            // html { }
1026
            $css['html']['font-family'] = 'Calibri, Arial, Helvetica, sans-serif';
547✔
1027
            $css['html']['font-size'] = '11pt';
547✔
1028
            $css['html']['background-color'] = 'white';
547✔
1029
        }
1030

1031
        // CSS for comments as found in LibreOffice
1032
        $css['a.comment-indicator:hover + div.comment'] = [
559✔
1033
            'background' => '#ffd',
559✔
1034
            'position' => 'absolute',
559✔
1035
            'display' => 'block',
559✔
1036
            'border' => '1px solid black',
559✔
1037
            'padding' => '0.5em',
559✔
1038
        ];
559✔
1039

1040
        $css['a.comment-indicator'] = [
559✔
1041
            'background' => 'red',
559✔
1042
            'display' => 'inline-block',
559✔
1043
            'border' => '1px solid black',
559✔
1044
            'width' => '0.5em',
559✔
1045
            'height' => '0.5em',
559✔
1046
        ];
559✔
1047

1048
        $css['div.comment']['display'] = 'none';
559✔
1049

1050
        // table { }
1051
        $css['table']['border-collapse'] = 'collapse';
559✔
1052

1053
        // .b {}
1054
        $css['.b']['text-align'] = 'center'; // BOOL
559✔
1055

1056
        // .e {}
1057
        $css['.e']['text-align'] = 'center'; // ERROR
559✔
1058

1059
        // .f {}
1060
        $css['.f']['text-align'] = 'right'; // FORMULA
559✔
1061

1062
        // .inlineStr {}
1063
        $css['.inlineStr']['text-align'] = 'left'; // INLINE
559✔
1064

1065
        // .n {}
1066
        $css['.n']['text-align'] = 'right'; // NUMERIC
559✔
1067

1068
        // .s {}
1069
        $css['.s']['text-align'] = 'left'; // STRING
559✔
1070

1071
        $css['.floatright']['float'] = 'right';
559✔
1072
        $css['.floatleft']['float'] = 'left';
559✔
1073

1074
        // Calculate cell style hashes
1075
        foreach ($this->spreadsheet->getCellXfCollection() as $index => $style) {
559✔
1076
            $css['td.style' . $index . ', th.style' . $index] = $this->createCSSStyle($style);
559✔
1077
            //$css['th.style' . $index] = $this->createCSSStyle($style);
1078
        }
1079

1080
        // Fetch sheets
1081
        $sheets = [];
559✔
1082
        if ($this->sheetIndex === null) {
559✔
1083
            $sheets = $this->spreadsheet->getAllSheets();
19✔
1084
        } else {
1085
            $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex);
547✔
1086
        }
1087

1088
        // Build styles per sheet
1089
        foreach ($sheets as $sheet) {
559✔
1090
            $this->buildCssPerSheet($sheet, $css);
559✔
1091
        }
1092

1093
        // Cache
1094
        if ($this->cssStyles === null) {
559✔
1095
            $this->cssStyles = $css;
559✔
1096
        }
1097

1098
        // Return
1099
        return $css;
559✔
1100
    }
1101

1102
    /**
1103
     * Create CSS style.
1104
     *
1105
     * @return string[]
1106
     */
1107
    private function createCSSStyle(Style $style, bool $conditional = false): array
559✔
1108
    {
1109
        // Create CSS
1110
        return array_merge(
559✔
1111
            $conditional ? [] : $this->createCSSStyleAlignment($style->getAlignment()),
559✔
1112
            $this->createCSSStyleBorders($style->getBorders()),
559✔
1113
            $this->createCSSStyleFont($style->getFont(), conditional: $conditional),
559✔
1114
            $this->createCSSStyleFill($style->getFill())
559✔
1115
        );
559✔
1116
    }
1117

1118
    /**
1119
     * Create CSS style.
1120
     *
1121
     * @return string[]
1122
     */
1123
    private function createCSSStyleAlignment(Alignment $alignment): array
559✔
1124
    {
1125
        // Construct CSS
1126
        $css = [];
559✔
1127

1128
        // Create CSS
1129
        $verticalAlign = $this->mapVAlign($alignment->getVertical() ?? '');
559✔
1130
        if ($verticalAlign) {
559✔
1131
            $css['vertical-align'] = $verticalAlign;
559✔
1132
        }
1133
        $textAlign = $this->mapHAlign($alignment->getHorizontal() ?? '');
559✔
1134
        if ($textAlign) {
559✔
1135
            $css['text-align'] = $textAlign;
18✔
1136
            if (in_array($textAlign, ['left', 'right'])) {
18✔
1137
                $css['padding-' . $textAlign] = (string) ($alignment->getIndent() * Alignment::INDENT_UNITS_TO_PIXELS) . 'px';
11✔
1138
            }
1139
        } else {
1140
            $indent = $alignment->getIndent();
559✔
1141
            if ($indent !== 0) {
559✔
1142
                $css['text-indent'] = (string) ($alignment->getIndent() * Alignment::INDENT_UNITS_TO_PIXELS) . 'px';
2✔
1143
            }
1144
        }
1145
        $rotation = $alignment->getTextRotation();
559✔
1146
        if ($rotation !== 0 && $rotation !== Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) {
559✔
1147
            if ($this instanceof Pdf\Mpdf) {
5✔
1148
                $css['text-rotate'] = "$rotation";
1✔
1149
            } else {
1150
                $css['transform'] = "rotate({$rotation}deg)";
4✔
1151
            }
1152
        }
1153
        $direction = $alignment->getReadOrder();
559✔
1154
        if ($direction === Alignment::READORDER_LTR) {
559✔
1155
            $css['direction'] = 'ltr';
2✔
1156
        } elseif ($direction === Alignment::READORDER_RTL) {
559✔
1157
            $css['direction'] = 'rtl';
2✔
1158
        }
1159

1160
        return $css;
559✔
1161
    }
1162

1163
    /**
1164
     * Create CSS style.
1165
     *
1166
     * @return string[]
1167
     */
1168
    private function createCSSStyleFont(Font $font, bool $useDefaults = false, bool $conditional = false): array
559✔
1169
    {
1170
        // Construct CSS
1171
        $css = [];
559✔
1172

1173
        // Create CSS
1174
        if ($font->getBold()) {
559✔
1175
            $css['font-weight'] = 'bold';
23✔
1176
        } elseif ($useDefaults) {
559✔
1177
            $css['font-weight'] = 'normal';
14✔
1178
        }
1179
        if ($font->getUnderline() != Font::UNDERLINE_NONE && $font->getStrikethrough()) {
559✔
1180
            $css['text-decoration'] = 'underline line-through';
1✔
1181
        } elseif ($font->getUnderline() != Font::UNDERLINE_NONE) {
559✔
1182
            $css['text-decoration'] = 'underline';
12✔
1183
        } elseif ($font->getStrikethrough()) {
559✔
1184
            $css['text-decoration'] = 'line-through';
1✔
1185
        } elseif ($useDefaults) {
559✔
1186
            $css['text-decoration'] = 'normal';
17✔
1187
        }
1188
        if ($font->getItalic()) {
559✔
1189
            $css['font-style'] = 'italic';
12✔
1190
        } elseif ($useDefaults) {
559✔
1191
            $css['font-style'] = 'normal';
17✔
1192
        }
1193

1194
        $css['color'] = '#' . $font->getColor()->getRGB();
559✔
1195
        if (!$conditional) {
559✔
1196
            $css['font-family'] = '\'' . htmlspecialchars((string) $font->getName(), ENT_QUOTES) . '\'';
559✔
1197
            $css['font-size'] = $font->getSize() . 'pt';
559✔
1198
        }
1199

1200
        return $css;
559✔
1201
    }
1202

1203
    /**
1204
     * @param string[] $css
1205
     */
1206
    private function styleBorder(array &$css, string $index, Border $border): void
559✔
1207
    {
1208
        $borderStyle = $border->getBorderStyle();
559✔
1209
        // Mpdf doesn't process !important, so omit unimportant border none
1210
        if ($borderStyle === Border::BORDER_NONE && $this instanceof Pdf\Mpdf) {
559✔
1211
            return;
26✔
1212
        }
1213
        if ($borderStyle !== Border::BORDER_OMIT) {
546✔
1214
            $css[$index] = $this->createCSSStyleBorder($border);
546✔
1215
        }
1216
    }
1217

1218
    /**
1219
     * Create CSS style.
1220
     *
1221
     * @param Borders $borders Borders
1222
     *
1223
     * @return string[]
1224
     */
1225
    private function createCSSStyleBorders(Borders $borders): array
559✔
1226
    {
1227
        // Construct CSS
1228
        $css = [];
559✔
1229

1230
        // Create CSS
1231
        $this->styleBorder($css, 'border-bottom', $borders->getBottom());
559✔
1232
        $this->styleBorder($css, 'border-top', $borders->getTop());
559✔
1233
        $this->styleBorder($css, 'border-left', $borders->getLeft());
559✔
1234
        $this->styleBorder($css, 'border-right', $borders->getRight());
559✔
1235

1236
        return $css;
559✔
1237
    }
1238

1239
    /**
1240
     * Create CSS style.
1241
     *
1242
     * @param Border $border Border
1243
     */
1244
    private function createCSSStyleBorder(Border $border): string
546✔
1245
    {
1246
        //    Create CSS - add !important to non-none border styles for merged cells
1247
        $borderStyle = $this->mapBorderStyle($border->getBorderStyle());
546✔
1248

1249
        return $borderStyle . ' #' . $border->getColor()->getRGB() . (($borderStyle === self::BORDER_NONE) ? '' : ' !important');
546✔
1250
    }
1251

1252
    /**
1253
     * Create CSS style (Fill).
1254
     *
1255
     * @param Fill $fill Fill
1256
     *
1257
     * @return string[]
1258
     */
1259
    private function createCSSStyleFill(Fill $fill): array
559✔
1260
    {
1261
        // Construct HTML
1262
        $css = [];
559✔
1263

1264
        // Create CSS
1265
        if ($fill->getFillType() !== Fill::FILL_NONE) {
559✔
1266
            if (
1267
                (in_array($fill->getFillType(), ['', Fill::FILL_SOLID], true) || !$fill->getEndColor()->getRGB())
23✔
1268
                && $fill->getStartColor()->getRGB()
23✔
1269
            ) {
1270
                $value = '#' . $fill->getStartColor()->getRGB();
23✔
1271
                $css['background-color'] = $value;
23✔
1272
            } elseif ($fill->getEndColor()->getRGB()) {
9✔
1273
                $value = '#' . $fill->getEndColor()->getRGB();
9✔
1274
                $css['background-color'] = $value;
9✔
1275
            }
1276
        }
1277

1278
        return $css;
559✔
1279
    }
1280

1281
    /**
1282
     * Generate HTML footer.
1283
     */
1284
    public function generateHTMLFooter(): string
557✔
1285
    {
1286
        // Construct HTML
1287
        $html = '';
557✔
1288
        $html .= '  </body>' . PHP_EOL;
557✔
1289
        $html .= '</html>' . PHP_EOL;
557✔
1290

1291
        return $html;
557✔
1292
    }
1293

1294
    private function getDir(Worksheet $worksheet): string
557✔
1295
    {
1296
        if ($worksheet->getRightToLeft()) {
557✔
1297
            return " dir='rtl'";
5✔
1298
        }
1299
        if ($this->rtlSheets) {
554✔
1300
            return " dir='ltr'";
2✔
1301
        }
1302

1303
        return '';
552✔
1304
    }
1305

1306
    private function getFloat(Worksheet $worksheet): string
557✔
1307
    {
1308
        $float = '';
557✔
1309
        if ($worksheet->getRightToLeft()) {
557✔
1310
            if ($this->ltrSheets) {
5✔
1311
                $float = ' floatright';
2✔
1312
            }
1313
        } else {
1314
            if ($this->rtlSheets) {
554✔
1315
                $float = ' floatleft';
2✔
1316
            }
1317
        }
1318

1319
        return $float;
557✔
1320
    }
1321

1322
    private function generateTableTagInline(Worksheet $worksheet, string $id): string
18✔
1323
    {
1324
        $style = isset($this->cssStyles['table'])
18✔
1325
            ? $this->assembleCSS($this->cssStyles['table']) : '';
18✔
1326
        $rtl = $this->getDir($worksheet);
18✔
1327
        $float = $this->getFloat($worksheet);
18✔
1328
        $prntgrid = $worksheet->getPrintGridlines();
18✔
1329
        $viewgrid = $this->isPdf ? $prntgrid : $worksheet->getShowGridlines();
18✔
1330
        $printArea = $worksheet->getPageSetup()->getPrintArea();
18✔
1331
        $dataPrint = ($printArea === '') ? '' : (" data-printarea='" . htmlspecialchars($printArea) . "'");
18✔
1332
        if ($viewgrid && $prntgrid) {
18✔
1333
            $html = "    <table border='1' cellpadding='1'$rtl$dataPrint $id cellspacing='1' style='$style' class='gridlines gridlinesp$float'>" . PHP_EOL;
3✔
1334
        } elseif ($viewgrid) {
16✔
1335
            $html = "    <table border='0' cellpadding='0'$rtl$dataPrint $id cellspacing='0' style='$style' class='gridlines$float'>" . PHP_EOL;
6✔
1336
        } elseif ($prntgrid) {
11✔
1337
            $html = "    <table border='0' cellpadding='0'$rtl$dataPrint $id cellspacing='0' style='$style' class='gridlinesp$float'>" . PHP_EOL;
2✔
1338
        } elseif ($float === '') {
11✔
1339
            $html = "    <table border='0' cellpadding='1'$rtl$dataPrint $id cellspacing='0' style='$style'>" . PHP_EOL;
11✔
1340
        } else {
NEW
1341
            $html = "    <table border='0' cellpadding='1'$rtl$dataPrint $id cellspacing='0' style='$style' class='$float'>" . PHP_EOL;
×
1342
        }
1343

1344
        return $html;
18✔
1345
    }
1346

1347
    private function generateTableTag(Worksheet $worksheet, string $id, string &$html, int $sheetIndex): void
557✔
1348
    {
1349
        if (!$this->useInlineCss) {
557✔
1350
            $rtl = $this->getDir($worksheet);
547✔
1351
            $printArea = $worksheet->getPageSetup()->getPrintArea();
547✔
1352
            $dataPrint = ($printArea === '') ? '' : (" data-printarea='" . htmlspecialchars($printArea) . "'");
547✔
1353
            $float = $this->getFloat($worksheet);
547✔
1354
            $gridlines = $worksheet->getShowGridlines() ? ' gridlines' : '';
547✔
1355
            $gridlinesp = $worksheet->getPrintGridlines() ? ' gridlinesp' : '';
547✔
1356
            $html .= "    <table border='0' cellpadding='0' cellspacing='0'$rtl$dataPrint $id class='sheet$sheetIndex$gridlines$gridlinesp$float'>" . PHP_EOL;
547✔
1357
        } else {
1358
            $html .= $this->generateTableTagInline($worksheet, $id);
18✔
1359
        }
1360
    }
1361

1362
    /**
1363
     * Generate table header.
1364
     *
1365
     * @param Worksheet $worksheet The worksheet for the table we are writing
1366
     * @param bool $showid whether or not to add id to table tag
1367
     */
1368
    private function generateTableHeader(Worksheet $worksheet, bool $showid = true): string
557✔
1369
    {
1370
        $sheetIndex = $worksheet->getParentOrThrow()->getIndex($worksheet);
557✔
1371

1372
        // Construct HTML
1373
        $html = '';
557✔
1374
        $id = $showid ? "id='sheet$sheetIndex'" : '';
557✔
1375
        $clear = ($this->rtlSheets && $this->ltrSheets) ? '; clear:both' : '';
557✔
1376

1377
        if ($showid) {
557✔
1378
            $html .= "<div style='page: page$sheetIndex$clear'>" . PHP_EOL;
557✔
1379
        } else {
1380
            $html .= "<div style='page: page$sheetIndex$clear' class='scrpgbrk'>" . PHP_EOL;
2✔
1381
        }
1382

1383
        $this->generateTableTag($worksheet, $id, $html, $sheetIndex);
557✔
1384

1385
        // Write <col> elements
1386
        $highestColumnIndex = Coordinate::columnIndexFromString($worksheet->getHighestColumn()) - 1;
557✔
1387
        $i = -1;
557✔
1388
        while ($i++ < $highestColumnIndex) {
557✔
1389
            if (!$this->useInlineCss) {
557✔
1390
                $html .= '        <col class="col' . $i . '" />' . PHP_EOL;
547✔
1391
            } else {
1392
                $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i])
18✔
1393
                    ? $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) : '';
18✔
1394
                $html .= '        <col style="' . $style . '" />' . PHP_EOL;
18✔
1395
            }
1396
        }
1397

1398
        return $html;
557✔
1399
    }
1400

1401
    /**
1402
     * Generate table footer.
1403
     */
1404
    private function generateTableFooter(): string
557✔
1405
    {
1406
        return '    </tbody></table>' . PHP_EOL . '</div>' . PHP_EOL;
557✔
1407
    }
1408

1409
    /**
1410
     * Generate row start.
1411
     *
1412
     * @param int $sheetIndex Sheet index (0-based)
1413
     * @param int $row row number
1414
     */
1415
    private function generateRowStart(Worksheet $worksheet, int $sheetIndex, int $row): string
557✔
1416
    {
1417
        $html = '';
557✔
1418
        if (count($worksheet->getBreaks()) > 0) {
557✔
1419
            $breaks = $worksheet->getRowBreaks();
2✔
1420

1421
            // check if a break is needed before this row
1422
            if (isset($breaks['A' . $row])) {
2✔
1423
                // close table: </table>
1424
                $html .= $this->generateTableFooter();
2✔
1425
                if ($this->isPdf && $this->useInlineCss) {
2✔
1426
                    $html .= '<div style="page-break-before:always" />';
1✔
1427
                }
1428

1429
                // open table again: <table> + <col> etc.
1430
                $html .= $this->generateTableHeader($worksheet, false);
2✔
1431
                $html .= '<tbody>' . PHP_EOL;
2✔
1432
            }
1433
        }
1434

1435
        // Write row start
1436
        if (!$this->useInlineCss) {
557✔
1437
            $html .= '          <tr class="row' . $row . '">' . PHP_EOL;
547✔
1438
        } else {
1439
            $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row])
18✔
1440
                ? $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]) : '';
18✔
1441

1442
            if ($style === '') {
18✔
1443
                $html .= '          <tr>' . PHP_EOL;
17✔
1444
            } else {
1445
                $html .= '          <tr style="' . $style . '">' . PHP_EOL;
1✔
1446
            }
1447
        }
1448

1449
        return $html;
557✔
1450
    }
1451

1452
    /** @return array{null|''|Cell, array{}|string, non-empty-string} */
1453
    private function generateRowCellCss(Worksheet $worksheet, string $cellAddress, int $row, int $columnNumber): array
557✔
1454
    {
1455
        $cell = ($cellAddress > '') ? $worksheet->getCellCollection()->get($cellAddress) : '';
557✔
1456
        $coordinate = Coordinate::stringFromColumnIndex($columnNumber + 1) . ($row + 1);
557✔
1457
        if (!$this->useInlineCss) {
557✔
1458
            $cssClass = 'column' . $columnNumber;
547✔
1459
        } else {
1460
            $cssClass = [];
18✔
1461
        }
1462

1463
        return [$cell, $cssClass, $coordinate];
557✔
1464
    }
1465

1466
    private function generateRowCellDataValueRich(RichText $richText, ?Font $defaultFont = null): string
33✔
1467
    {
1468
        $cellData = '';
33✔
1469
        // Loop through rich text elements
1470
        $elements = $richText->getRichTextElements();
33✔
1471
        foreach ($elements as $element) {
33✔
1472
            // Rich text start?
1473
            $font = ($element instanceof Run) ? $element->getFont() : $defaultFont;
33✔
1474
            if ($element instanceof Run || $font !== null) {
33✔
1475
                $cellEnd = '';
17✔
1476
                if ($font !== null) {
17✔
1477
                    $cellData .= '<span style="' . $this->assembleCSS($this->createCSSStyleFont($font, true)) . '">';
17✔
1478

1479
                    if ($font->getSuperscript()) {
17✔
1480
                        $cellData .= '<sup>';
1✔
1481
                        $cellEnd = '</sup>';
1✔
1482
                    } elseif ($font->getSubscript()) {
17✔
1483
                        $cellData .= '<sub>';
1✔
1484
                        $cellEnd = '</sub>';
1✔
1485
                    }
1486
                } else {
1487
                    $cellData .= '<span>';
×
1488
                }
1489

1490
                // Convert UTF8 data to PCDATA
1491
                $cellText = $element->getText();
17✔
1492
                $cellData .= htmlspecialchars($cellText, Settings::htmlEntityFlags());
17✔
1493

1494
                $cellData .= $cellEnd;
17✔
1495

1496
                $cellData .= '</span>';
17✔
1497
            } else {
1498
                // Convert UTF8 data to PCDATA
1499
                $cellText = $element->getText();
17✔
1500
                $cellData .= htmlspecialchars($cellText, Settings::htmlEntityFlags());
17✔
1501
            }
1502
        }
1503

1504
        return nl2br($cellData);
33✔
1505
    }
1506

1507
    private function generateRowCellDataValue(Worksheet $worksheet, Cell $cell, string &$cellData): void
555✔
1508
    {
1509
        if ($cell->getValue() instanceof RichText) {
555✔
1510
            $cellData .= $this->generateRowCellDataValueRich($cell->getValue(), $cell->getStyle()->getFont());
13✔
1511
        } else {
1512
            if ($this->preCalculateFormulas) {
553✔
1513
                try {
1514
                    $origData = $cell->getCalculatedValue();
552✔
1515
                } catch (CalculationException $exception) {
×
1516
                    $origData = '#ERROR'; // mark as error, rather than crash everything
×
1517
                }
1518
                if ($this->betterBoolean && is_bool($origData)) {
552✔
1519
                    $origData2 = $origData ? $this->getTrue : $this->getFalse;
4✔
1520
                } else {
1521
                    $origData2 = $cell->getCalculatedValueString();
552✔
1522
                }
1523
            } else {
1524
                $origData = $cell->getValue();
1✔
1525
                if ($this->betterBoolean && is_bool($origData)) {
1✔
1526
                    $origData2 = $origData ? $this->getTrue : $this->getFalse;
×
1527
                } else {
1528
                    $origData2 = $cell->getValueString();
1✔
1529
                }
1530
            }
1531
            $formatCode = $worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode();
553✔
1532

1533
            $cellData = NumberFormat::toFormattedString(
553✔
1534
                $origData2,
553✔
1535
                $formatCode ?? NumberFormat::FORMAT_GENERAL,
553✔
1536
                [$this, 'formatColor']
553✔
1537
            );
553✔
1538

1539
            if ($cellData === $origData) {
553✔
1540
                $cellData = htmlspecialchars($cellData, Settings::htmlEntityFlags());
123✔
1541
            }
1542
            if ($worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperscript()) {
553✔
1543
                $cellData = '<sup>' . $cellData . '</sup>';
1✔
1544
            } elseif ($worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubscript()) {
553✔
1545
                $cellData = '<sub>' . $cellData . '</sub>';
1✔
1546
            }
1547
        }
1548
    }
1549

1550
    /** @param string|string[] $cssClass */
1551
    private function generateRowCellData(Worksheet $worksheet, null|Cell|string $cell, array|string &$cssClass): string
557✔
1552
    {
1553
        if ($cell instanceof Cell) {
557✔
1554
            $cellData = '';
555✔
1555
            // Don't know what this does, and no test cases.
1556
            //if ($cell->getParent() === null) {
1557
            //    $cell->attach($worksheet);
1558
            //}
1559
            // Value
1560
            $this->generateRowCellDataValue($worksheet, $cell, $cellData);
555✔
1561

1562
            // Converts the cell content so that spaces occuring at beginning of each new line are replaced by &nbsp;
1563
            // Example: "  Hello\n to the world" is converted to "&nbsp;&nbsp;Hello\n&nbsp;to the world"
1564
            $cellData = Preg::replace('/(?m)(?:^|\G) /', '&nbsp;', $cellData);
555✔
1565

1566
            // convert newline "\n" to '<br>'
1567
            $cellData = nl2br($cellData);
555✔
1568

1569
            // Extend CSS class?
1570
            $dataType = $cell->getDataType();
555✔
1571
            if ($this->betterBoolean && $this->preCalculateFormulas && $dataType === DataType::TYPE_FORMULA) {
555✔
1572
                $calculatedValue = $cell->getCalculatedValue();
27✔
1573
                if (is_bool($calculatedValue)) {
27✔
1574
                    $dataType = DataType::TYPE_BOOL;
4✔
1575
                } elseif (is_numeric($calculatedValue)) {
27✔
1576
                    $dataType = DataType::TYPE_NUMERIC;
20✔
1577
                } elseif (is_string($calculatedValue)) {
19✔
1578
                    $dataType = DataType::TYPE_STRING;
18✔
1579
                }
1580
            }
1581
            if (!$this->useInlineCss && is_string($cssClass)) {
555✔
1582
                $cssClass .= ' style' . $cell->getXfIndex();
546✔
1583
                $cssClass .= ' ' . $dataType;
546✔
1584
            } elseif (is_array($cssClass)) {
17✔
1585
                $index = $cell->getXfIndex();
17✔
1586
                $styleIndex = 'td.style' . $index . ', th.style' . $index;
17✔
1587
                if (isset($this->cssStyles[$styleIndex])) {
17✔
1588
                    $cssClass = array_merge($cssClass, $this->cssStyles[$styleIndex]);
17✔
1589
                }
1590

1591
                // General horizontal alignment: Actual horizontal alignment depends on dataType
1592
                $sharedStyle = $worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex());
17✔
1593
                if (
1594
                    $sharedStyle->getAlignment()->getHorizontal() == Alignment::HORIZONTAL_GENERAL
17✔
1595
                    && isset($this->cssStyles['.' . $cell->getDataType()]['text-align'])
17✔
1596
                ) {
1597
                    $cssClass['text-align'] = $this->cssStyles['.' . $dataType]['text-align'];
17✔
1598
                }
1599
            }
1600
        } else {
1601
            $cellData = "$cell";
60✔
1602
            // Use default borders for empty cell
1603
            if (is_string($cssClass)) {
60✔
1604
                $cssClass .= ' style0';
53✔
1605
            }
1606
        }
1607
        /*
1608
         * Browsers may remove an entirely empty row.
1609
         * An interesting option is to leave an empty cell empty using css.
1610
         * td:empty::after{content: "\00a0";}
1611
         * This works well in modern browsers.
1612
         * Alas, none of our Pdf writers can handle it.
1613
         */
1614

1615
        return (trim($cellData) === '') ? '&nbsp;' : $cellData;
557✔
1616
    }
1617

1618
    private function generateRowIncludeCharts(Worksheet $worksheet, string $coordinate): string
557✔
1619
    {
1620
        return $this->includeCharts ? $this->writeChartInCell($worksheet, $coordinate) : '';
557✔
1621
    }
1622

1623
    private function generateRowSpans(string $html, int $rowSpan, int $colSpan): string
557✔
1624
    {
1625
        $html .= ($colSpan > 1) ? (' colspan="' . $colSpan . '"') : '';
557✔
1626
        $html .= ($rowSpan > 1) ? (' rowspan="' . $rowSpan . '"') : '';
557✔
1627

1628
        return $html;
557✔
1629
    }
1630

1631
    /**
1632
     * @param string|string[] $cssClass
1633
     * @param Conditional[] $condStyles
1634
     */
1635
    private function generateRowWriteCell(
557✔
1636
        string &$html,
1637
        Worksheet $worksheet,
1638
        string $coordinate,
1639
        string $cellType,
1640
        string $cellData,
1641
        int $colSpan,
1642
        int $rowSpan,
1643
        array|string $cssClass,
1644
        int $colNum,
1645
        int $sheetIndex,
1646
        int $row,
1647
        array $condStyles = []
1648
    ): void {
1649
        // Image?
1650
        $htmlx = $this->writeImageInCell($coordinate);
557✔
1651
        // Chart?
1652
        $htmlx .= $this->generateRowIncludeCharts($worksheet, $coordinate);
557✔
1653
        // Column start
1654
        $html .= '            <' . $cellType;
557✔
1655
        if ($this->betterBoolean) {
557✔
1656
            $dataType = $worksheet->getCell($coordinate)->getDataType();
556✔
1657
            if ($dataType === DataType::TYPE_BOOL) {
556✔
1658
                $html .= ' data-type="' . DataType::TYPE_BOOL . '"';
3✔
1659
            } elseif ($dataType === DataType::TYPE_FORMULA && $this->preCalculateFormulas && is_bool($worksheet->getCell($coordinate)->getCalculatedValue())) {
556✔
1660
                $html .= ' data-type="' . DataType::TYPE_BOOL . '"';
4✔
1661
            } elseif (is_numeric($cellData) && $worksheet->getCell($coordinate)->getDataType() === DataType::TYPE_STRING) {
556✔
1662
                $html .= ' data-type="' . DataType::TYPE_STRING . '"';
3✔
1663
            }
1664
        }
1665
        $holdCss = '';
557✔
1666
        if (!$this->useInlineCss && !$this->isPdf && is_string($cssClass)) {
557✔
1667
            $html .= ' class="' . $cssClass . '"';
520✔
1668
            if ($htmlx) {
520✔
1669
                $html .= " style='position: relative;'";
24✔
1670
            }
1671
        } else {
1672
            //** Necessary redundant code for the sake of \PhpOffice\PhpSpreadsheet\Writer\Pdf **
1673
            // We must explicitly write the width of the <td> element because TCPDF
1674
            // does not recognize e.g. <col style="width:42pt">
1675
            if ($this->useInlineCss) {
50✔
1676
                $xcssClass = is_array($cssClass) ? $cssClass : [];
18✔
1677
            } else {
1678
                if (is_string($cssClass)) {
34✔
1679
                    $html .= ' class="' . $cssClass . '"';
34✔
1680
                }
1681
                $xcssClass = [];
34✔
1682
            }
1683
            $width = 0;
50✔
1684
            $i = $colNum - 1;
50✔
1685
            $e = $colNum + $colSpan - 1;
50✔
1686
            while ($i++ < $e) {
50✔
1687
                if (isset($this->columnWidths[$sheetIndex][$i])) {
50✔
1688
                    $width += $this->columnWidths[$sheetIndex][$i];
50✔
1689
                }
1690
            }
1691
            $xcssClass['width'] = (string) $width . 'pt';
50✔
1692
            // We must also explicitly write the height of the <td> element because TCPDF
1693
            // does not recognize e.g. <tr style="height:50pt">
1694
            if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'])) {
50✔
1695
                $height = $this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'];
8✔
1696
                $xcssClass['height'] = $height;
8✔
1697
            }
1698
            //** end of redundant code **
1699
            if ($this->useInlineCss) {
50✔
1700
                foreach (['border-top', 'border-bottom', 'border-right', 'border-left'] as $borderType) {
18✔
1701
                    if (($xcssClass[$borderType] ?? '') === 'none #000000') {
18✔
1702
                        unset($xcssClass[$borderType]);
17✔
1703
                    }
1704
                }
1705
            }
1706

1707
            if ($htmlx) {
50✔
1708
                $xcssClass['position'] = 'relative';
11✔
1709
            }
1710
            /** @var string[] $xcssClass */
1711
            $holdCss = $this->assembleCSS($xcssClass);
50✔
1712
            if ($this->useInlineCss) {
50✔
1713
                $prntgrid = $worksheet->getPrintGridlines();
18✔
1714
                $viewgrid = $this->isPdf ? $prntgrid : $worksheet->getShowGridlines();
18✔
1715
                if ($viewgrid && $prntgrid) {
18✔
1716
                    $html .= ' class="gridlines gridlinesp"';
3✔
1717
                } elseif ($viewgrid) {
16✔
1718
                    $html .= ' class="gridlines"';
6✔
1719
                } elseif ($prntgrid) {
11✔
1720
                    $html .= ' class="gridlinesp"';
2✔
1721
                }
1722
            }
1723
        }
1724

1725
        $html = $this->generateRowSpans($html, $rowSpan, $colSpan);
557✔
1726

1727
        $tables = $worksheet->getTablesWithStylesForCell($worksheet->getCell($coordinate));
557✔
1728
        if (count($tables) > 0 || count($condStyles) > 0) {
557✔
1729
            $matched = false; // TODO the style gotten from the merger overrides everything
12✔
1730
            $styleMerger = new StyleMerger($worksheet->getCell($coordinate)->getStyle());
12✔
1731
            if ($this->tableFormats) {
12✔
1732
                if (count($tables) > 0) {
4✔
1733
                    foreach ($tables as $ts) {
4✔
1734
                        /** @var Table $ts */
1735
                        $dxfsTableStyle = $ts->getStyle()->getTableDxfsStyle();
4✔
1736
                        if ($dxfsTableStyle !== null) {
4✔
1737
                            /** @var int */
1738
                            $tableRow = $ts->getRowNumber($coordinate);
4✔
1739
                            /** @var TableDxfsStyle $dxfsTableStyle */
1740
                            if ($tableRow === 0 && $dxfsTableStyle->getHeaderRowStyle() !== null) {
4✔
1741
                                $styleMerger->mergeStyle($dxfsTableStyle->getHeaderRowStyle());
4✔
1742
                                $matched = true;
4✔
1743
                            } elseif ($tableRow % 2 === 1 && $dxfsTableStyle->getFirstRowStripeStyle() !== null) {
4✔
1744
                                $styleMerger->mergeStyle($dxfsTableStyle->getFirstRowStripeStyle());
4✔
1745
                                $matched = true;
4✔
1746
                            } elseif ($tableRow % 2 === 0 && $dxfsTableStyle->getSecondRowStripeStyle() !== null) {
4✔
1747
                                $styleMerger->mergeStyle($dxfsTableStyle->getSecondRowStripeStyle());
4✔
1748
                                $matched = true;
4✔
1749
                            }
1750
                        }
1751
                    }
1752
                }
1753
            }
1754
            if (count($condStyles) > 0 && $this->conditionalFormatting) {
12✔
1755
                if ($worksheet->getConditionalRange($coordinate) !== null) {
9✔
1756
                    $assessor = new CellStyleAssessor($worksheet->getCell($coordinate), $worksheet->getConditionalRange($coordinate));
9✔
1757
                } else {
1758
                    $assessor = new CellStyleAssessor($worksheet->getCell($coordinate), $coordinate);
×
1759
                }
1760
                $matchedStyle = $assessor->matchConditionsReturnNullIfNoneMatched($condStyles, $cellData, true);
9✔
1761

1762
                if ($matchedStyle !== null) {
9✔
1763
                    $matched = true;
9✔
1764
                    // this is really slow
1765
                    $styleMerger->mergeStyle($matchedStyle);
9✔
1766
                }
1767
            }
1768
            if ($matched) {
12✔
1769
                $styles = $this->createCSSStyle($styleMerger->getStyle(), true);
11✔
1770
                $html .= ' style="';
11✔
1771
                if ($holdCss !== '') {
11✔
1772
                    $html .= "$holdCss; ";
1✔
1773
                    $holdCss = '';
1✔
1774
                }
1775
                foreach ($styles as $key => $value) {
11✔
1776
                    if (!str_starts_with($key, 'border-') || $value !== 'none #000000') {
11✔
1777
                        $html .= $key . ':' . $value . ';';
11✔
1778
                    }
1779
                }
1780
                $html .= '"';
11✔
1781
            }
1782
        }
1783
        if ($holdCss !== '') {
557✔
1784
            $html .= ' style="' . $holdCss . '"';
50✔
1785
        }
1786

1787
        $html .= '>';
557✔
1788
        $html .= $htmlx;
557✔
1789

1790
        $html .= $this->writeComment($worksheet, $coordinate);
557✔
1791

1792
        // Cell data
1793
        $html .= $cellData;
557✔
1794

1795
        // Column end
1796
        $html .= '</' . $cellType . '>' . PHP_EOL;
557✔
1797
    }
1798

1799
    /**
1800
     * Generate row.
1801
     *
1802
     * @param array<int, string> $values Array containing cells in a row
1803
     * @param int $row Row number (0-based)
1804
     * @param string $cellType eg: 'td'
1805
     */
1806
    private function generateRow(Worksheet $worksheet, array $values, int $row, string $cellType): string
557✔
1807
    {
1808
        // Sheet index
1809
        $sheetIndex = $worksheet->getParentOrThrow()->getIndex($worksheet);
557✔
1810
        $html = $this->generateRowStart($worksheet, $sheetIndex, $row);
557✔
1811

1812
        // Write cells
1813
        $colNum = 0;
557✔
1814
        $tcpdfInited = false;
557✔
1815
        foreach ($values as $key => $cellAddress) {
557✔
1816
            if ($this instanceof Pdf\Mpdf) {
557✔
1817
                $colNum = $key - 1;
26✔
1818
            } elseif ($this instanceof Pdf\Tcpdf) {
539✔
1819
                // It appears that Tcpdf requires first cell in tr.
1820
                $colNum = $key - 1;
9✔
1821
                if (!$tcpdfInited && $key !== 1) {
9✔
1822
                    $tempspan = ($colNum > 1) ? " colspan='$colNum'" : '';
2✔
1823
                    $html .= "<td$tempspan></td>" . PHP_EOL;
2✔
1824
                }
1825
                $tcpdfInited = true;
9✔
1826
            }
1827
            [$cell, $cssClass, $coordinate] = $this->generateRowCellCss($worksheet, $cellAddress, $row, $colNum);
557✔
1828

1829
            // Cell Data
1830
            $cellData = $this->generateRowCellData($worksheet, $cell, $cssClass);
557✔
1831

1832
            // Get an array of all styles
1833
            $condStyles = $worksheet->getStyle($coordinate)->getConditionalStyles();
557✔
1834

1835
            // Hyperlink?
1836
            if ($worksheet->hyperlinkExists($coordinate) && !$worksheet->getHyperlink($coordinate)->isInternal()) {
557✔
1837
                $url = $worksheet->getHyperlink($coordinate)->getUrl();
13✔
1838
                $urlDecode1 = html_entity_decode($url, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
13✔
1839
                $urlTrim = Preg::replace('/^\s+/u', '', $urlDecode1);
13✔
1840
                $parseScheme = Preg::isMatch('/^([\w\s\x00-\x1f]+):/u', strtolower($urlTrim), $matches);
13✔
1841
                if ($parseScheme && !in_array($matches[1], ['http', 'https', 'file', 'ftp', 'mailto', 's3'], true)) {
13✔
1842
                    $cellData = htmlspecialchars($url, Settings::htmlEntityFlags());
3✔
1843
                    $cellData = self::replaceControlChars($cellData);
3✔
1844
                } else {
1845
                    $tooltip = $worksheet->getHyperlink($coordinate)->getTooltip();
11✔
1846
                    $tooltipOut = empty($tooltip) ? '' : (' title="' . htmlspecialchars($tooltip) . '"');
11✔
1847
                    $cellData = '<a href="'
11✔
1848
                        . htmlspecialchars($url) . '"'
11✔
1849
                        . $tooltipOut
11✔
1850
                        . '>' . $cellData . '</a>';
11✔
1851
                }
1852
            }
1853

1854
            // Should the cell be written or is it swallowed by a rowspan or colspan?
1855
            $writeCell = !(isset($this->isSpannedCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum])
557✔
1856
                && $this->isSpannedCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum]);
557✔
1857

1858
            // Colspan and Rowspan
1859
            $colSpan = 1;
557✔
1860
            $rowSpan = 1;
557✔
1861
            if (isset($this->isBaseCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum])) {
557✔
1862
                /** @var array<string, int> */
1863
                $spans = $this->isBaseCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum];
21✔
1864
                $rowSpan = $spans['rowspan'];
21✔
1865
                $colSpan = $spans['colspan'];
21✔
1866

1867
                //    Also apply style from last cell in merge to fix borders -
1868
                //        relies on !important for non-none border declarations in createCSSStyleBorder
1869
                $endCellCoord = Coordinate::stringFromColumnIndex($colNum + $colSpan) . ($row + $rowSpan);
21✔
1870
                if (!$this->useInlineCss && is_string($cssClass)) {
21✔
1871
                    $cssClass .= ' style' . $worksheet->getCell($endCellCoord)->getXfIndex();
18✔
1872
                } else {
1873
                    $endBorders = $this->spreadsheet->getCellXfByIndex($worksheet->getCell($endCellCoord)->getXfIndex())->getBorders();
4✔
1874
                    $altBorders = $this->createCSSStyleBorders($endBorders);
4✔
1875
                    foreach ($altBorders as $altKey => $altValue) {
4✔
1876
                        if (str_contains($altValue, '!important')) {
4✔
1877
                            $cssClass[$altKey] = $altValue;
2✔
1878
                        }
1879
                    }
1880
                }
1881
            }
1882

1883
            // Write
1884
            if ($writeCell) {
557✔
1885
                $this->generateRowWriteCell($html, $worksheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $row, $condStyles);
557✔
1886
            }
1887

1888
            // Next column
1889
            ++$colNum;
557✔
1890
        }
1891

1892
        // Write row end
1893
        $html .= '          </tr>' . PHP_EOL;
557✔
1894

1895
        // Return
1896
        return $html;
557✔
1897
    }
1898

1899
    private static function replaceControlChars(string $convert): string
3✔
1900
    {
1901
        return Preg::replaceCallback(
3✔
1902
            '/[\x00-\x1f]/',
3✔
1903
            fn (array $matches) => '&#' . ord($matches[0]) . ';',
3✔
1904
            $convert
3✔
1905
        );
3✔
1906
    }
1907

1908
    /**
1909
     * Takes array where of CSS properties / values and converts to CSS string.
1910
     *
1911
     * @param string[] $values
1912
     */
1913
    private function assembleCSS(array $values = []): string
559✔
1914
    {
1915
        $pairs = [];
559✔
1916
        foreach ($values as $property => $value) {
559✔
1917
            $pairs[] = $property . ':' . $value;
559✔
1918
        }
1919
        $string = implode('; ', $pairs);
559✔
1920

1921
        return $string;
559✔
1922
    }
1923

1924
    /**
1925
     * Get images root.
1926
     */
1927
    public function getImagesRoot(): string
19✔
1928
    {
1929
        return $this->imagesRoot;
19✔
1930
    }
1931

1932
    /**
1933
     * Set images root.
1934
     *
1935
     * @return $this
1936
     */
1937
    public function setImagesRoot(string $imagesRoot): static
1✔
1938
    {
1939
        $this->imagesRoot = $imagesRoot;
1✔
1940

1941
        return $this;
1✔
1942
    }
1943

1944
    /**
1945
     * Get embed images.
1946
     */
1947
    public function getEmbedImages(): bool
5✔
1948
    {
1949
        return $this->embedImages;
5✔
1950
    }
1951

1952
    /**
1953
     * Set embed images.
1954
     *
1955
     * @return $this
1956
     */
1957
    public function setEmbedImages(bool $embedImages): static
4✔
1958
    {
1959
        $this->embedImages = $embedImages;
4✔
1960

1961
        return $this;
4✔
1962
    }
1963

1964
    /**
1965
     * Get use inline CSS?
1966
     */
1967
    public function getUseInlineCss(): bool
1✔
1968
    {
1969
        return $this->useInlineCss;
1✔
1970
    }
1971

1972
    /**
1973
     * Set use inline CSS?
1974
     *
1975
     * @return $this
1976
     */
1977
    public function setUseInlineCss(bool $useInlineCss): static
20✔
1978
    {
1979
        $this->useInlineCss = $useInlineCss;
20✔
1980

1981
        return $this;
20✔
1982
    }
1983

1984
    public function getTableFormats(): bool
2✔
1985
    {
1986
        return $this->tableFormats;
2✔
1987
    }
1988

1989
    public function setTableFormats(bool $tableFormats): self
4✔
1990
    {
1991
        $this->tableFormats = $tableFormats;
4✔
1992

1993
        return $this;
4✔
1994
    }
1995

1996
    public function getConditionalFormatting(): bool
1✔
1997
    {
1998
        return $this->conditionalFormatting;
1✔
1999
    }
2000

2001
    public function setConditionalFormatting(bool $conditionalFormatting): self
9✔
2002
    {
2003
        $this->conditionalFormatting = $conditionalFormatting;
9✔
2004

2005
        return $this;
9✔
2006
    }
2007

2008
    /**
2009
     * Add color to formatted string as inline style.
2010
     *
2011
     * @param string $value Plain formatted value without color
2012
     * @param string $format Format code
2013
     */
2014
    public function formatColor(string $value, string $format): string
395✔
2015
    {
2016
        return self::formatColorStatic($value, $format);
395✔
2017
    }
2018

2019
    /**
2020
     * Add color to formatted string as inline style.
2021
     *
2022
     * @param string $value Plain formatted value without color
2023
     * @param string $format Format code
2024
     */
2025
    public static function formatColorStatic(string $value, string $format): string
395✔
2026
    {
2027
        // Color information, e.g. [Red] is always at the beginning
2028
        $color = null; // initialize
395✔
2029
        $matches = [];
395✔
2030

2031
        $color_regex = '/^\[[a-zA-Z]+\]/';
395✔
2032
        if (Preg::isMatch($color_regex, $format, $matches)) {
395✔
2033
            $color = str_replace(['[', ']'], '', $matches[0]);
17✔
2034
            $color = strtolower($color);
17✔
2035
        }
2036

2037
        // convert to PCDATA
2038
        $result = htmlspecialchars($value, Settings::htmlEntityFlags());
395✔
2039

2040
        // color span tag
2041
        if ($color !== null) {
395✔
2042
            $result = '<span style="color:' . $color . '">' . $result . '</span>';
17✔
2043
        }
2044

2045
        return $result;
395✔
2046
    }
2047

2048
    /**
2049
     * Calculate information about HTML colspan and rowspan which is not always the same as Excel's.
2050
     */
2051
    private function calculateSpans(): void
559✔
2052
    {
2053
        if ($this->spansAreCalculated) {
559✔
2054
            return;
559✔
2055
        }
2056
        // Identify all cells that should be omitted in HTML due to cell merge.
2057
        // In HTML only the upper-left cell should be written and it should have
2058
        //   appropriate rowspan / colspan attribute
2059
        $sheetIndexes = $this->sheetIndex !== null
559✔
2060
            ? [$this->sheetIndex] : range(0, $this->spreadsheet->getSheetCount() - 1);
559✔
2061

2062
        foreach ($sheetIndexes as $sheetIndex) {
559✔
2063
            $sheet = $this->spreadsheet->getSheet($sheetIndex);
559✔
2064

2065
            $candidateSpannedRow = [];
559✔
2066

2067
            // loop through all Excel merged cells
2068
            foreach ($sheet->getMergeCells() as $cells) {
559✔
2069
                [$cells] = Coordinate::splitRange($cells);
21✔
2070
                $first = $cells[0];
21✔
2071
                $last = $cells[1];
21✔
2072

2073
                [$fc, $fr] = Coordinate::indexesFromString($first);
21✔
2074
                $fc = $fc - 1;
21✔
2075

2076
                [$lc, $lr] = Coordinate::indexesFromString($last);
21✔
2077
                $lc = $lc - 1;
21✔
2078

2079
                // loop through the individual cells in the individual merge
2080
                $r = $fr - 1;
21✔
2081
                while ($r++ < $lr) {
21✔
2082
                    // also, flag this row as a HTML row that is candidate to be omitted
2083
                    $candidateSpannedRow[$r] = $r;
21✔
2084

2085
                    $c = $fc - 1;
21✔
2086
                    while ($c++ < $lc) {
21✔
2087
                        if (!($c == $fc && $r == $fr)) {
21✔
2088
                            // not the upper-left cell (should not be written in HTML)
2089
                            $this->isSpannedCell[$sheetIndex][$r][$c] = [
21✔
2090
                                'baseCell' => [$fr, $fc],
21✔
2091
                            ];
21✔
2092
                        } else {
2093
                            // upper-left is the base cell that should hold the colspan/rowspan attribute
2094
                            $this->isBaseCell[$sheetIndex][$r][$c] = [
21✔
2095
                                'xlrowspan' => $lr - $fr + 1, // Excel rowspan
21✔
2096
                                'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change
21✔
2097
                                'xlcolspan' => $lc - $fc + 1, // Excel colspan
21✔
2098
                                'colspan' => $lc - $fc + 1, // HTML colspan, value may change
21✔
2099
                            ];
21✔
2100
                        }
2101
                    }
2102
                }
2103
            }
2104

2105
            $this->calculateSpansOmitRows($sheet, $sheetIndex, $candidateSpannedRow);
559✔
2106

2107
            // TODO: Same for columns
2108
        }
2109

2110
        // We have calculated the spans
2111
        $this->spansAreCalculated = true;
559✔
2112
    }
2113

2114
    /** @param int[] $candidateSpannedRow */
2115
    private function calculateSpansOmitRows(Worksheet $sheet, int $sheetIndex, array $candidateSpannedRow): void
559✔
2116
    {
2117
        // Identify which rows should be omitted in HTML. These are the rows where all the cells
2118
        //   participate in a merge and the where base cells are somewhere above.
2119
        $countColumns = Coordinate::columnIndexFromString($sheet->getHighestColumn());
559✔
2120
        foreach ($candidateSpannedRow as $rowIndex) {
559✔
2121
            if (isset($this->isSpannedCell[$sheetIndex][$rowIndex])) {
21✔
2122
                if (count($this->isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) {
21✔
2123
                    $this->isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex;
9✔
2124
                }
2125
            }
2126
        }
2127

2128
        // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1
2129
        if (isset($this->isSpannedRow[$sheetIndex])) {
559✔
2130
            foreach ($this->isSpannedRow[$sheetIndex] as $rowIndex) {
9✔
2131
                /** @var int $rowIndex */
2132
                $adjustedBaseCells = [];
9✔
2133
                $c = -1;
9✔
2134
                $e = $countColumns - 1;
9✔
2135
                while ($c++ < $e) {
9✔
2136
                    $baseCell = $this->isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell'];
9✔
2137

2138
                    if (!in_array($baseCell, $adjustedBaseCells, true)) {
9✔
2139
                        // subtract rowspan by 1
2140
                        /** @var array<int|string> $baseCell */
2141
                        --$this->isBaseCell[$sheetIndex][$baseCell[0]][$baseCell[1]]['rowspan'];
9✔
2142
                        $adjustedBaseCells[] = $baseCell;
9✔
2143
                    }
2144
                }
2145
            }
2146
        }
2147
    }
2148

2149
    /**
2150
     * Write a comment in the same format as LibreOffice.
2151
     *
2152
     * @see https://github.com/LibreOffice/core/blob/9fc9bf3240f8c62ad7859947ab8a033ac1fe93fa/sc/source/filter/html/htmlexp.cxx#L1073-L1092
2153
     */
2154
    private function writeComment(Worksheet $worksheet, string $coordinate): string
557✔
2155
    {
2156
        $result = '';
557✔
2157
        if (!$this->isPdf && isset($worksheet->getComments()[$coordinate])) {
557✔
2158
            $sanitizedString = $this->generateRowCellDataValueRich($worksheet->getComment($coordinate)->getText());
24✔
2159
            $dir = ($worksheet->getComment($coordinate)->getTextboxDirection() === Comment::TEXTBOX_DIRECTION_RTL) ? ' dir="rtl"' : '';
24✔
2160
            $align = strtolower($worksheet->getComment($coordinate)->getAlignment());
24✔
2161
            $alignment = Alignment::HORIZONTAL_ALIGNMENT_FOR_HTML[$align] ?? '';
24✔
2162
            if ($alignment !== '') {
24✔
2163
                $alignment = " style=\"text-align:$alignment\"";
2✔
2164
            }
2165
            if ($sanitizedString !== '') {
24✔
2166
                $result .= '<a class="comment-indicator"></a>';
24✔
2167
                $result .= "<div class=\"comment\"$dir$alignment>" . $sanitizedString . '</div>';
24✔
2168
                $result .= PHP_EOL;
24✔
2169
            }
2170
        }
2171

2172
        return $result;
557✔
2173
    }
2174

2175
    public function getOrientation(): ?string
525✔
2176
    {
2177
        // Expect Pdf classes to override this method.
2178
        return $this->isPdf ? PageSetup::ORIENTATION_PORTRAIT : null;
525✔
2179
    }
2180

2181
    /**
2182
     * Generate @page declarations.
2183
     */
2184
    private function generatePageDeclarations(bool $generateSurroundingHTML): string
559✔
2185
    {
2186
        // Ensure that Spans have been calculated?
2187
        $this->calculateSpans();
559✔
2188

2189
        // Fetch sheets
2190
        $sheets = [];
559✔
2191
        if ($this->sheetIndex === null) {
559✔
2192
            $sheets = $this->spreadsheet->getAllSheets();
19✔
2193
        } else {
2194
            $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex);
547✔
2195
        }
2196

2197
        // Construct HTML
2198
        $htmlPage = $generateSurroundingHTML ? ('<style type="text/css">' . PHP_EOL) : '';
559✔
2199

2200
        // Loop all sheets
2201
        $sheetId = 0;
559✔
2202
        foreach ($sheets as $worksheet) {
559✔
2203
            $htmlPage .= "@page page$sheetId { ";
559✔
2204
            $left = StringHelper::formatNumber($worksheet->getPageMargins()->getLeft()) . 'in; ';
559✔
2205
            $htmlPage .= 'margin-left: ' . $left;
559✔
2206
            $right = StringHelper::FormatNumber($worksheet->getPageMargins()->getRight()) . 'in; ';
559✔
2207
            $htmlPage .= 'margin-right: ' . $right;
559✔
2208
            $top = StringHelper::FormatNumber($worksheet->getPageMargins()->getTop()) . 'in; ';
559✔
2209
            $htmlPage .= 'margin-top: ' . $top;
559✔
2210
            $bottom = StringHelper::FormatNumber($worksheet->getPageMargins()->getBottom()) . 'in; ';
559✔
2211
            $htmlPage .= 'margin-bottom: ' . $bottom;
559✔
2212
            $orientation = $this->getOrientation() ?? $worksheet->getPageSetup()->getOrientation();
559✔
2213
            if ($orientation === PageSetup::ORIENTATION_LANDSCAPE) {
559✔
2214
                $htmlPage .= 'size: landscape; ';
17✔
2215
            } elseif ($orientation === PageSetup::ORIENTATION_PORTRAIT) {
543✔
2216
                $htmlPage .= 'size: portrait; ';
14✔
2217
            }
2218
            $htmlPage .= '}' . PHP_EOL;
559✔
2219
            if (!$this->isPdf) {
559✔
2220
                $htmlPage .= $this->printAreaStyles($sheetId, $worksheet);
525✔
2221
            }
2222
            ++$sheetId;
559✔
2223
        }
2224
        $htmlPage .= implode(PHP_EOL, [
559✔
2225
            '.navigation {page-break-after: always;}',
559✔
2226
            '.scrpgbrk, div + div {page-break-before: always;}',
559✔
2227
            '@media screen {',
559✔
2228
            '  .gridlines td {border: 1px solid black;}',
559✔
2229
            '  .gridlines th {border: 1px solid black;}',
559✔
2230
            '  body>div {margin-top: 5px;}',
559✔
2231
            '  body>div:first-child {margin-top: 0;}',
559✔
2232
            '  .scrpgbrk {margin-top: 1px;}',
559✔
2233
            '}',
559✔
2234
            '@media print {',
559✔
2235
            '  .gridlinesp td {border: 1px solid black;}',
559✔
2236
            '  .gridlinesp th {border: 1px solid black;}',
559✔
2237
            '  .navigation {display: none;}',
559✔
2238
            '}',
559✔
2239
            '',
559✔
2240
        ]);
559✔
2241
        $htmlPage .= $generateSurroundingHTML ? ('</style>' . PHP_EOL) : '';
559✔
2242

2243
        return $htmlPage;
559✔
2244
    }
2245

2246
    private function printAreaStyles(int $sheetId, Worksheet $worksheet): string
525✔
2247
    {
2248
        $retVal = '';
525✔
2249
        $printArea = $worksheet->getPageSetup()->getPrintArea();
525✔
2250
        if (Preg::isMatch('/^([a-z]+)([0-9]+):([a-z]+)([0-9]+)$/i', $printArea, $matches)) {
525✔
2251
            $lowCol = Coordinate::columnIndexFromString($matches[1]) - 1;
2✔
2252
            $highCol = Coordinate::columnIndexFromString($matches[3]) - 1;
2✔
2253
            $lowRow = (int) $matches[2] - 1;
2✔
2254
            $highRow = (int) $matches[4] - 1;
2✔
2255
            $retVal = '@media print {' . PHP_EOL;
2✔
2256
            $highDataRow = $worksheet->getHighestDataRow();
2✔
2257
            for ($row = 0; $row < $highDataRow; ++$row) {
2✔
2258
                if ($row < $lowRow || $row > $highRow) {
2✔
2259
                    $retVal .= "    table.sheet$sheetId tr.row$row td { display:none }" . PHP_EOL;
2✔
2260
                }
2261
            }
2262
            $highDataColumn = $worksheet->getHighestDataColumn();
2✔
2263
            $highDataCol = Coordinate::columnIndexFromString($highDataColumn);
2✔
2264
            for ($col = 0; $col < $highDataCol; ++$col) {
2✔
2265
                if ($col < $lowCol || $col > $highCol) {
2✔
2266
                    $retVal .= "    table.sheet$sheetId td.column$col { display:none }" . PHP_EOL;
1✔
2267
                }
2268
            }
2269
            $retVal .= '}' . PHP_EOL;
2✔
2270
        }
2271

2272
        return $retVal;
525✔
2273
    }
2274

2275
    private function shouldGenerateRow(Worksheet $sheet, int $row): bool
557✔
2276
    {
2277
        if ($this->isPdf) {
557✔
2278
            if ($this->printAreaLowRow >= 0) {
41✔
2279
                if ($row < $this->printAreaLowRow || $row > $this->printAreaHighRow) {
3✔
2280
                    return false;
3✔
2281
                }
2282
            }
2283
        }
2284
        if (!($this instanceof Pdf\Mpdf || $this instanceof Pdf\Tcpdf)) {
557✔
2285
            return true;
532✔
2286
        }
2287

2288
        return $sheet->isRowVisible($row);
33✔
2289
    }
2290

2291
    private function shouldGenerateColumn(Worksheet $sheet, string $colStr): bool
559✔
2292
    {
2293
        if ($this->isPdf) {
559✔
2294
            if ($this->printAreaLowCol >= 0) {
41✔
2295
                $col = Coordinate::columnIndexFromString($colStr);
3✔
2296
                if ($col < $this->printAreaLowCol || $col > $this->printAreaHighCol) {
3✔
2297
                    return false;
3✔
2298
                }
2299
            }
2300
        }
2301
        if (!($this instanceof Pdf\Mpdf || $this instanceof Pdf\Tcpdf)) {
559✔
2302
            return true;
534✔
2303
        }
2304
        if (!$sheet->columnDimensionExists($colStr)) {
33✔
2305
            return true;
32✔
2306
        }
2307

2308
        return $sheet->getColumnDimension($colStr)->getVisible();
11✔
2309
    }
2310

2311
    public function getBetterBoolean(): bool
1✔
2312
    {
2313
        return $this->betterBoolean;
1✔
2314
    }
2315

2316
    public function setBetterBoolean(bool $betterBoolean): self
3✔
2317
    {
2318
        $this->betterBoolean = $betterBoolean;
3✔
2319

2320
        return $this;
3✔
2321
    }
2322
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc