Merge ba1d66086d96fb8f0246e06a2d7567167d570cba into 91f756be0b0bf78f79f93a36ffdc240a5bf4099d

This commit is contained in:
quamis 2021-03-21 18:12:31 +01:00 committed by GitHub
commit e84304cbe9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 392 additions and 3 deletions

View File

@ -18,6 +18,12 @@ class Row
*/
protected $style;
/**
* Row height (default is 15)
* @var string
*/
protected $height = '15';
/**
* Row constructor.
* @param Cell[] $cells
@ -126,4 +132,25 @@ class Row
return $cell->getValue();
}, $this->cells);
}
/**
* Set row height
* @param string $height
* @return Row
*/
public function setHeight($height)
{
$this->height = $height;
return $this;
}
/**
* Returns row height
* @return string
*/
public function getHeight()
{
return $this->height;
}
}

View File

@ -66,6 +66,11 @@ class Style
/** @var bool Whether the wrap text property was set */
private $hasSetWrapText = false;
/** @var bool Whether the cell should shrink to fit to content */
private $shouldShrinkToFit = false;
/** @var bool Whether the shouldShrinkToFit text property was set */
private $hasSetShrinkToFit = false;
/** @var Border */
private $border;
@ -463,4 +468,33 @@ class Style
{
return $this->hasSetFormat;
}
/**
* Sets should shrink to fit
* @param bool $shrinkToFit
* @return Style
*/
public function setShouldShrinkToFit($shrinkToFit = true)
{
$this->hasSetShrinkToFit = true;
$this->shouldShrinkToFit = $shrinkToFit;
return $this;
}
/**
* @return bool Whether format should be applied
*/
public function shouldShrinkToFit()
{
return $this->shouldShrinkToFit;
}
/**
* @return bool
*/
public function hasSetShrinkToFit()
{
return $this->hasSetShrinkToFit;
}
}

View File

@ -51,6 +51,23 @@ abstract class OptionsManagerAbstract implements OptionsManagerInterface
}
}
/**
* Add an option to the internal list of options
* Used only for mergeCells() for now
* @param mixed $optionName
* @param mixed $optionValue
* @return void
*/
public function addOption($optionName, $optionValue)
{
if (\in_array($optionName, $this->supportedOptions)) {
if (!isset($this->options[$optionName])) {
$this->options[$optionName] = [];
}
$this->options[$optionName][] = $optionValue;
}
}
/**
* @param string $optionName
* @return mixed|null The set option or NULL if no option with given name found

View File

@ -19,4 +19,13 @@ interface OptionsManagerInterface
* @return mixed|null The set option or NULL if no option with given name found
*/
public function getOption($optionName);
/**
* Add an option to the internal list of options
* Used only for mergeCells() for now
* @param mixed $optionName
* @param mixed $optionValue
* @return void
*/
public function addOption($optionName, $optionValue);
}

View File

@ -183,6 +183,19 @@ class StyleBuilder
return $this;
}
/**
* Set should shrink to fit
* @param bool $shrinkToFit
* @return StyleBuilder
* @api
*/
public function setShouldShrinkToFit($shrinkToFit = true)
{
$this->style->setShouldShrinkToFit($shrinkToFit);
return $this;
}
/**
* Returns the configured style. The style is cached and can be reused.
*

View File

@ -20,4 +20,10 @@ abstract class Options
// XLSX specific options
const SHOULD_USE_INLINE_STRINGS = 'shouldUseInlineStrings';
// XLSX column widths
const COLUMN_WIDTHS = 'columnWidths';
// XLSX merge cells
const MERGE_CELLS = 'mergeCells';
}

View File

@ -27,6 +27,9 @@ class Sheet
/** @var SheetManager Sheet manager */
private $sheetManager;
/** @var bool Sheet is started */
private $isSheetStarted = false;
/**
* @param int $sheetIndex Index of the sheet, based on order in the workbook (zero-based)
* @param string $associatedWorkbookId ID of the sheet's associated workbook
@ -108,4 +111,23 @@ class Sheet
return $this;
}
/**
* @return bool isSheetStarted Sheet was started
*/
public function isSheetStarted()
{
return $this->isSheetStarted;
}
/**
* @param bool $isSheetStarted Set if sheet was started
* @return Sheet
*/
public function setIsSheetStarted($isSheetStarted)
{
$this->isSheetStarted = $isSheetStarted;
return $this;
}
}

