first commit
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX\Helper;
|
||||
|
||||
use Box\Spout\Writer\Style\Border;
|
||||
use Box\Spout\Writer\Style\BorderPart;
|
||||
|
||||
class BorderHelper
|
||||
{
|
||||
public static $xlsxStyleMap = [
|
||||
Border::STYLE_SOLID => [
|
||||
Border::WIDTH_THIN => 'thin',
|
||||
Border::WIDTH_MEDIUM => 'medium',
|
||||
Border::WIDTH_THICK => 'thick'
|
||||
],
|
||||
Border::STYLE_DOTTED => [
|
||||
Border::WIDTH_THIN => 'dotted',
|
||||
Border::WIDTH_MEDIUM => 'dotted',
|
||||
Border::WIDTH_THICK => 'dotted',
|
||||
],
|
||||
Border::STYLE_DASHED => [
|
||||
Border::WIDTH_THIN => 'dashed',
|
||||
Border::WIDTH_MEDIUM => 'mediumDashed',
|
||||
Border::WIDTH_THICK => 'mediumDashed',
|
||||
],
|
||||
Border::STYLE_DOUBLE => [
|
||||
Border::WIDTH_THIN => 'double',
|
||||
Border::WIDTH_MEDIUM => 'double',
|
||||
Border::WIDTH_THICK => 'double',
|
||||
],
|
||||
Border::STYLE_NONE => [
|
||||
Border::WIDTH_THIN => 'none',
|
||||
Border::WIDTH_MEDIUM => 'none',
|
||||
Border::WIDTH_THICK => 'none',
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* @param BorderPart $borderPart
|
||||
* @return string
|
||||
*/
|
||||
public static function serializeBorderPart(BorderPart $borderPart)
|
||||
{
|
||||
$borderStyle = self::getBorderStyle($borderPart);
|
||||
|
||||
$colorEl = $borderPart->getColor() ? sprintf('<color rgb="%s"/>', $borderPart->getColor()) : '';
|
||||
$partEl = sprintf(
|
||||
'<%s style="%s">%s</%s>',
|
||||
$borderPart->getName(),
|
||||
$borderStyle,
|
||||
$colorEl,
|
||||
$borderPart->getName()
|
||||
);
|
||||
|
||||
return $partEl . PHP_EOL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the style definition from the style map
|
||||
*
|
||||
* @param BorderPart $borderPart
|
||||
* @return string
|
||||
*/
|
||||
protected static function getBorderStyle(BorderPart $borderPart)
|
||||
{
|
||||
return self::$xlsxStyleMap[$borderPart->getStyle()][$borderPart->getWidth()];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX\Helper;
|
||||
|
||||
use Box\Spout\Writer\Common\Helper\ZipHelper;
|
||||
use Box\Spout\Writer\XLSX\Internal\Worksheet;
|
||||
|
||||
/**
|
||||
* Class FileSystemHelper
|
||||
* This class provides helper functions to help with the file system operations
|
||||
* like files/folders creation & deletion for XLSX files
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX\Helper
|
||||
*/
|
||||
class FileSystemHelper extends \Box\Spout\Common\Helper\FileSystemHelper
|
||||
{
|
||||
const APP_NAME = 'Spout';
|
||||
|
||||
const RELS_FOLDER_NAME = '_rels';
|
||||
const DOC_PROPS_FOLDER_NAME = 'docProps';
|
||||
const XL_FOLDER_NAME = 'xl';
|
||||
const WORKSHEETS_FOLDER_NAME = 'worksheets';
|
||||
|
||||
const RELS_FILE_NAME = '.rels';
|
||||
const APP_XML_FILE_NAME = 'app.xml';
|
||||
const CORE_XML_FILE_NAME = 'core.xml';
|
||||
const CONTENT_TYPES_XML_FILE_NAME = '[Content_Types].xml';
|
||||
const WORKBOOK_XML_FILE_NAME = 'workbook.xml';
|
||||
const WORKBOOK_RELS_XML_FILE_NAME = 'workbook.xml.rels';
|
||||
const STYLES_XML_FILE_NAME = 'styles.xml';
|
||||
|
||||
/** @var string Path to the root folder inside the temp folder where the files to create the XLSX will be stored */
|
||||
protected $rootFolder;
|
||||
|
||||
/** @var string Path to the "_rels" folder inside the root folder */
|
||||
protected $relsFolder;
|
||||
|
||||
/** @var string Path to the "docProps" folder inside the root folder */
|
||||
protected $docPropsFolder;
|
||||
|
||||
/** @var string Path to the "xl" folder inside the root folder */
|
||||
protected $xlFolder;
|
||||
|
||||
/** @var string Path to the "_rels" folder inside the "xl" folder */
|
||||
protected $xlRelsFolder;
|
||||
|
||||
/** @var string Path to the "worksheets" folder inside the "xl" folder */
|
||||
protected $xlWorksheetsFolder;
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getRootFolder()
|
||||
{
|
||||
return $this->rootFolder;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getXlFolder()
|
||||
{
|
||||
return $this->xlFolder;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getXlWorksheetsFolder()
|
||||
{
|
||||
return $this->xlWorksheetsFolder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates all the folders needed to create a XLSX file, as well as the files that won't change.
|
||||
*
|
||||
* @return void
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create at least one of the base folders
|
||||
*/
|
||||
public function createBaseFilesAndFolders()
|
||||
{
|
||||
$this
|
||||
->createRootFolder()
|
||||
->createRelsFolderAndFile()
|
||||
->createDocPropsFolderAndFiles()
|
||||
->createXlFolderAndSubFolders();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the folder that will be used as root
|
||||
*
|
||||
* @return FileSystemHelper
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create the folder
|
||||
*/
|
||||
protected function createRootFolder()
|
||||
{
|
||||
$this->rootFolder = $this->createFolder($this->baseFolderRealPath, uniqid('xlsx', true));
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the "_rels" folder under the root folder as well as the ".rels" file in it
|
||||
*
|
||||
* @return FileSystemHelper
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create the folder or the ".rels" file
|
||||
*/
|
||||
protected function createRelsFolderAndFile()
|
||||
{
|
||||
$this->relsFolder = $this->createFolder($this->rootFolder, self::RELS_FOLDER_NAME);
|
||||
|
||||
$this->createRelsFile();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the ".rels" file under the "_rels" folder (under root)
|
||||
*
|
||||
* @return FileSystemHelper
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create the file
|
||||
*/
|
||||
protected function createRelsFile()
|
||||
{
|
||||
$relsFileContents = <<<EOD
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rIdWorkbook" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
|
||||
<Relationship Id="rIdCore" Type="http://schemas.openxmlformats.org/officedocument/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
|
||||
<Relationship Id="rIdApp" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>
|
||||
</Relationships>
|
||||
EOD;
|
||||
|
||||
$this->createFileWithContents($this->relsFolder, self::RELS_FILE_NAME, $relsFileContents);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the "docProps" folder under the root folder as well as the "app.xml" and "core.xml" files in it
|
||||
*
|
||||
* @return FileSystemHelper
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create the folder or one of the files
|
||||
*/
|
||||
protected function createDocPropsFolderAndFiles()
|
||||
{
|
||||
$this->docPropsFolder = $this->createFolder($this->rootFolder, self::DOC_PROPS_FOLDER_NAME);
|
||||
|
||||
$this->createAppXmlFile();
|
||||
$this->createCoreXmlFile();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the "app.xml" file under the "docProps" folder
|
||||
*
|
||||
* @return FileSystemHelper
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create the file
|
||||
*/
|
||||
protected function createAppXmlFile()
|
||||
{
|
||||
$appName = self::APP_NAME;
|
||||
$appXmlFileContents = <<<EOD
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties">
|
||||
<Application>$appName</Application>
|
||||
<TotalTime>0</TotalTime>
|
||||
</Properties>
|
||||
EOD;
|
||||
|
||||
$this->createFileWithContents($this->docPropsFolder, self::APP_XML_FILE_NAME, $appXmlFileContents);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the "core.xml" file under the "docProps" folder
|
||||
*
|
||||
* @return FileSystemHelper
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create the file
|
||||
*/
|
||||
protected function createCoreXmlFile()
|
||||
{
|
||||
$createdDate = (new \DateTime())->format(\DateTime::W3C);
|
||||
$coreXmlFileContents = <<<EOD
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<dcterms:created xsi:type="dcterms:W3CDTF">$createdDate</dcterms:created>
|
||||
<dcterms:modified xsi:type="dcterms:W3CDTF">$createdDate</dcterms:modified>
|
||||
<cp:revision>0</cp:revision>
|
||||
</cp:coreProperties>
|
||||
EOD;
|
||||
|
||||
$this->createFileWithContents($this->docPropsFolder, self::CORE_XML_FILE_NAME, $coreXmlFileContents);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the "xl" folder under the root folder as well as its subfolders
|
||||
*
|
||||
* @return FileSystemHelper
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create at least one of the folders
|
||||
*/
|
||||
protected function createXlFolderAndSubFolders()
|
||||
{
|
||||
$this->xlFolder = $this->createFolder($this->rootFolder, self::XL_FOLDER_NAME);
|
||||
$this->createXlRelsFolder();
|
||||
$this->createXlWorksheetsFolder();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the "_rels" folder under the "xl" folder
|
||||
*
|
||||
* @return FileSystemHelper
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create the folder
|
||||
*/
|
||||
protected function createXlRelsFolder()
|
||||
{
|
||||
$this->xlRelsFolder = $this->createFolder($this->xlFolder, self::RELS_FOLDER_NAME);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the "worksheets" folder under the "xl" folder
|
||||
*
|
||||
* @return FileSystemHelper
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create the folder
|
||||
*/
|
||||
protected function createXlWorksheetsFolder()
|
||||
{
|
||||
$this->xlWorksheetsFolder = $this->createFolder($this->xlFolder, self::WORKSHEETS_FOLDER_NAME);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the "[Content_Types].xml" file under the root folder
|
||||
*
|
||||
* @param Worksheet[] $worksheets
|
||||
* @return FileSystemHelper
|
||||
*/
|
||||
public function createContentTypesFile($worksheets)
|
||||
{
|
||||
$contentTypesXmlFileContents = <<<EOD
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
||||
<Default ContentType="application/xml" Extension="xml"/>
|
||||
<Default ContentType="application/vnd.openxmlformats-package.relationships+xml" Extension="rels"/>
|
||||
<Override ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml" PartName="/xl/workbook.xml"/>
|
||||
EOD;
|
||||
|
||||
/** @var Worksheet $worksheet */
|
||||
foreach ($worksheets as $worksheet) {
|
||||
$contentTypesXmlFileContents .= '<Override ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" PartName="/xl/worksheets/sheet' . $worksheet->getId() . '.xml"/>';
|
||||
}
|
||||
|
||||
$contentTypesXmlFileContents .= <<<EOD
|
||||
<Override ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml" PartName="/xl/styles.xml"/>
|
||||
<Override ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml" PartName="/xl/sharedStrings.xml"/>
|
||||
<Override ContentType="application/vnd.openxmlformats-package.core-properties+xml" PartName="/docProps/core.xml"/>
|
||||
<Override ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml" PartName="/docProps/app.xml"/>
|
||||
</Types>
|
||||
EOD;
|
||||
|
||||
$this->createFileWithContents($this->rootFolder, self::CONTENT_TYPES_XML_FILE_NAME, $contentTypesXmlFileContents);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the "workbook.xml" file under the "xl" folder
|
||||
*
|
||||
* @param Worksheet[] $worksheets
|
||||
* @return FileSystemHelper
|
||||
*/
|
||||
public function createWorkbookFile($worksheets)
|
||||
{
|
||||
$workbookXmlFileContents = <<<EOD
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
||||
<sheets>
|
||||
EOD;
|
||||
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$escaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
|
||||
|
||||
/** @var Worksheet $worksheet */
|
||||
foreach ($worksheets as $worksheet) {
|
||||
$worksheetName = $worksheet->getExternalSheet()->getName();
|
||||
$worksheetId = $worksheet->getId();
|
||||
$workbookXmlFileContents .= '<sheet name="' . $escaper->escape($worksheetName) . '" sheetId="' . $worksheetId . '" r:id="rIdSheet' . $worksheetId . '"/>';
|
||||
}
|
||||
|
||||
$workbookXmlFileContents .= <<<EOD
|
||||
</sheets>
|
||||
</workbook>
|
||||
EOD;
|
||||
|
||||
$this->createFileWithContents($this->xlFolder, self::WORKBOOK_XML_FILE_NAME, $workbookXmlFileContents);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the "workbook.xml.res" file under the "xl/_res" folder
|
||||
*
|
||||
* @param Worksheet[] $worksheets
|
||||
* @return FileSystemHelper
|
||||
*/
|
||||
public function createWorkbookRelsFile($worksheets)
|
||||
{
|
||||
$workbookRelsXmlFileContents = <<<EOD
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Id="rIdStyles" Target="styles.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"/>
|
||||
<Relationship Id="rIdSharedStrings" Target="sharedStrings.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings"/>
|
||||
EOD;
|
||||
|
||||
/** @var Worksheet $worksheet */
|
||||
foreach ($worksheets as $worksheet) {
|
||||
$worksheetId = $worksheet->getId();
|
||||
$workbookRelsXmlFileContents .= '<Relationship Id="rIdSheet' . $worksheetId . '" Target="worksheets/sheet' . $worksheetId . '.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"/>';
|
||||
}
|
||||
|
||||
$workbookRelsXmlFileContents .= '</Relationships>';
|
||||
|
||||
$this->createFileWithContents($this->xlRelsFolder, self::WORKBOOK_RELS_XML_FILE_NAME, $workbookRelsXmlFileContents);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the "styles.xml" file under the "xl" folder
|
||||
*
|
||||
* @param StyleHelper $styleHelper
|
||||
* @return FileSystemHelper
|
||||
*/
|
||||
public function createStylesFile($styleHelper)
|
||||
{
|
||||
$stylesXmlFileContents = $styleHelper->getStylesXMLFileContent();
|
||||
$this->createFileWithContents($this->xlFolder, self::STYLES_XML_FILE_NAME, $stylesXmlFileContents);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zips the root folder and streams the contents of the zip into the given stream
|
||||
*
|
||||
* @param resource $streamPointer Pointer to the stream to copy the zip
|
||||
* @return void
|
||||
*/
|
||||
public function zipRootFolderAndCopyToStream($streamPointer)
|
||||
{
|
||||
$zipHelper = new ZipHelper($this->rootFolder);
|
||||
|
||||
// In order to have the file's mime type detected properly, files need to be added
|
||||
// to the zip file in a particular order.
|
||||
// "[Content_Types].xml" then at least 2 files located in "xl" folder should be zipped first.
|
||||
$zipHelper->addFileToArchive($this->rootFolder, self::CONTENT_TYPES_XML_FILE_NAME);
|
||||
$zipHelper->addFileToArchive($this->rootFolder, self::XL_FOLDER_NAME . '/' . self::WORKBOOK_XML_FILE_NAME);
|
||||
$zipHelper->addFileToArchive($this->rootFolder, self::XL_FOLDER_NAME . '/' . self::STYLES_XML_FILE_NAME);
|
||||
|
||||
$zipHelper->addFolderToArchive($this->rootFolder, ZipHelper::EXISTING_FILES_SKIP);
|
||||
$zipHelper->closeArchiveAndCopyToStream($streamPointer);
|
||||
|
||||
// once the zip is copied, remove it
|
||||
$this->deleteFile($zipHelper->getZipFilePath());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX\Helper;
|
||||
|
||||
use Box\Spout\Common\Exception\IOException;
|
||||
|
||||
/**
|
||||
* Class SharedStringsHelper
|
||||
* This class provides helper functions to write shared strings
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX\Helper
|
||||
*/
|
||||
class SharedStringsHelper
|
||||
{
|
||||
const SHARED_STRINGS_FILE_NAME = 'sharedStrings.xml';
|
||||
|
||||
const SHARED_STRINGS_XML_FILE_FIRST_PART_HEADER = <<<EOD
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
|
||||
EOD;
|
||||
|
||||
/**
|
||||
* This number must be really big so that the no generated file will have more strings than that.
|
||||
* If the strings number goes above, characters will be overwritten in an unwanted way and will corrupt the file.
|
||||
*/
|
||||
const DEFAULT_STRINGS_COUNT_PART = 'count="9999999999999" uniqueCount="9999999999999"';
|
||||
|
||||
/** @var resource Pointer to the sharedStrings.xml file */
|
||||
protected $sharedStringsFilePointer;
|
||||
|
||||
/** @var int Number of shared strings already written */
|
||||
protected $numSharedStrings = 0;
|
||||
|
||||
/** @var \Box\Spout\Common\Escaper\XLSX Strings escaper */
|
||||
protected $stringsEscaper;
|
||||
|
||||
/**
|
||||
* @param string $xlFolder Path to the "xl" folder
|
||||
*/
|
||||
public function __construct($xlFolder)
|
||||
{
|
||||
$sharedStringsFilePath = $xlFolder . '/' . self::SHARED_STRINGS_FILE_NAME;
|
||||
$this->sharedStringsFilePointer = fopen($sharedStringsFilePath, 'w');
|
||||
|
||||
$this->throwIfSharedStringsFilePointerIsNotAvailable();
|
||||
|
||||
// the headers is split into different parts so that we can fseek and put in the correct count and uniqueCount later
|
||||
$header = self::SHARED_STRINGS_XML_FILE_FIRST_PART_HEADER . ' ' . self::DEFAULT_STRINGS_COUNT_PART . '>';
|
||||
fwrite($this->sharedStringsFilePointer, $header);
|
||||
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$this->stringsEscaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the book has been created. Throws an exception if not created yet.
|
||||
*
|
||||
* @return void
|
||||
* @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
|
||||
*/
|
||||
protected function throwIfSharedStringsFilePointerIsNotAvailable()
|
||||
{
|
||||
if (!$this->sharedStringsFilePointer) {
|
||||
throw new IOException('Unable to open shared strings file for writing.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the given string into the sharedStrings.xml file.
|
||||
* Starting and ending whitespaces are preserved.
|
||||
*
|
||||
* @param string $string
|
||||
* @return int ID of the written shared string
|
||||
*/
|
||||
public function writeString($string)
|
||||
{
|
||||
fwrite($this->sharedStringsFilePointer, '<si><t xml:space="preserve">' . $this->stringsEscaper->escape($string) . '</t></si>');
|
||||
$this->numSharedStrings++;
|
||||
|
||||
// Shared string ID is zero-based
|
||||
return ($this->numSharedStrings - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes writing the data in the sharedStrings.xml file and closes the file.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function close()
|
||||
{
|
||||
if (!is_resource($this->sharedStringsFilePointer)) {
|
||||
return;
|
||||
}
|
||||
|
||||
fwrite($this->sharedStringsFilePointer, '</sst>');
|
||||
|
||||
// Replace the default strings count with the actual number of shared strings in the file header
|
||||
$firstPartHeaderLength = strlen(self::SHARED_STRINGS_XML_FILE_FIRST_PART_HEADER);
|
||||
$defaultStringsCountPartLength = strlen(self::DEFAULT_STRINGS_COUNT_PART);
|
||||
|
||||
// Adding 1 to take into account the space between the last xml attribute and "count"
|
||||
fseek($this->sharedStringsFilePointer, $firstPartHeaderLength + 1);
|
||||
fwrite($this->sharedStringsFilePointer, sprintf("%-{$defaultStringsCountPartLength}s", 'count="' . $this->numSharedStrings . '" uniqueCount="' . $this->numSharedStrings . '"'));
|
||||
|
||||
fclose($this->sharedStringsFilePointer);
|
||||
}
|
||||
}
|
||||
344
modules/x13import/tools/Spout/Writer/XLSX/Helper/StyleHelper.php
Normal file
344
modules/x13import/tools/Spout/Writer/XLSX/Helper/StyleHelper.php
Normal file
@@ -0,0 +1,344 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX\Helper;
|
||||
|
||||
use Box\Spout\Writer\Common\Helper\AbstractStyleHelper;
|
||||
use Box\Spout\Writer\Style\Color;
|
||||
use Box\Spout\Writer\Style\Style;
|
||||
|
||||
/**
|
||||
* Class StyleHelper
|
||||
* This class provides helper functions to manage styles
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX\Helper
|
||||
*/
|
||||
class StyleHelper extends AbstractStyleHelper
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $registeredFills = [];
|
||||
|
||||
/**
|
||||
* @var array [STYLE_ID] => [FILL_ID] maps a style to a fill declaration
|
||||
*/
|
||||
protected $styleIdToFillMappingTable = [];
|
||||
|
||||
/**
|
||||
* Excel preserves two default fills with index 0 and 1
|
||||
* Since Excel is the dominant vendor - we play along here
|
||||
*
|
||||
* @var int The fill index counter for custom fills.
|
||||
*/
|
||||
protected $fillIndex = 2;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $registeredBorders = [];
|
||||
|
||||
/**
|
||||
* @var array [STYLE_ID] => [BORDER_ID] maps a style to a border declaration
|
||||
*/
|
||||
protected $styleIdToBorderMappingTable = [];
|
||||
|
||||
/**
|
||||
* XLSX specific operations on the registered styles
|
||||
*
|
||||
* @param \Box\Spout\Writer\Style\Style $style
|
||||
* @return \Box\Spout\Writer\Style\Style
|
||||
*/
|
||||
public function registerStyle($style)
|
||||
{
|
||||
$registeredStyle = parent::registerStyle($style);
|
||||
$this->registerFill($registeredStyle);
|
||||
$this->registerBorder($registeredStyle);
|
||||
return $registeredStyle;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a fill definition
|
||||
*
|
||||
* @param \Box\Spout\Writer\Style\Style $style
|
||||
*/
|
||||
protected function registerFill($style)
|
||||
{
|
||||
$styleId = $style->getId();
|
||||
|
||||
// Currently - only solid backgrounds are supported
|
||||
// so $backgroundColor is a scalar value (RGB Color)
|
||||
$backgroundColor = $style->getBackgroundColor();
|
||||
|
||||
if ($backgroundColor) {
|
||||
$isBackgroundColorRegistered = isset($this->registeredFills[$backgroundColor]);
|
||||
|
||||
// We need to track the already registered background definitions
|
||||
if ($isBackgroundColorRegistered) {
|
||||
$registeredStyleId = $this->registeredFills[$backgroundColor];
|
||||
$registeredFillId = $this->styleIdToFillMappingTable[$registeredStyleId];
|
||||
$this->styleIdToFillMappingTable[$styleId] = $registeredFillId;
|
||||
} else {
|
||||
$this->registeredFills[$backgroundColor] = $styleId;
|
||||
$this->styleIdToFillMappingTable[$styleId] = $this->fillIndex++;
|
||||
}
|
||||
|
||||
} else {
|
||||
// The fillId maps a style to a fill declaration
|
||||
// When there is no background color definition - we default to 0
|
||||
$this->styleIdToFillMappingTable[$styleId] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a border definition
|
||||
*
|
||||
* @param \Box\Spout\Writer\Style\Style $style
|
||||
*/
|
||||
protected function registerBorder($style)
|
||||
{
|
||||
$styleId = $style->getId();
|
||||
|
||||
if ($style->shouldApplyBorder()) {
|
||||
$border = $style->getBorder();
|
||||
$serializedBorder = serialize($border);
|
||||
|
||||
$isBorderAlreadyRegistered = isset($this->registeredBorders[$serializedBorder]);
|
||||
|
||||
if ($isBorderAlreadyRegistered) {
|
||||
$registeredStyleId = $this->registeredBorders[$serializedBorder];
|
||||
$registeredBorderId = $this->styleIdToBorderMappingTable[$registeredStyleId];
|
||||
$this->styleIdToBorderMappingTable[$styleId] = $registeredBorderId;
|
||||
} else {
|
||||
$this->registeredBorders[$serializedBorder] = $styleId;
|
||||
$this->styleIdToBorderMappingTable[$styleId] = count($this->registeredBorders);
|
||||
}
|
||||
|
||||
} else {
|
||||
// If no border should be applied - the mapping is the default border: 0
|
||||
$this->styleIdToBorderMappingTable[$styleId] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* For empty cells, we can specify a style or not. If no style are specified,
|
||||
* then the software default will be applied. But sometimes, it may be useful
|
||||
* to override this default style, for instance if the cell should have a
|
||||
* background color different than the default one or some borders
|
||||
* (fonts property don't really matter here).
|
||||
*
|
||||
* @param int $styleId
|
||||
* @return bool Whether the cell should define a custom style
|
||||
*/
|
||||
public function shouldApplyStyleOnEmptyCell($styleId)
|
||||
{
|
||||
$hasStyleCustomFill = (isset($this->styleIdToFillMappingTable[$styleId]) && $this->styleIdToFillMappingTable[$styleId] !== 0);
|
||||
$hasStyleCustomBorders = (isset($this->styleIdToBorderMappingTable[$styleId]) && $this->styleIdToBorderMappingTable[$styleId] !== 0);
|
||||
|
||||
return ($hasStyleCustomFill || $hasStyleCustomBorders);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the content of the "styles.xml" file, given a list of styles.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getStylesXMLFileContent()
|
||||
{
|
||||
$content = <<<EOD
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
|
||||
EOD;
|
||||
|
||||
$content .= $this->getFontsSectionContent();
|
||||
$content .= $this->getFillsSectionContent();
|
||||
$content .= $this->getBordersSectionContent();
|
||||
$content .= $this->getCellStyleXfsSectionContent();
|
||||
$content .= $this->getCellXfsSectionContent();
|
||||
$content .= $this->getCellStylesSectionContent();
|
||||
|
||||
$content .= <<<EOD
|
||||
</styleSheet>
|
||||
EOD;
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<fonts>" section.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getFontsSectionContent()
|
||||
{
|
||||
$content = '<fonts count="' . count($this->styleIdToStyleMappingTable) . '">';
|
||||
|
||||
/** @var \Box\Spout\Writer\Style\Style $style */
|
||||
foreach ($this->getRegisteredStyles() as $style) {
|
||||
$content .= '<font>';
|
||||
|
||||
$content .= '<sz val="' . $style->getFontSize() . '"/>';
|
||||
$content .= '<color rgb="' . Color::toARGB($style->getFontColor()) . '"/>';
|
||||
$content .= '<name val="' . $style->getFontName() . '"/>';
|
||||
|
||||
if ($style->isFontBold()) {
|
||||
$content .= '<b/>';
|
||||
}
|
||||
if ($style->isFontItalic()) {
|
||||
$content .= '<i/>';
|
||||
}
|
||||
if ($style->isFontUnderline()) {
|
||||
$content .= '<u/>';
|
||||
}
|
||||
if ($style->isFontStrikethrough()) {
|
||||
$content .= '<strike/>';
|
||||
}
|
||||
|
||||
$content .= '</font>';
|
||||
}
|
||||
|
||||
$content .= '</fonts>';
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<fills>" section.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getFillsSectionContent()
|
||||
{
|
||||
// Excel reserves two default fills
|
||||
$fillsCount = count($this->registeredFills) + 2;
|
||||
$content = sprintf('<fills count="%d">', $fillsCount);
|
||||
|
||||
$content .= '<fill><patternFill patternType="none"/></fill>';
|
||||
$content .= '<fill><patternFill patternType="gray125"/></fill>';
|
||||
|
||||
// The other fills are actually registered by setting a background color
|
||||
foreach ($this->registeredFills as $styleId) {
|
||||
/** @var Style $style */
|
||||
$style = $this->styleIdToStyleMappingTable[$styleId];
|
||||
|
||||
$backgroundColor = $style->getBackgroundColor();
|
||||
$content .= sprintf(
|
||||
'<fill><patternFill patternType="solid"><fgColor rgb="%s"/></patternFill></fill>',
|
||||
$backgroundColor
|
||||
);
|
||||
}
|
||||
|
||||
$content .= '</fills>';
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<borders>" section.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getBordersSectionContent()
|
||||
{
|
||||
|
||||
// There is one default border with index 0
|
||||
$borderCount = count($this->registeredBorders) + 1;
|
||||
|
||||
$content = '<borders count="' . $borderCount . '">';
|
||||
|
||||
// Default border starting at index 0
|
||||
$content .= '<border><left/><right/><top/><bottom/></border>';
|
||||
|
||||
foreach ($this->registeredBorders as $styleId) {
|
||||
/** @var \Box\Spout\Writer\Style\Style $style */
|
||||
$style = $this->styleIdToStyleMappingTable[$styleId];
|
||||
$border = $style->getBorder();
|
||||
$content .= '<border>';
|
||||
|
||||
// @link https://github.com/box/spout/issues/271
|
||||
$sortOrder = ['left', 'right', 'top', 'bottom'];
|
||||
|
||||
foreach ($sortOrder as $partName) {
|
||||
if ($border->hasPart($partName)) {
|
||||
/** @var $part \Box\Spout\Writer\Style\BorderPart */
|
||||
$part = $border->getPart($partName);
|
||||
$content .= BorderHelper::serializeBorderPart($part);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
$content .= '</border>';
|
||||
}
|
||||
|
||||
$content .= '</borders>';
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<cellStyleXfs>" section.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getCellStyleXfsSectionContent()
|
||||
{
|
||||
return <<<EOD
|
||||
<cellStyleXfs count="1">
|
||||
<xf borderId="0" fillId="0" fontId="0" numFmtId="0"/>
|
||||
</cellStyleXfs>
|
||||
EOD;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<cellXfs>" section.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getCellXfsSectionContent()
|
||||
{
|
||||
$registeredStyles = $this->getRegisteredStyles();
|
||||
|
||||
$content = '<cellXfs count="' . count($registeredStyles) . '">';
|
||||
|
||||
foreach ($registeredStyles as $style) {
|
||||
$styleId = $style->getId();
|
||||
$fillId = $this->styleIdToFillMappingTable[$styleId];
|
||||
$borderId = $this->styleIdToBorderMappingTable[$styleId];
|
||||
|
||||
$content .= '<xf numFmtId="0" fontId="' . $styleId . '" fillId="' . $fillId . '" borderId="' . $borderId . '" xfId="0"';
|
||||
|
||||
if ($style->shouldApplyFont()) {
|
||||
$content .= ' applyFont="1"';
|
||||
}
|
||||
|
||||
$content .= sprintf(' applyBorder="%d"', $style->shouldApplyBorder() ? 1 : 0);
|
||||
|
||||
if ($style->shouldWrapText()) {
|
||||
$content .= ' applyAlignment="1">';
|
||||
$content .= '<alignment wrapText="1"/>';
|
||||
$content .= '</xf>';
|
||||
} else {
|
||||
$content .= '/>';
|
||||
}
|
||||
}
|
||||
|
||||
$content .= '</cellXfs>';
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the content of the "<cellStyles>" section.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getCellStylesSectionContent()
|
||||
{
|
||||
return <<<EOD
|
||||
<cellStyles count="1">
|
||||
<cellStyle builtinId="0" name="Normal" xfId="0"/>
|
||||
</cellStyles>
|
||||
EOD;
|
||||
}
|
||||
}
|
||||
135
modules/x13import/tools/Spout/Writer/XLSX/Internal/Workbook.php
Normal file
135
modules/x13import/tools/Spout/Writer/XLSX/Internal/Workbook.php
Normal file
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX\Internal;
|
||||
|
||||
use Box\Spout\Writer\Common\Internal\AbstractWorkbook;
|
||||
use Box\Spout\Writer\XLSX\Helper\FileSystemHelper;
|
||||
use Box\Spout\Writer\XLSX\Helper\SharedStringsHelper;
|
||||
use Box\Spout\Writer\XLSX\Helper\StyleHelper;
|
||||
use Box\Spout\Writer\Common\Sheet;
|
||||
|
||||
/**
|
||||
* Class Workbook
|
||||
* Represents a workbook within a XLSX file.
|
||||
* It provides the functions to work with worksheets.
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX\Internal
|
||||
*/
|
||||
class Workbook extends AbstractWorkbook
|
||||
{
|
||||
/**
|
||||
* Maximum number of rows a XLSX sheet can contain
|
||||
* @see http://office.microsoft.com/en-us/excel-help/excel-specifications-and-limits-HP010073849.aspx
|
||||
*/
|
||||
protected static $maxRowsPerWorksheet = 1048576;
|
||||
|
||||
/** @var bool Whether inline or shared strings should be used */
|
||||
protected $shouldUseInlineStrings;
|
||||
|
||||
/** @var \Box\Spout\Writer\XLSX\Helper\FileSystemHelper Helper to perform file system operations */
|
||||
protected $fileSystemHelper;
|
||||
|
||||
/** @var \Box\Spout\Writer\XLSX\Helper\SharedStringsHelper Helper to write shared strings */
|
||||
protected $sharedStringsHelper;
|
||||
|
||||
/** @var \Box\Spout\Writer\XLSX\Helper\StyleHelper Helper to apply styles */
|
||||
protected $styleHelper;
|
||||
|
||||
/**
|
||||
* @param string $tempFolder
|
||||
* @param bool $shouldUseInlineStrings
|
||||
* @param bool $shouldCreateNewSheetsAutomatically
|
||||
* @param \Box\Spout\Writer\Style\Style $defaultRowStyle
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to create at least one of the base folders
|
||||
*/
|
||||
public function __construct($tempFolder, $shouldUseInlineStrings, $shouldCreateNewSheetsAutomatically, $defaultRowStyle)
|
||||
{
|
||||
parent::__construct($shouldCreateNewSheetsAutomatically, $defaultRowStyle);
|
||||
|
||||
$this->shouldUseInlineStrings = $shouldUseInlineStrings;
|
||||
|
||||
$this->fileSystemHelper = new FileSystemHelper($tempFolder);
|
||||
$this->fileSystemHelper->createBaseFilesAndFolders();
|
||||
|
||||
$this->styleHelper = new StyleHelper($defaultRowStyle);
|
||||
|
||||
// This helper will be shared by all sheets
|
||||
$xlFolder = $this->fileSystemHelper->getXlFolder();
|
||||
$this->sharedStringsHelper = new SharedStringsHelper($xlFolder);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Box\Spout\Writer\XLSX\Helper\StyleHelper Helper to apply styles to XLSX files
|
||||
*/
|
||||
protected function getStyleHelper()
|
||||
{
|
||||
return $this->styleHelper;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int Maximum number of rows/columns a sheet can contain
|
||||
*/
|
||||
protected function getMaxRowsPerWorksheet()
|
||||
{
|
||||
return self::$maxRowsPerWorksheet;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new sheet in the workbook. The current sheet remains unchanged.
|
||||
*
|
||||
* @return Worksheet The created sheet
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to open the sheet for writing
|
||||
*/
|
||||
public function addNewSheet()
|
||||
{
|
||||
$newSheetIndex = count($this->worksheets);
|
||||
$sheet = new Sheet($newSheetIndex, $this->internalId);
|
||||
|
||||
$worksheetFilesFolder = $this->fileSystemHelper->getXlWorksheetsFolder();
|
||||
$worksheet = new Worksheet($sheet, $worksheetFilesFolder, $this->sharedStringsHelper, $this->styleHelper, $this->shouldUseInlineStrings);
|
||||
$this->worksheets[] = $worksheet;
|
||||
|
||||
return $worksheet;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the workbook and all its associated sheets.
|
||||
* All the necessary files are written to disk and zipped together to create the XLSX file.
|
||||
* All the temporary files are then deleted.
|
||||
*
|
||||
* @param resource $finalFilePointer Pointer to the XLSX that will be created
|
||||
* @return void
|
||||
*/
|
||||
public function close($finalFilePointer)
|
||||
{
|
||||
/** @var Worksheet[] $worksheets */
|
||||
$worksheets = $this->worksheets;
|
||||
|
||||
foreach ($worksheets as $worksheet) {
|
||||
$worksheet->close();
|
||||
}
|
||||
|
||||
$this->sharedStringsHelper->close();
|
||||
|
||||
// Finish creating all the necessary files before zipping everything together
|
||||
$this->fileSystemHelper
|
||||
->createContentTypesFile($worksheets)
|
||||
->createWorkbookFile($worksheets)
|
||||
->createWorkbookRelsFile($worksheets)
|
||||
->createStylesFile($this->styleHelper)
|
||||
->zipRootFolderAndCopyToStream($finalFilePointer);
|
||||
|
||||
$this->cleanupTempFolder();
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the root folder created in the temp folder and all its contents.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function cleanupTempFolder()
|
||||
{
|
||||
$xlsxRootFolder = $this->fileSystemHelper->getRootFolder();
|
||||
$this->fileSystemHelper->deleteFolderRecursively($xlsxRootFolder);
|
||||
}
|
||||
}
|
||||
275
modules/x13import/tools/Spout/Writer/XLSX/Internal/Worksheet.php
Normal file
275
modules/x13import/tools/Spout/Writer/XLSX/Internal/Worksheet.php
Normal file
@@ -0,0 +1,275 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX\Internal;
|
||||
|
||||
use Box\Spout\Common\Exception\InvalidArgumentException;
|
||||
use Box\Spout\Common\Exception\IOException;
|
||||
use Box\Spout\Common\Helper\StringHelper;
|
||||
use Box\Spout\Writer\Common\Helper\CellHelper;
|
||||
use Box\Spout\Writer\Common\Internal\WorksheetInterface;
|
||||
|
||||
/**
|
||||
* Class Worksheet
|
||||
* Represents a worksheet within a XLSX file. The difference with the Sheet object is
|
||||
* that this class provides an interface to write data
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX\Internal
|
||||
*/
|
||||
class Worksheet implements WorksheetInterface
|
||||
{
|
||||
/**
|
||||
* 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]
|
||||
* @see https://support.office.com/en-us/article/Excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3 [Excel 2010]
|
||||
* @see https://support.office.com/en-us/article/Excel-specifications-and-limits-ca36e2dc-1f09-4620-b726-67c00b05040f [Excel 2013/2016]
|
||||
*/
|
||||
const MAX_CHARACTERS_PER_CELL = 32767;
|
||||
|
||||
const SHEET_XML_FILE_HEADER = <<<EOD
|
||||
<?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 \Box\Spout\Writer\Common\Sheet The "external" sheet */
|
||||
protected $externalSheet;
|
||||
|
||||
/** @var string Path to the XML file that will contain the sheet data */
|
||||
protected $worksheetFilePath;
|
||||
|
||||
/** @var \Box\Spout\Writer\XLSX\Helper\SharedStringsHelper Helper to write shared strings */
|
||||
protected $sharedStringsHelper;
|
||||
|
||||
/** @var \Box\Spout\Writer\XLSX\Helper\StyleHelper Helper to work with styles */
|
||||
protected $styleHelper;
|
||||
|
||||
/** @var bool Whether inline or shared strings should be used */
|
||||
protected $shouldUseInlineStrings;
|
||||
|
||||
/** @var \Box\Spout\Common\Escaper\XLSX Strings escaper */
|
||||
protected $stringsEscaper;
|
||||
|
||||
/** @var \Box\Spout\Common\Helper\StringHelper String helper */
|
||||
protected $stringHelper;
|
||||
|
||||
/** @var Resource Pointer to the sheet data file (e.g. xl/worksheets/sheet1.xml) */
|
||||
protected $sheetFilePointer;
|
||||
|
||||
/** @var int Index of the last written row */
|
||||
protected $lastWrittenRowIndex = 0;
|
||||
|
||||
/**
|
||||
* @param \Box\Spout\Writer\Common\Sheet $externalSheet The associated "external" sheet
|
||||
* @param string $worksheetFilesFolder Temporary folder where the files to create the XLSX will be stored
|
||||
* @param \Box\Spout\Writer\XLSX\Helper\SharedStringsHelper $sharedStringsHelper Helper for shared strings
|
||||
* @param \Box\Spout\Writer\XLSX\Helper\StyleHelper Helper to work with styles
|
||||
* @param bool $shouldUseInlineStrings Whether inline or shared strings should be used
|
||||
* @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
|
||||
*/
|
||||
public function __construct($externalSheet, $worksheetFilesFolder, $sharedStringsHelper, $styleHelper, $shouldUseInlineStrings)
|
||||
{
|
||||
$this->externalSheet = $externalSheet;
|
||||
$this->sharedStringsHelper = $sharedStringsHelper;
|
||||
$this->styleHelper = $styleHelper;
|
||||
$this->shouldUseInlineStrings = $shouldUseInlineStrings;
|
||||
|
||||
/** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
|
||||
$this->stringsEscaper = \Box\Spout\Common\Escaper\XLSX::getInstance();
|
||||
$this->stringHelper = new StringHelper();
|
||||
|
||||
$this->worksheetFilePath = $worksheetFilesFolder . '/' . strtolower($this->externalSheet->getName()) . '.xml';
|
||||
$this->startSheet();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the worksheet to accept data
|
||||
*
|
||||
* @return void
|
||||
* @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
|
||||
*/
|
||||
protected function startSheet()
|
||||
{
|
||||
$this->sheetFilePointer = fopen($this->worksheetFilePath, 'w');
|
||||
$this->throwIfSheetFilePointerIsNotAvailable();
|
||||
|
||||
fwrite($this->sheetFilePointer, self::SHEET_XML_FILE_HEADER);
|
||||
fwrite($this->sheetFilePointer, '<sheetData>');
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the book has been created. Throws an exception if not created yet.
|
||||
*
|
||||
* @return void
|
||||
* @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
|
||||
*/
|
||||
protected function throwIfSheetFilePointerIsNotAvailable()
|
||||
{
|
||||
if (!$this->sheetFilePointer) {
|
||||
throw new IOException('Unable to open sheet for writing.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Box\Spout\Writer\Common\Sheet The "external" sheet
|
||||
*/
|
||||
public function getExternalSheet()
|
||||
{
|
||||
return $this->externalSheet;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int The index of the last written row
|
||||
*/
|
||||
public function getLastWrittenRowIndex()
|
||||
{
|
||||
return $this->lastWrittenRowIndex;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int The ID of the worksheet
|
||||
*/
|
||||
public function getId()
|
||||
{
|
||||
// sheet index is zero-based, while ID is 1-based
|
||||
return $this->externalSheet->getIndex() + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds data to the worksheet.
|
||||
*
|
||||
* @param array $dataRow Array containing data to be written. Cannot be empty.
|
||||
* Example $dataRow = ['data1', 1234, null, '', 'data5'];
|
||||
* @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row. NULL means use default style.
|
||||
* @return void
|
||||
* @throws \Box\Spout\Common\Exception\IOException If the data cannot be written
|
||||
* @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
|
||||
*/
|
||||
public function addRow($dataRow, $style)
|
||||
{
|
||||
if (!$this->isEmptyRow($dataRow)) {
|
||||
$this->addNonEmptyRow($dataRow, $style);
|
||||
}
|
||||
|
||||
$this->lastWrittenRowIndex++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the given row is empty
|
||||
*
|
||||
* @param array $dataRow Array containing data to be written. Cannot be empty.
|
||||
* Example $dataRow = ['data1', 1234, null, '', 'data5'];
|
||||
* @return bool Whether the given row is empty
|
||||
*/
|
||||
protected function isEmptyRow($dataRow)
|
||||
{
|
||||
$numCells = count($dataRow);
|
||||
// using "reset()" instead of "$dataRow[0]" because $dataRow can be an associative array
|
||||
return ($numCells === 1 && CellHelper::isEmpty(reset($dataRow)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds non empty row to the worksheet.
|
||||
*
|
||||
* @param array $dataRow Array containing data to be written. Cannot be empty.
|
||||
* Example $dataRow = ['data1', 1234, null, '', 'data5'];
|
||||
* @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row. NULL means use default style.
|
||||
* @return void
|
||||
* @throws \Box\Spout\Common\Exception\IOException If the data cannot be written
|
||||
* @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
|
||||
*/
|
||||
protected function addNonEmptyRow($dataRow, $style)
|
||||
{
|
||||
$cellNumber = 0;
|
||||
$rowIndex = $this->lastWrittenRowIndex + 1;
|
||||
$numCells = count($dataRow);
|
||||
|
||||
$rowXML = '<row r="' . $rowIndex . '" spans="1:' . $numCells . '">';
|
||||
|
||||
foreach($dataRow as $cellValue) {
|
||||
$rowXML .= $this->getCellXML($rowIndex, $cellNumber, $cellValue, $style->getId());
|
||||
$cellNumber++;
|
||||
}
|
||||
|
||||
$rowXML .= '</row>';
|
||||
|
||||
$wasWriteSuccessful = fwrite($this->sheetFilePointer, $rowXML);
|
||||
if ($wasWriteSuccessful === false) {
|
||||
throw new IOException("Unable to write data in {$this->worksheetFilePath}");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build and return xml for a single cell.
|
||||
*
|
||||
* @param int $rowIndex
|
||||
* @param int $cellNumber
|
||||
* @param mixed $cellValue
|
||||
* @param int $styleId
|
||||
* @return string
|
||||
* @throws InvalidArgumentException If the given value cannot be processed
|
||||
*/
|
||||
protected function getCellXML($rowIndex, $cellNumber, $cellValue, $styleId)
|
||||
{
|
||||
$columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
|
||||
$cellXML = '<c r="' . $columnIndex . $rowIndex . '"';
|
||||
$cellXML .= ' s="' . $styleId . '"';
|
||||
|
||||
if (CellHelper::isNonEmptyString($cellValue)) {
|
||||
$cellXML .= $this->getCellXMLFragmentForNonEmptyString($cellValue);
|
||||
} else if (CellHelper::isBoolean($cellValue)) {
|
||||
$cellXML .= ' t="b"><v>' . intval($cellValue) . '</v></c>';
|
||||
} else if (CellHelper::isNumeric($cellValue)) {
|
||||
$cellXML .= '><v>' . $cellValue . '</v></c>';
|
||||
} else if (empty($cellValue)) {
|
||||
if ($this->styleHelper->shouldApplyStyleOnEmptyCell($styleId)) {
|
||||
$cellXML .= '/>';
|
||||
} else {
|
||||
// don't write empty cells that do no need styling
|
||||
// NOTE: not appending to $cellXML is the right behavior!!
|
||||
$cellXML = '';
|
||||
}
|
||||
} else {
|
||||
throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cellValue));
|
||||
}
|
||||
|
||||
return $cellXML;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the XML fragment for a cell containing a non empty string
|
||||
*
|
||||
* @param string $cellValue The cell value
|
||||
* @return string The XML fragment representing the cell
|
||||
* @throws InvalidArgumentException If the string exceeds the maximum number of characters allowed per cell
|
||||
*/
|
||||
protected function getCellXMLFragmentForNonEmptyString($cellValue)
|
||||
{
|
||||
if ($this->stringHelper->getStringLength($cellValue) > self::MAX_CHARACTERS_PER_CELL) {
|
||||
throw new InvalidArgumentException('Trying to add a value that exceeds the maximum number of characters allowed in a cell (32,767)');
|
||||
}
|
||||
|
||||
if ($this->shouldUseInlineStrings) {
|
||||
$cellXMLFragment = ' t="inlineStr"><is><t>' . $this->stringsEscaper->escape($cellValue) . '</t></is></c>';
|
||||
} else {
|
||||
$sharedStringId = $this->sharedStringsHelper->writeString($cellValue);
|
||||
$cellXMLFragment = ' t="s"><v>' . $sharedStringId . '</v></c>';
|
||||
}
|
||||
|
||||
return $cellXMLFragment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the worksheet
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function close()
|
||||
{
|
||||
if (!is_resource($this->sheetFilePointer)) {
|
||||
return;
|
||||
}
|
||||
|
||||
fwrite($this->sheetFilePointer, '</sheetData>');
|
||||
fwrite($this->sheetFilePointer, '</worksheet>');
|
||||
fclose($this->sheetFilePointer);
|
||||
}
|
||||
}
|
||||
132
modules/x13import/tools/Spout/Writer/XLSX/Writer.php
Normal file
132
modules/x13import/tools/Spout/Writer/XLSX/Writer.php
Normal file
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace Box\Spout\Writer\XLSX;
|
||||
|
||||
use Box\Spout\Writer\AbstractMultiSheetsWriter;
|
||||
use Box\Spout\Writer\Style\StyleBuilder;
|
||||
use Box\Spout\Writer\XLSX\Internal\Workbook;
|
||||
|
||||
/**
|
||||
* Class Writer
|
||||
* This class provides base support to write data to XLSX files
|
||||
*
|
||||
* @package Box\Spout\Writer\XLSX
|
||||
*/
|
||||
class Writer extends AbstractMultiSheetsWriter
|
||||
{
|
||||
/** Default style font values */
|
||||
const DEFAULT_FONT_SIZE = 12;
|
||||
const DEFAULT_FONT_NAME = 'Calibri';
|
||||
|
||||
/** @var string Content-Type value for the header */
|
||||
protected static $headerContentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||||
|
||||
/** @var string Temporary folder where the files to create the XLSX will be stored */
|
||||
protected $tempFolder;
|
||||
|
||||
/** @var bool Whether inline or shared strings should be used - inline string is more memory efficient */
|
||||
protected $shouldUseInlineStrings = true;
|
||||
|
||||
/** @var Internal\Workbook The workbook for the XLSX file */
|
||||
protected $book;
|
||||
|
||||
/**
|
||||
* Sets a custom temporary folder for creating intermediate files/folders.
|
||||
* This must be set before opening the writer.
|
||||
*
|
||||
* @api
|
||||
* @param string $tempFolder Temporary folder where the files to create the XLSX will be stored
|
||||
* @return Writer
|
||||
* @throws \Box\Spout\Writer\Exception\WriterAlreadyOpenedException If the writer was already opened
|
||||
*/
|
||||
public function setTempFolder($tempFolder)
|
||||
{
|
||||
$this->throwIfWriterAlreadyOpened('Writer must be configured before opening it.');
|
||||
|
||||
$this->tempFolder = $tempFolder;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use inline string to be more memory efficient. If set to false, it will use shared strings.
|
||||
* This must be set before opening the writer.
|
||||
*
|
||||
* @api
|
||||
* @param bool $shouldUseInlineStrings Whether inline or shared strings should be used
|
||||
* @return Writer
|
||||
* @throws \Box\Spout\Writer\Exception\WriterAlreadyOpenedException If the writer was already opened
|
||||
*/
|
||||
public function setShouldUseInlineStrings($shouldUseInlineStrings)
|
||||
{
|
||||
$this->throwIfWriterAlreadyOpened('Writer must be configured before opening it.');
|
||||
|
||||
$this->shouldUseInlineStrings = $shouldUseInlineStrings;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the write and sets the current sheet pointer to a new sheet.
|
||||
*
|
||||
* @return void
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to open the file for writing
|
||||
*/
|
||||
protected function openWriter()
|
||||
{
|
||||
if (!$this->book) {
|
||||
$tempFolder = ($this->tempFolder) ? : sys_get_temp_dir();
|
||||
$this->book = new Workbook($tempFolder, $this->shouldUseInlineStrings, $this->shouldCreateNewSheetsAutomatically, $this->defaultRowStyle);
|
||||
$this->book->addNewSheetAndMakeItCurrent();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Internal\Workbook The workbook representing the file to be written
|
||||
*/
|
||||
protected function getWorkbook()
|
||||
{
|
||||
return $this->book;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds data to the currently opened writer.
|
||||
* If shouldCreateNewSheetsAutomatically option is set to true, it will handle pagination
|
||||
* with the creation of new worksheets if one worksheet has reached its maximum capicity.
|
||||
*
|
||||
* @param array $dataRow Array containing data to be written.
|
||||
* Example $dataRow = ['data1', 1234, null, '', 'data5'];
|
||||
* @param \Box\Spout\Writer\Style\Style $style Style to be applied to the row.
|
||||
* @return void
|
||||
* @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If the book is not created yet
|
||||
* @throws \Box\Spout\Common\Exception\IOException If unable to write data
|
||||
*/
|
||||
protected function addRowToWriter(array $dataRow, $style)
|
||||
{
|
||||
$this->throwIfBookIsNotAvailable();
|
||||
$this->book->addRowToCurrentWorksheet($dataRow, $style);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the default style to be applied to rows.
|
||||
*
|
||||
* @return \Box\Spout\Writer\Style\Style
|
||||
*/
|
||||
protected function getDefaultRowStyle()
|
||||
{
|
||||
return (new StyleBuilder())
|
||||
->setFontSize(self::DEFAULT_FONT_SIZE)
|
||||
->setFontName(self::DEFAULT_FONT_NAME)
|
||||
->build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the writer, preventing any additional writing.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function closeWriter()
|
||||
{
|
||||
if ($this->book) {
|
||||
$this->book->close($this->filePointer);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user