Add column width options

This commit is contained in:
nartzis committed 2022-01-17 16:35:35 +03:00
1 parent e95e0eeefd
commit 3a0ce0e059
16 files changed
+664 -16

No files matched your search

@@ -20,4 +20,9 @@ abstract class Options
// XLSX specific options
public const SHOULD_USE_INLINE_STRINGS = 'shouldUseInlineStrings';
// Cell size options
const DEFAULT_COLUMN_WIDTH = 'defaultColumnWidth';
const DEFAULT_ROW_HEIGHT = 'defaultRowHeight';
const COLUMN_WIDTHS = 'columnWidthDefinition';
}
@@ -23,6 +23,9 @@ class Worksheet
/** @var int Index of the last written row */
private $lastWrittenRowIndex;
/** @var bool has the sheet data header been written */
private $sheetDataStarted = false;
/**
* Worksheet constructor.
*
@@ -36,6 +39,7 @@ class Worksheet
$this->externalSheet = $externalSheet;
$this->maxNumColumns = 0;
$this->lastWrittenRowIndex = 0;
$this->sheetDataStarted = false;
}
/**
@@ -110,4 +114,20 @@ class Worksheet
// sheet index is zero-based, while ID is 1-based
return $this->externalSheet->getIndex() + 1;
}
/**
* @return bool
*/
public function getSheetDataStarted()
{
return $this->sheetDataStarted;
}
/**
* @param bool $sheetDataStarted
*/
public function setSheetDataStarted($sheetDataStarted)
{
$this->sheetDataStarted = $sheetDataStarted;
}
}
@@ -0,0 +1,63 @@
<?php
namespace Box\Spout\Writer\Common\Manager;
trait ManagesCellSize
{
/** @var float|null The default column width to use */
private $defaultColumnWidth;
/** @var float|null The default row height to use */
private $defaultRowHeight;
/** @var array Array of min-max-width arrays */
private $columnWidths = [];
/**
* @param float|null $width
*/
public function setDefaultColumnWidth($width)
{
$this->defaultColumnWidth = $width;
}
/**
* @param float|null $height
*/
public function setDefaultRowHeight($height)
{
$this->defaultRowHeight = $height;
}
/**
* @param float $width
* @param array $columns One or more columns with this width
*/
public function setColumnWidth(float $width, ...$columns)
{
// Gather sequences
$sequence = [];
foreach ($columns as $i) {
$sequenceLength = count($sequence);
if ($sequenceLength > 0) {
$previousValue = $sequence[$sequenceLength - 1];
if ($i !== $previousValue + 1) {
$this->setColumnWidthForRange($width, $sequence[0], $previousValue);
$sequence = [];
}
}
$sequence[] = $i;
}
$this->setColumnWidthForRange($width, $sequence[0], $sequence[count($sequence) - 1]);
}
/**
* @param float $width The width to set
* @param int $start First column index of the range
* @param int $end Last column index of the range
*/
public function setColumnWidthForRange(float $width, int $start, int $end)
{
$this->columnWidths[] = [$start, $end, $width];
}
}
@@ -157,6 +157,16 @@ abstract class WorkbookManagerAbstract implements WorkbookManagerInterface
return $this->currentWorksheet;
}
/**
* Starts the current sheet and opens the file pointer
*
* @throws IOException
*/
public function startCurrentSheet()
{
$this->worksheetManager->startSheet($this->getCurrentWorksheet());
}
/**
* Sets the given sheet as the current one. New data will be written to this sheet.
* The writing will resume where it stopped (i.e. data won't be truncated).
@@ -276,6 +286,41 @@ abstract class WorkbookManagerAbstract implements WorkbookManagerInterface
}
}
/**
* @param float $width
*/
public function setDefaultColumnWidth(float $width)
{
$this->worksheetManager->setDefaultColumnWidth($width);
}
/**
* @param float $height
*/
public function setDefaultRowHeight(float $height)
{
$this->worksheetManager->setDefaultRowHeight($height);
}
/**
* @param float $width
* @param array $columns One or more columns with this width
*/
public function setColumnWidth(float $width, ...$columns)
{
$this->worksheetManager->setColumnWidth($width, ...$columns);
}
/**
* @param float $width The width to set
* @param int $start First column index of the range
* @param int $end Last column index of the range
*/
public function setColumnWidthForRange(float $width, int $start, int $end)
{
$this->worksheetManager->setColumnWidthForRange($width, $start, $end);
}
/**
* Closes the workbook and all its associated sheets.
* All the necessary files are written to disk and zipped together to create the final file.
@@ -42,6 +42,21 @@ interface WorkbookManagerInterface
*/
public function getCurrentWorksheet();
/**
* Starts the current sheet and opens its file pointer
*/
public function startCurrentSheet();
/**
* @param float $width
*/
public function setDefaultColumnWidth(float $width);
/**
* @param float $height
*/
public function setDefaultRowHeight(float $height);
/**
* Sets the given sheet as the current one. New data will be written to this sheet.
* The writing will resume where it stopped (i.e. data won't be truncated).
@@ -11,6 +11,29 @@ use Box\Spout\Writer\Common\Entity\Worksheet;
*/
interface WorksheetManagerInterface
{
/**
* @param float|null $width
*/
public function setDefaultColumnWidth($width);
/**
* @param float|null $height
*/
public function setDefaultRowHeight($height);
/**
* @param float $width
* @param array $columns One or more columns with this width
*/
public function setColumnWidth(float $width, ...$columns);
/**
* @param float $width The width to set
* @param int $start First column index of the range
* @param int $end Last column index of the range
*/
public function setColumnWidthForRange(float $width, int $start, int $end);
/**
* Adds a row to the worksheet.
*
@@ -93,7 +93,7 @@ class ManagerFactory implements ManagerFactoryInterface
{
$styleRegistry = $this->createStyleRegistry($optionsManager);
return new StyleManager($styleRegistry);
return new StyleManager($styleRegistry, $optionsManager);
}
/**
@@ -34,6 +34,9 @@ class OptionsManager extends OptionsManagerAbstract
Options::TEMP_FOLDER,
Options::DEFAULT_ROW_STYLE,
Options::SHOULD_CREATE_NEW_SHEETS_AUTOMATICALLY,
Options::DEFAULT_COLUMN_WIDTH,
Options::DEFAULT_ROW_HEIGHT,
Options::COLUMN_WIDTHS,
];
}
@@ -4,7 +4,10 @@ namespace Box\Spout\Writer\ODS\Manager\Style;
use Box\Spout\Common\Entity\Style\BorderPart;
use Box\Spout\Common\Entity\Style\CellAlignment;
use Box\Spout\Common\Manager\OptionsManagerInterface;
use Box\Spout\Writer\Common\Entity\Options;
use Box\Spout\Writer\Common\Entity\Worksheet;
use Box\Spout\Writer\Common\Manager\ManagesCellSize;
use Box\Spout\Writer\ODS\Helper\BorderHelper;
/**
@@ -13,9 +16,22 @@ use Box\Spout\Writer\ODS\Helper\BorderHelper;
*/
class StyleManager extends \Box\Spout\Writer\Common\Manager\Style\StyleManager
{
use ManagesCellSize;
/** @var StyleRegistry */
protected $styleRegistry;
/**
* @param StyleRegistry $styleRegistry
*/
public function __construct(StyleRegistry $styleRegistry, OptionsManagerInterface $optionsManager)
{
parent::__construct($styleRegistry);
$this->setDefaultColumnWidth($optionsManager->getOption(Options::DEFAULT_COLUMN_WIDTH));
$this->setDefaultRowHeight($optionsManager->getOption(Options::DEFAULT_ROW_HEIGHT));
$this->columnWidths = $optionsManager->getOption(Options::COLUMN_WIDTHS) ?? [];
}
/**
* Returns the content of the "styles.xml" file, given a list of styles.
*
@@ -162,12 +178,16 @@ EOD;
$content .= $this->getStyleSectionContent($style);
}
$content .= <<<'EOD'
<style:style style:family="table-column" style:name="co1">
<style:table-column-properties fo:break-before="auto"/>
$useOptimalRowHeight = empty($this->defaultRowHeight) ? 'true' : 'false';
$defaultRowHeight = empty($this->defaultRowHeight) ? '15pt' : "{$this->defaultRowHeight}pt";
$defaultColumnWidth = empty($this->defaultColumnWidth) ? '' : "style:column-width=\"{$this->defaultColumnWidth}pt\"";
$content .= <<<EOD
<style:style style:family="table-column" style:name="default-column-style">
<style:table-column-properties fo:break-before="auto" {$defaultColumnWidth}/>
</style:style>
<style:style style:family="table-row" style:name="ro1">
<style:table-row-properties fo:break-before="auto" style:row-height="15pt" style:use-optimal-row-height="true"/>
<style:table-row-properties fo:break-before="auto" style:row-height="{$defaultRowHeight}" style:use-optimal-row-height="{$useOptimalRowHeight}"/>
</style:style>
EOD;
@@ -182,6 +202,17 @@ EOD;
EOD;
}
// Sort column widths since ODS cares about order
usort($this->columnWidths, function ($a, $b) {
if ($a[0] === $b[0]) {
return 0;
}
return ($a[0] < $b[0]) ? -1 : 1;
});
$content .= $this->getTableColumnStylesXMLContent();
$content .= '</office:automatic-styles>';
return $content;
@@ -381,4 +412,42 @@ EOD;
{
return \sprintf(' fo:background-color="#%s" ', $style->getBackgroundColor());
}
public function getTableColumnStylesXMLContent() : string
{
if (empty($this->columnWidths)) {
return '';
}
$content = '';
foreach ($this->columnWidths as $styleIndex => $entry) {
$content .= <<<EOD
<style:style style:family="table-column" style:name="co{$styleIndex}">
<style:table-column-properties fo:break-before="auto" style:use-optimal-column-width="false" style:column-width="{$entry[2]}pt"/>
</style:style>
EOD;
}
return $content;
}
public function getStyledTableColumnXMLContent(int $maxNumColumns) : string
{
if (empty($this->columnWidths)) {
return '';
}
$content = '';
foreach ($this->columnWidths as $styleIndex => $entry) {
$numCols = $entry[1] - $entry[0] + 1;
$content .= <<<EOD
<table:table-column table:default-cell-style-name='Default' table:style-name="co{$styleIndex}" table:number-columns-repeated="{$numCols}"/>
EOD;
}
// Note: This assumes the column widths are contiguous and default width is
// only applied to columns after the last custom column with a custom width
$content .= '<table:table-column table:default-cell-style-name="ce1" table:style-name="default-column-style" table:number-columns-repeated="' . ($maxNumColumns - $entry[1]) . '"/>';
return $content;
}
}
@@ -95,7 +95,7 @@ class WorksheetManager implements WorksheetManagerInterface
$tableStyleName = 'ta' . ($externalSheet->getIndex() + 1);
$tableElement = '<table:table table:style-name="' . $tableStyleName . '" table:name="' . $escapedSheetName . '">';
$tableElement .= '<table:table-column table:default-cell-style-name="ce1" table:style-name="co1" table:number-columns-repeated="' . $worksheet->getMaxNumColumns() . '"/>';
$tableElement .= $this->styleManager->getStyledTableColumnXMLContent($worksheet->getMaxNumColumns());
return $tableElement;
}
@@ -265,4 +265,39 @@ class WorksheetManager implements WorksheetManagerInterface
\fclose($worksheetFilePointer);
}
/**
* @param float|null $width
*/
public function setDefaultColumnWidth($width)
{
$this->styleManager->setDefaultColumnWidth($width);
}
/**
* @param float|null $height
*/
public function setDefaultRowHeight($height)
{
$this->styleManager->setDefaultRowHeight($height);
}
/**
* @param float $width
* @param array $columns One or more columns with this width
*/
public function setColumnWidth(float $width, ...$columns)
{
$this->styleManager->setColumnWidth($width, ...$columns);
}
/**
* @param float $width The width to set
* @param int $start First column index of the range
* @param int $end Last column index of the range
*/
public function setColumnWidthForRange(float $width, int $start, int $end)
{
$this->styleManager->setColumnWidthForRange($width, $start, $end);
}
}
+50 -1
View File
@@ -135,6 +135,55 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract
$this->workbookManager->setCurrentSheet($sheet);
}
/**
* @param float $width
* @throws WriterAlreadyOpenedException
*/
public function setDefaultColumnWidth(float $width)
{
$this->throwIfWriterAlreadyOpened('Writer must be configured before opening it.');
$this->optionsManager->setOption(
Options::DEFAULT_COLUMN_WIDTH,
$width
);
}
/**
* @param float $height
* @throws WriterAlreadyOpenedException
*/
public function setDefaultRowHeight(float $height)
{
$this->throwIfWriterAlreadyOpened('Writer must be configured before opening it.');
$this->optionsManager->setOption(
Options::DEFAULT_ROW_HEIGHT,
$height
);
}
/**
* @param float|null $width
* @param array $columns One or more columns with this width
* @throws WriterNotOpenedException
*/
public function setColumnWidth($width, ...$columns)
{
$this->throwIfWorkbookIsNotAvailable();
$this->workbookManager->setColumnWidth($width, ...$columns);
}
/**
* @param float $width The width to set
* @param int $start First column index of the range
* @param int $end Last column index of the range
* @throws WriterNotOpenedException
*/
public function setColumnWidthForRange(float $width, int $start, int $end)
{
$this->throwIfWorkbookIsNotAvailable();
$this->workbookManager->setColumnWidthForRange($width, $start, $end);
}
/**
* Checks if the workbook has been created. Throws an exception if not created yet.
*
@@ -143,7 +192,7 @@ abstract class WriterMultiSheetsAbstract extends WriterAbstract
*/
protected function throwIfWorkbookIsNotAvailable()
{
if (!$this->workbookManager->getWorkbook()) {
if (empty($this->workbookManager) || !$this->workbookManager->getWorkbook()) {
throw new WriterNotOpenedException('The writer must be opened before performing this action.');
}
}
@@ -39,6 +39,9 @@ class OptionsManager extends OptionsManagerAbstract
Options::DEFAULT_ROW_STYLE,
Options::SHOULD_CREATE_NEW_SHEETS_AUTOMATICALLY,
Options::SHOULD_USE_INLINE_STRINGS,
Options::DEFAULT_COLUMN_WIDTH,
Options::DEFAULT_ROW_HEIGHT,
Options::COLUMN_WIDTHS,
];
}
@@ -15,6 +15,7 @@ use Box\Spout\Writer\Common\Entity\Options;
use Box\Spout\Writer\Common\Entity\Worksheet;
use Box\Spout\Writer\Common\Helper\CellHelper;
use Box\Spout\Writer\Common\Manager\RegisteredStyle;
use Box\Spout\Writer\Common\Manager\ManagesCellSize;
use Box\Spout\Writer\Common\Manager\RowManager;
use Box\Spout\Writer\Common\Manager\Style\StyleMerger;
use Box\Spout\Writer\Common\Manager\WorksheetManagerInterface;
@@ -26,6 +27,8 @@ use Box\Spout\Writer\XLSX\Manager\Style\StyleManager;
*/
class WorksheetManager implements WorksheetManagerInterface
{
use ManagesCellSize;
/**
* Maximum number of characters a cell can contain
* @see https://support.office.com/en-us/article/Excel-specifications-and-limits-16c69c74-3d6a-4aaf-ba35-e6eb276e8eaa [Excel 2007]
@@ -86,6 +89,9 @@ EOD;
InternalEntityFactory $entityFactory
) {
$this->shouldUseInlineStrings = $optionsManager->getOption(Options::SHOULD_USE_INLINE_STRINGS);
$this->setDefaultColumnWidth($optionsManager->getOption(Options::DEFAULT_COLUMN_WIDTH));
$this->setDefaultRowHeight($optionsManager->getOption(Options::DEFAULT_ROW_HEIGHT));
$this->columnWidths = $optionsManager->getOption(Options::COLUMN_WIDTHS) ?? [];
$this->rowManager = $rowManager;
$this->styleManager = $styleManager;
$this->styleMerger = $styleMerger;
@@ -114,7 +120,23 @@ EOD;
$worksheet->setFilePointer($sheetFilePointer);
\fwrite($sheetFilePointer, self::SHEET_XML_FILE_HEADER);
\fwrite($sheetFilePointer, '<sheetData>');
}
/**
* Writes the sheet data header
*
* @param Worksheet $worksheet The worksheet to add the row to
* @return void
*/
private function ensureSheetDataStated(Worksheet $worksheet)
{
if (!$worksheet->getSheetDataStarted()) {
$worksheetFilePointer = $worksheet->getFilePointer();
\fwrite($worksheetFilePointer, $this->getXMLFragmentForDefaultCellSizing());
\fwrite($worksheetFilePointer, $this->getXMLFragmentForColumnWidths());
\fwrite($worksheetFilePointer, '<sheetData>');
$worksheet->setSheetDataStarted(true);
}
}
/**
@@ -154,11 +176,14 @@ EOD;
*/
private function addNonEmptyRow(Worksheet $worksheet, Row $row)
{
$this->ensureSheetDataStated($worksheet);
$sheetFilePointer = $worksheet->getFilePointer();
$rowStyle = $row->getStyle();
$rowIndexOneBased = $worksheet->getLastWrittenRowIndex() + 1;
$numCells = $row->getNumCells();
$rowXML = '<row r="' . $rowIndexOneBased . '" spans="1:' . $numCells . '">';
$hasCustomHeight = $this->defaultRowHeight > 0 ? '1' : '0';
$rowXML = "<row r=\"{$rowIndexOneBased}\" spans=\"1:{$numCells}\" customHeight=\"{$hasCustomHeight}\">";
foreach ($row->getCells() as $columnIndexZeroBased => $cell) {
$registeredStyle = $this->applyStyleAndRegister($cell, $rowStyle);
@@ -171,7 +196,7 @@ EOD;
$rowXML .= '</row>';
$wasWriteSuccessful = \fwrite($worksheet->getFilePointer(), $rowXML);
$wasWriteSuccessful = \fwrite($sheetFilePointer, $rowXML);
if ($wasWriteSuccessful === false) {
throw new IOException("Unable to write data in {$worksheet->getFilePath()}");
}
@@ -283,6 +308,43 @@ EOD;
return $cellXMLFragment;
}
/**
* Construct column width references xml to inject into worksheet xml file
*
* @return string
*/
public function getXMLFragmentForColumnWidths()
{
if (empty($this->columnWidths)) {
return '';
}
$xml = '<cols>';
foreach ($this->columnWidths as $entry) {
$xml .= '<col min="' . $entry[0] . '" max="' . $entry[1] . '" width="' . $entry[2] . '" customWidth="true"/>';
}
$xml .= '</cols>';
return $xml;
}
/**
* Constructs default row height and width xml to inject into worksheet xml file
*
* @return string
*/
public function getXMLFragmentForDefaultCellSizing()
{
$rowHeightXml = empty($this->defaultRowHeight) ? '' : " defaultRowHeight=\"{$this->defaultRowHeight}\"";
$colWidthXml = empty($this->defaultColumnWidth) ? '' : " defaultColWidth=\"{$this->defaultColumnWidth}\"";
if (empty($colWidthXml) && empty($rowHeightXml)) {
return '';
}
// Ensure that the required defaultRowHeight is set
$rowHeightXml = empty($rowHeightXml) ? ' defaultRowHeight="0"' : $rowHeightXml;
return "<sheetFormatPr{$colWidthXml}{$rowHeightXml}/>";
}
/**
* {@inheritdoc}
*/
@@ -294,6 +356,7 @@ EOD;
return;
}
$this->ensureSheetDataStated($worksheet);
\fwrite($worksheetFilePointer, '</sheetData>');
\fwrite($worksheetFilePointer, '</worksheet>');
\fclose($worksheetFilePointer);