View File

@ -85,6 +85,9 @@ class StyleMerger
if (!$style->hasSetWrapText() && $baseStyle->shouldWrapText()) {
$styleToUpdate->setShouldWrapText();
}
if (!$style->hasSetShrinkToFit() && $baseStyle->shouldShrinkToFit()) {
$styleToUpdate->setShouldShrinkToFit();
}
if (!$style->hasSetCellAlignment() && $baseStyle->shouldApplyCellAlignment()) {
$styleToUpdate->setCellAlignment($baseStyle->getCellAlignment());
}

View File

@ -4,6 +4,7 @@ namespace Box\Spout\Writer;
use Box\Spout\Common\Creator\HelperFactory;
use Box\Spout\Common\Entity\Row;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Common\Helper\GlobalFunctionsHelper;
use Box\Spout\Common\Manager\OptionsManagerInterface;
use Box\Spout\Writer\Common\Creator\ManagerFactoryInterface;
@ -97,6 +98,7 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract
* Creates a new sheet and make it the current sheet. The data will now be written to this sheet.
*
* @throws WriterNotOpenedException If the writer has not been opened yet
* @throws IOException If unable to open the sheet for writing
* @return Sheet The created sheet
*/
public function addNewSheetAndMakeItCurrent()

View File

@ -39,6 +39,8 @@ class OptionsManager extends OptionsManagerAbstract
Options::DEFAULT_ROW_STYLE,
Options::SHOULD_CREATE_NEW_SHEETS_AUTOMATICALLY,
Options::SHOULD_USE_INLINE_STRINGS,
Options::COLUMN_WIDTHS,
Options::MERGE_CELLS,
];
}
@ -56,5 +58,7 @@ class OptionsManager extends OptionsManagerAbstract
$this->setOption(Options::DEFAULT_ROW_STYLE, $defaultRowStyle);
$this->setOption(Options::SHOULD_CREATE_NEW_SHEETS_AUTOMATICALLY, true);
$this->setOption(Options::SHOULD_USE_INLINE_STRINGS, true);
$this->setOption(Options::COLUMN_WIDTHS, []);
$this->setOption(Options::MERGE_CELLS, []);
}
}

View File

