Xlsx Style Writer Minor Refactoring

In our unit tests, we can test the Worksheet Xml which PhpSpreadsheet will generate without having to actually write the spreadsheet to and read it from disk. This refactoring allows us to do the same for Styles, as demonstrated in the new StylesWriterTest.
This commit is contained in:
oleibman
2025-06-12 15:51:48 -07:00
parent 44c3bd564b
commit 04cfc57457
2 changed files with 63 additions and 6 deletions
+35 -6
View File
@@ -249,6 +249,40 @@ class Xlsx extends BaseWriter
return $this->writerPartWorksheet;
}
public function createStyleDictionaries(): void
{
$this->styleHashTable->addFromSource(
$this->getWriterPartStyle()->allStyles(
$this->spreadSheet
)
);
$this->stylesConditionalHashTable->addFromSource(
$this->getWriterPartStyle()->allConditionalStyles(
$this->spreadSheet
)
);
$this->fillHashTable->addFromSource(
$this->getWriterPartStyle()->allFills(
$this->spreadSheet
)
);
$this->fontHashTable->addFromSource(
$this->getWriterPartStyle()->allFonts(
$this->spreadSheet
)
);
$this->bordersHashTable->addFromSource(
$this->getWriterPartStyle()->allBorders(
$this->spreadSheet
)
);
$this->numFmtHashTable->addFromSource(
$this->getWriterPartStyle()->allNumberFormats(
$this->spreadSheet
)
);
}
/**
* Save PhpSpreadsheet to file.
*
@@ -275,12 +309,7 @@ class Xlsx extends BaseWriter
}
// Create styles dictionaries
$this->styleHashTable->addFromSource($this->getWriterPartStyle()->allStyles($this->spreadSheet));
$this->stylesConditionalHashTable->addFromSource($this->getWriterPartStyle()->allConditionalStyles($this->spreadSheet));
$this->fillHashTable->addFromSource($this->getWriterPartStyle()->allFills($this->spreadSheet));
$this->fontHashTable->addFromSource($this->getWriterPartStyle()->allFonts($this->spreadSheet));
$this->bordersHashTable->addFromSource($this->getWriterPartStyle()->allBorders($this->spreadSheet));
$this->numFmtHashTable->addFromSource($this->getWriterPartStyle()->allNumberFormats($this->spreadSheet));
$this->createStyleDictionaries();
// Create drawing dictionary
$this->drawingHashTable->addFromSource($this->getWriterPartDrawing()->allDrawings($this->spreadSheet));
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as XlsxWriter;
use PHPUnit\Framework\TestCase;
class StylesWriterTest extends TestCase
{
public function testStylesWriter(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$writer = new XlsxWriter($spreadsheet);
$writer->createStyleDictionaries();
$writerStyle = new XlsxWriter\Style($writer);
$data = $writerStyle->writeStyles($spreadsheet);
self::assertStringContainsString(
'<fonts count="1"><font><b val="0"/><i val="0"/><strike val="0"/><u val="none"/><sz val="11"/><color rgb="FF000000"/><name val="Calibri"/></font></fonts>',
$data
);
$spreadsheet->disconnectWorksheets();
}
}