@ -249,7 +249,7 @@ EOD;
$content .= \sprintf(' applyBorder="%d"', $style->shouldApplyBorder() ? 1 : 0);
if ($style->shouldApplyCellAlignment() || $style->shouldWrapText()) {
if ($style->shouldApplyCellAlignment() || $style->shouldWrapText() || $style->shouldShrinkToFit()) {
$content .= ' applyAlignment="1">';
$content .= '<alignment';
if ($style->shouldApplyCellAlignment()) {
@ -258,6 +258,10 @@ EOD;
if ($style->shouldWrapText()) {
$content .= ' wrapText="1"';
}
if ($style->shouldShrinkToFit()) {
$content .= ' shrinkToFit="true"';
}
$content .= '/>';
$content .= '</xf>';
} else {

View File

@ -37,6 +37,8 @@ class WorksheetManager implements WorksheetManagerInterface
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
EOD;
/** @var OptionsManagerInterface */
private $optionsManager;
/** @var bool Whether inline or shared strings should be used */
protected $shouldUseInlineStrings;
@ -84,6 +86,7 @@ EOD;
StringHelper $stringHelper,
InternalEntityFactory $entityFactory
) {
$this->optionsManager = $optionsManager;
$this->shouldUseInlineStrings = $optionsManager->getOption(Options::SHOULD_USE_INLINE_STRINGS);
$this->rowManager = $rowManager;
$this->styleManager = $styleManager;
@ -113,7 +116,6 @@ EOD;
$worksheet->setFilePointer($sheetFilePointer);
\fwrite($sheetFilePointer, self::SHEET_XML_FILE_HEADER);
\fwrite($sheetFilePointer, '<sheetData>');
}
/**
@ -153,11 +155,28 @@ EOD;
*/
private function addNonEmptyRow(Worksheet $worksheet, Row $row)
{
if (!$worksheet->getExternalSheet()->isSheetStarted()) {
// create nodes for columns widths
if ($this->optionsManager->getOption(Options::COLUMN_WIDTHS)) {
$colsString = '<cols>';
foreach ($this->optionsManager->getOption(Options::COLUMN_WIDTHS) as $index => $width) {
$index++;
$colsString.= '<col collapsed="false" customWidth="true" hidden="false" outlineLevel="0" style="0" max="' . $index . '" min="' . $index . '" width="' . $width . '"/>';
}
$colsString.='</cols>';
\fwrite($worksheet->getFilePointer(), $colsString);
}
\fwrite($worksheet->getFilePointer(), '<sheetData>');
$worksheet->getExternalSheet()->setIsSheetStarted(true);
}
$rowStyle = $row->getStyle();
$rowIndexOneBased = $worksheet->getLastWrittenRowIndex() + 1;
$numCells = $row->getNumCells();
$rowHeight = $row->getHeight();
$rowXML = '<row r="' . $rowIndexOneBased . '" spans="1:' . $numCells . '">';
$rowXML = '<row r="' . $rowIndexOneBased . '" spans="1:' . $numCells . '" customHeight="true"' . ' ht="' . $rowHeight . '">';
foreach ($row->getCells() as $columnIndexZeroBased => $cell) {
$rowXML .= $this->applyStyleAndGetCellXML($cell, $rowStyle, $rowIndexOneBased, $columnIndexZeroBased);
@ -270,7 +289,26 @@ EOD;
return;
}
if (!$worksheet->getExternalSheet()->isSheetStarted()) {
\fwrite($worksheetFilePointer, '<sheetData>');
$worksheet->getExternalSheet()->setIsSheetStarted(true);
}
\fwrite($worksheetFilePointer, '</sheetData>');
// create nodes for merge cells
if ($this->optionsManager->getOption(Options::MERGE_CELLS)) {
$mergeCellString = '<mergeCells count="' . \count($this->optionsManager->getOption(Options::MERGE_CELLS)) . '">';
foreach ($this->optionsManager->getOption(Options::MERGE_CELLS) as $values) {
$output = \array_map(function ($value) {
return CellHelper::getColumnLettersFromColumnIndex($value[0]) . $value[1];
}, $values);
$mergeCellString.= '<mergeCell ref="' . \implode(':', $output) . '"/>';
}
$mergeCellString.= '</mergeCells>';
\fwrite($worksheet->getFilePointer(), $mergeCellString);
}
\fwrite($worksheetFilePointer, '</worksheet>');
\fclose($worksheetFilePointer);
}

View File

@ -47,4 +47,34 @@ class Writer extends WriterMultiSheetsAbstract
return $this;
}
/**
* Set columns widths as list. If value is null will set column with default width (8.43)
* @param array $columnWidths
* @return WriterMultiSheetsAbstract
*/
public function setColumnWidths(array $columnWidths)
{
$this->optionsManager->setOption(Options::COLUMN_WIDTHS, $columnWidths);
return $this;
}
/**
* Merge cells.
* Row coordinates are indexed from 1, columns from 0 (A = 0),
* so a merge B2:G2 looks like $writer->mergeCells([1,2], [6, 2]);
*
* You may use CellHelper::getColumnLettersFromColumnIndex() to convert from "B2" to "[1,2]"
*
* @param int[] $range1 - top left cell's coordinate [column, row]
* @param int[] $range2 - bottom right cell's coordinate [column, row]
* @return $this
*/
public function mergeCells(array $range1, array $range2)
{
$this->optionsManager->addOption(Options::MERGE_CELLS, [$range1, $range2]);
return $this;
}
}

View File

@ -73,4 +73,28 @@ class OptionsManagerTest extends TestCase
$optionsManager->setOption('not-supported', 'something');
$this->assertNull($optionsManager->getOption('not-supported'));
}
/**
* @return void
*/
public function testOptionManagerShouldReturnArrayIfListOptionsAdded()
{
$optionsManager = $this->optionsManager;
$optionsManager->addOption('bar', 'something');
$optionsManager->addOption('bar', 'something-else');
$this->assertIsArray($optionsManager->getOption('bar'));
$this->assertCount(2, $optionsManager->getOption('bar'));
$this->assertEquals('something', $optionsManager->getOption('bar')[0]);
$this->assertEquals('something-else', $optionsManager->getOption('bar')[1]);
}
/**
* @return void
*/
public function testOptionsManagerShouldReturnNullIfListOptionNotSupported()
{
$optionsManager = $this->optionsManager;
$optionsManager->addOption('not-supported', 'something');
$this->assertNull($optionsManager->getOption('not-supported'));
}
}

View File

@ -7,6 +7,7 @@ use Box\Spout\Common\Entity\Row;
use Box\Spout\Common\Exception\InvalidArgumentException;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Common\Exception\SpoutException;
use Box\Spout\Reader\Wrapper\XMLReader;
use Box\Spout\TestUsingResource;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Box\Spout\Writer\Exception\WriterAlreadyOpenedException;
@ -527,6 +528,105 @@ class WriterTest extends TestCase
$this->assertInlineDataWasWrittenToSheet($fileName, 1, 'control _x0015_ character');
}
/**
* @return void
*/
public function testAddRowShouldSupportRowHeights()
{
$fileName = 'test_add_row_should_support_row_heights.xlsx';
$dataRows = $this->createRowsFromValues([
['First row with default height'],
['Second row with custom height'],
]);
$dataRows[1]->setHeight('23');
$this->writeToXLSXFile($dataRows, $fileName);
$firstRow = $this->getXmlRowFromXmlFile($fileName, 1, 1);
$secondRow = $this->getXmlRowFromXmlFile($fileName, 1, 2);
$this->assertEquals('15', $firstRow->getAttribute('ht'), '1st row does not have default height.');
$this->assertEquals('23', $secondRow->getAttribute('ht'), '2nd row does not have custom height.');
}
/**
* @return void
*/
public function testAddRowShouldSupportColumnWidths()
{
$fileName = 'test_add_row_should_support_column_widths.xlsx';
$this->createGeneratedFolderIfNeeded($fileName);
$resourcePath = $this->getGeneratedResourcePath($fileName);
$writer = WriterEntityFactory::createXLSXWriter();
$writer->setShouldUseInlineStrings(true);
$writer->openToFile($resourcePath);
$columnWidths = [1, 2, 3, 4];
$writer->setColumnWidths($columnWidths);
$writer->addRows($this->createRowsFromValues([
['Test cell'],
]));
$writer->close();
$xmlReader = $this->getXmlReaderForSheetFromXmlFile($fileName, 1);
$xmlReader->readUntilNodeFound('cols');
$this->assertEquals('cols', $xmlReader->getCurrentNodeName(), 'Sheet does not have cols tag');
$this->assertEquals(count($columnWidths), $xmlReader->expand()->childNodes->length, 'Sheet does not have the specified number of column definitions');
foreach ($columnWidths as $index => $columnWidth) {
$xmlReader->readUntilNodeFound('col');
$this->assertEquals($index + 1, $xmlReader->expand()->getAttribute('min'));
$this->assertEquals($index + 1, $xmlReader->expand()->getAttribute('max'));
$this->assertEquals($columnWidth, $xmlReader->expand()->getAttribute('width'));
}
}
/**
* @return void
*/
public function testCloseShouldAddMergeCellTags()
{
$fileName = 'test_add_row_should_support_column_widths.xlsx';
$this->createGeneratedFolderIfNeeded($fileName);
$resourcePath = $this->getGeneratedResourcePath($fileName);
$writer = WriterEntityFactory::createXLSXWriter();
$writer->setShouldUseInlineStrings(true);
$writer->openToFile($resourcePath);
$writer->mergeCells([0, 1], [3, 1]);
$writer->mergeCells([2, 3], [10, 3]);
$writer->close();
$xmlReader = $this->getXmlReaderForSheetFromXmlFile($fileName, 1);
$xmlReader->readUntilNodeFound('mergeCells');
$this->assertEquals('mergeCells', $xmlReader->getCurrentNodeName(), 'Sheet does not have mergeCells tag');
$this->assertEquals(2, $xmlReader->expand()->childNodes->length, 'Sheet does not have the specified number of mergeCell definitions');
$xmlReader->readUntilNodeFound('mergeCell');
$this->assertEquals('A1:D1', $xmlReader->expand()->getAttribute('ref'), 'Merge ref for first range is not valid.');
$xmlReader->readUntilNodeFound('mergeCell');
$this->assertEquals('C3:K3', $xmlReader->expand()->getAttribute('ref'), 'Merge ref for second range is not valid.');
}
/**
* @return void
*/
public function testGeneratedFileShouldBeValidForEmptySheets()
{
$fileName = 'test_empty_sheet.xlsx';
$this->createGeneratedFolderIfNeeded($fileName);
$resourcePath = $this->getGeneratedResourcePath($fileName);
$writer = WriterEntityFactory::createXLSXWriter();
$writer->openToFile($resourcePath);
$writer->addNewSheetAndMakeItCurrent();
$writer->close();
$xmlReader = $this->getXmlReaderForSheetFromXmlFile($fileName, 1);
$xmlReader->setParserProperty(XMLReader::VALIDATE, true);
$this->assertTrue($xmlReader->isValid(), 'worksheet xml is not valid');
$xmlReader->setParserProperty(XMLReader::VALIDATE, false);
$xmlReader->readUntilNodeFound('sheetData');
$this->assertEquals('sheetData', $xmlReader->getCurrentNodeName(), 'worksheet xml does not have sheetData');
}
/**
* @return void
*/
@ -641,4 +741,42 @@ class WriterTest extends TestCase
$this->assertStringContainsString($sharedString, $xmlContents, $message);
}
/**
* @param $fileName
* @param $sheetIndex - 1 based
* @return XMLReader
*/
private function getXmlReaderForSheetFromXmlFile($fileName, $sheetIndex)
{
$resourcePath = $this->getGeneratedResourcePath($fileName);
$xmlReader = new XMLReader();
$xmlReader->openFileInZip($resourcePath, 'xl/worksheets/sheet' . $sheetIndex . '.xml');
return $xmlReader;
}
/**
* @param $fileName
* @param $sheetIndex - 1 based
* @param $rowIndex - 1 based
* @throws \Box\Spout\Reader\Exception\XMLProcessingException
* @return \DOMNode|null
*/
private function getXmlRowFromXmlFile($fileName, $sheetIndex, $rowIndex)
{
$xmlReader = $this->getXmlReaderForSheetFromXmlFile($fileName, $sheetIndex);
$xmlReader->readUntilNodeFound('sheetData');
for ($i = 0; $i < $rowIndex; $i++) {
$xmlReader->readUntilNodeFound('row');
}
$row = $xmlReader->expand();
$xmlReader->close();
return $row;
}
}

View File

@ -306,6 +306,24 @@ class WriterWithStyleTest extends TestCase
$this->assertFirstChildHasAttributeEquals(CellAlignment::RIGHT, $xfElement, 'alignment', 'horizontal');
}
/**
* @return void
*/
public function testAddRowShouldApplyShrinkToFit()
{
$fileName = 'test_add_row_should_apply_shrink_to_fit.xlsx';
$shrinkToFitStyle = (new StyleBuilder())->setShouldShrinkToFit()->build();
$dataRows = $this->createStyledRowsFromValues([['xlsx--11']], $shrinkToFitStyle);
$this->writeToXLSXFile($dataRows, $fileName);
$cellXfsDomElement = $this->getXmlSectionFromStylesXmlFile($fileName, 'cellXfs');
$xfElement = $cellXfsDomElement->getElementsByTagName('xf')->item(1);
$this->assertEquals(1, $xfElement->getAttribute('applyAlignment'));
$this->assertFirstChildHasAttributeEquals('true', $xfElement, 'alignment', 'shrinkToFit');
}
/**
* @return void
*/