updated-packages

This commit is contained in:
RafficMohammed
2023-01-08 00:13:22 +05:30
parent 3ff7df7487
commit da241bacb6
12659 changed files with 563377 additions and 510538 deletions

View File

@@ -0,0 +1,131 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer;
abstract class BaseWriter implements IWriter
{
/**
* Write charts that are defined in the workbook?
* Identifies whether the Writer should write definitions for any charts that exist in the PhpSpreadsheet object;.
*
* @var bool
*/
protected $includeCharts = false;
/**
* Pre-calculate formulas
* Forces PhpSpreadsheet to recalculate all formulae in a workbook when saving, so that the pre-calculated values are
* immediately available to MS Excel or other office spreadsheet viewer when opening the file.
*
* @var bool
*/
protected $preCalculateFormulas = true;
/**
* Use disk caching where possible?
*
* @var bool
*/
private $useDiskCaching = false;
/**
* Disk caching directory.
*
* @var string
*/
private $diskCachingDirectory = './';
/**
* @var resource
*/
protected $fileHandle;
/**
* @var bool
*/
private $shouldCloseFile;
public function getIncludeCharts()
{
return $this->includeCharts;
}
public function setIncludeCharts($pValue)
{
$this->includeCharts = (bool) $pValue;
return $this;
}
public function getPreCalculateFormulas()
{
return $this->preCalculateFormulas;
}
public function setPreCalculateFormulas($pValue)
{
$this->preCalculateFormulas = (bool) $pValue;
return $this;
}
public function getUseDiskCaching()
{
return $this->useDiskCaching;
}
public function setUseDiskCaching($pValue, $pDirectory = null)
{
$this->useDiskCaching = $pValue;
if ($pDirectory !== null) {
if (is_dir($pDirectory)) {
$this->diskCachingDirectory = $pDirectory;
} else {
throw new Exception("Directory does not exist: $pDirectory");
}
}
return $this;
}
public function getDiskCachingDirectory()
{
return $this->diskCachingDirectory;
}
/**
* Open file handle.
*
* @param resource|string $filename
*/
public function openFileHandle($filename): void
{
if (is_resource($filename)) {
$this->fileHandle = $filename;
$this->shouldCloseFile = false;
return;
}
$fileHandle = $filename ? fopen($filename, 'wb+') : false;
if ($fileHandle === false) {
throw new Exception('Could not open file "' . $filename . '" for writing.');
}
$this->fileHandle = $fileHandle;
$this->shouldCloseFile = true;
}
/**
* Close file handle only if we opened it ourselves.
*/
protected function maybeCloseFileHandle(): void
{
if ($this->shouldCloseFile) {
if (!fclose($this->fileHandle)) {
throw new Exception('Could not close file after writing.');
}
}
}
}

View File

@@ -0,0 +1,352 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Csv extends BaseWriter
{
/**
* PhpSpreadsheet object.
*
* @var Spreadsheet
*/
private $spreadsheet;
/**
* Delimiter.
*
* @var string
*/
private $delimiter = ',';
/**
* Enclosure.
*
* @var string
*/
private $enclosure = '"';
/**
* Line ending.
*
* @var string
*/
private $lineEnding = PHP_EOL;
/**
* Sheet index to write.
*
* @var int
*/
private $sheetIndex = 0;
/**
* Whether to write a BOM (for UTF8).
*
* @var bool
*/
private $useBOM = false;
/**
* Whether to write a Separator line as the first line of the file
* sep=x.
*
* @var bool
*/
private $includeSeparatorLine = false;
/**
* Whether to write a fully Excel compatible CSV file.
*
* @var bool
*/
private $excelCompatibility = false;
/**
* Create a new CSV.
*
* @param Spreadsheet $spreadsheet Spreadsheet object
*/
public function __construct(Spreadsheet $spreadsheet)
{
$this->spreadsheet = $spreadsheet;
}
/**
* Save PhpSpreadsheet to file.
*
* @param resource|string $pFilename
*/
public function save($pFilename): void
{
// Fetch sheet
$sheet = $this->spreadsheet->getSheet($this->sheetIndex);
$saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog();
Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false);
$saveArrayReturnType = Calculation::getArrayReturnType();
Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE);
// Open file
$this->openFileHandle($pFilename);
if ($this->excelCompatibility) {
$this->setUseBOM(true); // Enforce UTF-8 BOM Header
$this->setIncludeSeparatorLine(true); // Set separator line
$this->setEnclosure('"'); // Set enclosure to "
$this->setDelimiter(';'); // Set delimiter to a semi-colon
$this->setLineEnding("\r\n");
}
if ($this->useBOM) {
// Write the UTF-8 BOM code if required
fwrite($this->fileHandle, "\xEF\xBB\xBF");
}
if ($this->includeSeparatorLine) {
// Write the separator line if required
fwrite($this->fileHandle, 'sep=' . $this->getDelimiter() . $this->lineEnding);
}
// Identify the range that we need to extract from the worksheet
$maxCol = $sheet->getHighestDataColumn();
$maxRow = $sheet->getHighestDataRow();
// Write rows to file
for ($row = 1; $row <= $maxRow; ++$row) {
// Convert the row to an array...
$cellsArray = $sheet->rangeToArray('A' . $row . ':' . $maxCol . $row, '', $this->preCalculateFormulas);
// ... and write to the file
$this->writeLine($this->fileHandle, $cellsArray[0]);
}
$this->maybeCloseFileHandle();
Calculation::setArrayReturnType($saveArrayReturnType);
Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
}
/**
* Get delimiter.
*
* @return string
*/
public function getDelimiter()
{
return $this->delimiter;
}
/**
* Set delimiter.
*
* @param string $pValue Delimiter, defaults to ','
*
* @return $this
*/
public function setDelimiter($pValue)
{
$this->delimiter = $pValue;
return $this;
}
/**
* Get enclosure.
*
* @return string
*/
public function getEnclosure()
{
return $this->enclosure;
}
/**
* Set enclosure.
*
* @param string $pValue Enclosure, defaults to "
*
* @return $this
*/
public function setEnclosure($pValue = '"')
{
$this->enclosure = $pValue;
return $this;
}
/**
* Get line ending.
*
* @return string
*/
public function getLineEnding()
{
return $this->lineEnding;
}
/**
* Set line ending.
*
* @param string $pValue Line ending, defaults to OS line ending (PHP_EOL)
*
* @return $this
*/
public function setLineEnding($pValue)
{
$this->lineEnding = $pValue;
return $this;
}
/**
* Get whether BOM should be used.
*
* @return bool
*/
public function getUseBOM()
{
return $this->useBOM;
}
/**
* Set whether BOM should be used.
*
* @param bool $pValue Use UTF-8 byte-order mark? Defaults to false
*
* @return $this
*/
public function setUseBOM($pValue)
{
$this->useBOM = $pValue;
return $this;
}
/**
* Get whether a separator line should be included.
*
* @return bool
*/
public function getIncludeSeparatorLine()
{
return $this->includeSeparatorLine;
}
/**
* Set whether a separator line should be included as the first line of the file.
*
* @param bool $pValue Use separator line? Defaults to false
*
* @return $this
*/
public function setIncludeSeparatorLine($pValue)
{
$this->includeSeparatorLine = $pValue;
return $this;
}
/**
* Get whether the file should be saved with full Excel Compatibility.
*
* @return bool
*/
public function getExcelCompatibility()
{
return $this->excelCompatibility;
}
/**
* Set whether the file should be saved with full Excel Compatibility.
*
* @param bool $pValue Set the file to be written as a fully Excel compatible csv file
* Note that this overrides other settings such as useBOM, enclosure and delimiter
*
* @return $this
*/
public function setExcelCompatibility($pValue)
{
$this->excelCompatibility = $pValue;
return $this;
}
/**
* Get sheet index.
*
* @return int
*/
public function getSheetIndex()
{
return $this->sheetIndex;
}
/**
* Set sheet index.
*
* @param int $pValue Sheet index
*
* @return $this
*/
public function setSheetIndex($pValue)
{
$this->sheetIndex = $pValue;
return $this;
}
private $enclosureRequired = true;
public function setEnclosureRequired(bool $value): self
{
$this->enclosureRequired = $value;
return $this;
}
public function getEnclosureRequired(): bool
{
return $this->enclosureRequired;
}
/**
* Write line to CSV file.
*
* @param resource $pFileHandle PHP filehandle
* @param array $pValues Array containing values in a row
*/
private function writeLine($pFileHandle, array $pValues): void
{
// No leading delimiter
$delimiter = '';
// Build the line
$line = '';
foreach ($pValues as $element) {
// Add delimiter
$line .= $delimiter;
$delimiter = $this->delimiter;
// Escape enclosures
$enclosure = $this->enclosure;
if ($enclosure) {
// If enclosure is not required, use enclosure only if
// element contains newline, delimiter, or enclosure.
if (!$this->enclosureRequired && strpbrk($element, "$delimiter$enclosure\n") === false) {
$enclosure = '';
} else {
$element = str_replace($enclosure, $enclosure . $enclosure, $element);
}
}
// Add enclosed string
$line .= $enclosure . $element . $enclosure;
}
// Add line ending
$line .= $this->lineEnding;
// Write to file
fwrite($pFileHandle, $line);
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
class Exception extends PhpSpreadsheetException
{
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,87 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
interface IWriter
{
/**
* IWriter constructor.
*/
public function __construct(Spreadsheet $spreadsheet);
/**
* Write charts in workbook?
* If this is true, then the Writer will write definitions for any charts that exist in the PhpSpreadsheet object.
* If false (the default) it will ignore any charts defined in the PhpSpreadsheet object.
*
* @return bool
*/
public function getIncludeCharts();
/**
* Set write charts in workbook
* Set to true, to advise the Writer to include any charts that exist in the PhpSpreadsheet object.
* Set to false (the default) to ignore charts.
*
* @param bool $pValue
*
* @return IWriter
*/
public function setIncludeCharts($pValue);
/**
* Get Pre-Calculate Formulas flag
* If this is true (the default), then the writer will recalculate all formulae in a workbook when saving,
* so that the pre-calculated values are immediately available to MS Excel or other office spreadsheet
* viewer when opening the file
* If false, then formulae are not calculated on save. This is faster for saving in PhpSpreadsheet, but slower
* when opening the resulting file in MS Excel, because Excel has to recalculate the formulae itself.
*
* @return bool
*/
public function getPreCalculateFormulas();
/**
* Set Pre-Calculate Formulas
* Set to true (the default) to advise the Writer to calculate all formulae on save
* Set to false to prevent precalculation of formulae on save.
*
* @param bool $pValue Pre-Calculate Formulas?
*
* @return IWriter
*/
public function setPreCalculateFormulas($pValue);
/**
* Save PhpSpreadsheet to file.
*
* @param resource|string $pFilename Name of the file to save
*/
public function save($pFilename);
/**
* Get use disk caching where possible?
*
* @return bool
*/
public function getUseDiskCaching();
/**
* Set use disk caching where possible?
*
* @param bool $pValue
* @param string $pDirectory Disk caching directory
*
* @return IWriter
*/
public function setUseDiskCaching($pValue, $pDirectory = null);
/**
* Get disk caching directory.
*
* @return string
*/
public function getDiskCachingDirectory();
}

View File

@@ -0,0 +1,156 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Content;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Meta;
use PhpOffice\PhpSpreadsheet\Writer\Ods\MetaInf;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Mimetype;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Settings;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Styles;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Thumbnails;
use ZipStream\Exception\OverflowException;
use ZipStream\Option\Archive;
use ZipStream\ZipStream;
class Ods extends BaseWriter
{
/**
* Private writer parts.
*
* @var Ods\WriterPart[]
*/
private $writerParts = [];
/**
* Private PhpSpreadsheet.
*
* @var Spreadsheet
*/
private $spreadSheet;
/**
* Create a new Ods.
*/
public function __construct(Spreadsheet $spreadsheet)
{
$this->setSpreadsheet($spreadsheet);
$writerPartsArray = [
'content' => Content::class,
'meta' => Meta::class,
'meta_inf' => MetaInf::class,
'mimetype' => Mimetype::class,
'settings' => Settings::class,
'styles' => Styles::class,
'thumbnails' => Thumbnails::class,
];
foreach ($writerPartsArray as $writer => $class) {
$this->writerParts[$writer] = new $class($this);
}
}
/**
* Get writer part.
*
* @param string $pPartName Writer part name
*
* @return null|Ods\WriterPart
*/
public function getWriterPart($pPartName)
{
if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) {
return $this->writerParts[strtolower($pPartName)];
}
return null;
}
/**
* Save PhpSpreadsheet to file.
*
* @param resource|string $pFilename
*/
public function save($pFilename): void
{
if (!$this->spreadSheet) {
throw new WriterException('PhpSpreadsheet object unassigned.');
}
// garbage collect
$this->spreadSheet->garbageCollect();
$this->openFileHandle($pFilename);
$zip = $this->createZip();
$zip->addFile('META-INF/manifest.xml', $this->getWriterPart('meta_inf')->writeManifest());
$zip->addFile('Thumbnails/thumbnail.png', $this->getWriterPart('thumbnails')->writeThumbnail());
$zip->addFile('content.xml', $this->getWriterPart('content')->write());
$zip->addFile('meta.xml', $this->getWriterPart('meta')->write());
$zip->addFile('mimetype', $this->getWriterPart('mimetype')->write());
$zip->addFile('settings.xml', $this->getWriterPart('settings')->write());
$zip->addFile('styles.xml', $this->getWriterPart('styles')->write());
// Close file
try {
$zip->finish();
} catch (OverflowException $e) {
throw new WriterException('Could not close resource.');
}
$this->maybeCloseFileHandle();
}
/**
* Create zip object.
*
* @return ZipStream
*/
private function createZip()
{
// Try opening the ZIP file
if (!is_resource($this->fileHandle)) {
throw new WriterException('Could not open resource for writing.');
}
// Create new ZIP stream
$options = new Archive();
$options->setEnableZip64(false);
$options->setOutputStream($this->fileHandle);
return new ZipStream(null, $options);
}
/**
* Get Spreadsheet object.
*
* @return Spreadsheet
*/
public function getSpreadsheet()
{
if ($this->spreadSheet !== null) {
return $this->spreadSheet;
}
throw new WriterException('No PhpSpreadsheet assigned.');
}
/**
* Set Spreadsheet object.
*
* @param Spreadsheet $spreadsheet PhpSpreadsheet object
*
* @return $this
*/
public function setSpreadsheet(Spreadsheet $spreadsheet)
{
$this->spreadSheet = $spreadsheet;
return $this;
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
/**
* @author Alexander Pervakov <frost-nzcr4@jagmort.com>
*/
class Comment
{
public static function write(XMLWriter $objWriter, Cell $cell): void
{
$comments = $cell->getWorksheet()->getComments();
if (!isset($comments[$cell->getCoordinate()])) {
return;
}
$comment = $comments[$cell->getCoordinate()];
$objWriter->startElement('office:annotation');
$objWriter->writeAttribute('svg:width', $comment->getWidth());
$objWriter->writeAttribute('svg:height', $comment->getHeight());
$objWriter->writeAttribute('svg:x', $comment->getMarginLeft());
$objWriter->writeAttribute('svg:y', $comment->getMarginTop());
$objWriter->writeElement('dc:creator', $comment->getAuthor());
$objWriter->writeElement('text:p', $comment->getText()->getPlainText());
$objWriter->endElement();
}
}

View File

@@ -0,0 +1,382 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Font;
use PhpOffice\PhpSpreadsheet\Worksheet\Row;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Writer\Exception;
use PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Comment;
/**
* @author Alexander Pervakov <frost-nzcr4@jagmort.com>
*/
class Content extends WriterPart
{
const NUMBER_COLS_REPEATED_MAX = 1024;
const NUMBER_ROWS_REPEATED_MAX = 1048576;
const CELL_STYLE_PREFIX = 'ce';
private $formulaConvertor;
/**
* Set parent Ods writer.
*/
public function __construct(Ods $writer)
{
parent::__construct($writer);
$this->formulaConvertor = new Formula($this->getParentWriter()->getSpreadsheet()->getDefinedNames());
}
/**
* Write content.xml to XML format.
*
* @return string XML Output
*/
public function write()
{
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8');
// Content
$objWriter->startElement('office:document-content');
$objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0');
$objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0');
$objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0');
$objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0');
$objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0');
$objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0');
$objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
$objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
$objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0');
$objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0');
$objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0');
$objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0');
$objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0');
$objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0');
$objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML');
$objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0');
$objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0');
$objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office');
$objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer');
$objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc');
$objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events');
$objWriter->writeAttribute('xmlns:xforms', 'http://www.w3.org/2002/xforms');
$objWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema');
$objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
$objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report');
$objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2');
$objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml');
$objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#');
$objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table');
$objWriter->writeAttribute('xmlns:field', 'urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0');
$objWriter->writeAttribute('xmlns:formx', 'urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0');
$objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/');
$objWriter->writeAttribute('office:version', '1.2');
$objWriter->writeElement('office:scripts');
$objWriter->writeElement('office:font-face-decls');
// Styles XF
$objWriter->startElement('office:automatic-styles');
$this->writeXfStyles($objWriter, $this->getParentWriter()->getSpreadsheet());
$objWriter->endElement();
$objWriter->startElement('office:body');
$objWriter->startElement('office:spreadsheet');
$objWriter->writeElement('table:calculation-settings');
$this->writeSheets($objWriter);
// Defined names (ranges and formulae)
(new NamedExpressions($objWriter, $this->getParentWriter()->getSpreadsheet(), $this->formulaConvertor))->write();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write sheets.
*/
private function writeSheets(XMLWriter $objWriter): void
{
$spreadsheet = $this->getParentWriter()->getSpreadsheet(); /** @var Spreadsheet $spreadsheet */
$sheetCount = $spreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
$objWriter->startElement('table:table');
$objWriter->writeAttribute('table:name', $spreadsheet->getSheet($i)->getTitle());
$objWriter->writeElement('office:forms');
$objWriter->startElement('table:table-column');
$objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX);
$objWriter->endElement();
$this->writeRows($objWriter, $spreadsheet->getSheet($i));
$objWriter->endElement();
}
}
/**
* Write rows of the specified sheet.
*/
private function writeRows(XMLWriter $objWriter, Worksheet $sheet): void
{
$numberRowsRepeated = self::NUMBER_ROWS_REPEATED_MAX;
$span_row = 0;
$rows = $sheet->getRowIterator();
while ($rows->valid()) {
--$numberRowsRepeated;
$row = $rows->current();
if ($row->getCellIterator()->valid()) {
if ($span_row) {
$objWriter->startElement('table:table-row');
if ($span_row > 1) {
$objWriter->writeAttribute('table:number-rows-repeated', $span_row);
}
$objWriter->startElement('table:table-cell');
$objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX);
$objWriter->endElement();
$objWriter->endElement();
$span_row = 0;
}
$objWriter->startElement('table:table-row');
$this->writeCells($objWriter, $row);
$objWriter->endElement();
} else {
++$span_row;
}
$rows->next();
}
}
/**
* Write cells of the specified row.
*/
private function writeCells(XMLWriter $objWriter, Row $row): void
{
$numberColsRepeated = self::NUMBER_COLS_REPEATED_MAX;
$prevColumn = -1;
$cells = $row->getCellIterator();
while ($cells->valid()) {
/** @var \PhpOffice\PhpSpreadsheet\Cell\Cell $cell */
$cell = $cells->current();
$column = Coordinate::columnIndexFromString($cell->getColumn()) - 1;
$this->writeCellSpan($objWriter, $column, $prevColumn);
$objWriter->startElement('table:table-cell');
$this->writeCellMerge($objWriter, $cell);
// Style XF
$style = $cell->getXfIndex();
if ($style !== null) {
$objWriter->writeAttribute('table:style-name', self::CELL_STYLE_PREFIX . $style);
}
switch ($cell->getDataType()) {
case DataType::TYPE_BOOL:
$objWriter->writeAttribute('office:value-type', 'boolean');
$objWriter->writeAttribute('office:value', $cell->getValue());
$objWriter->writeElement('text:p', $cell->getValue());
break;
case DataType::TYPE_ERROR:
throw new Exception('Writing of error not implemented yet.');
break;
case DataType::TYPE_FORMULA:
$formulaValue = $cell->getValue();
if ($this->getParentWriter()->getPreCalculateFormulas()) {
try {
$formulaValue = $cell->getCalculatedValue();
} catch (Exception $e) {
// don't do anything
}
}
$objWriter->writeAttribute('table:formula', $this->formulaConvertor->convertFormula($cell->getValue()));
if (is_numeric($formulaValue)) {
$objWriter->writeAttribute('office:value-type', 'float');
} else {
$objWriter->writeAttribute('office:value-type', 'string');
}
$objWriter->writeAttribute('office:value', $formulaValue);
$objWriter->writeElement('text:p', $formulaValue);
break;
case DataType::TYPE_INLINE:
throw new Exception('Writing of inline not implemented yet.');
break;
case DataType::TYPE_NUMERIC:
$objWriter->writeAttribute('office:value-type', 'float');
$objWriter->writeAttribute('office:value', $cell->getValue());
$objWriter->writeElement('text:p', $cell->getValue());
break;
case DataType::TYPE_STRING:
$objWriter->writeAttribute('office:value-type', 'string');
$objWriter->writeElement('text:p', $cell->getValue());
break;
}
Comment::write($objWriter, $cell);
$objWriter->endElement();
$prevColumn = $column;
$cells->next();
}
$numberColsRepeated = $numberColsRepeated - $prevColumn - 1;
if ($numberColsRepeated > 0) {
if ($numberColsRepeated > 1) {
$objWriter->startElement('table:table-cell');
$objWriter->writeAttribute('table:number-columns-repeated', $numberColsRepeated);
$objWriter->endElement();
} else {
$objWriter->writeElement('table:table-cell');
}
}
}
/**
* Write span.
*
* @param int $curColumn
* @param int $prevColumn
*/
private function writeCellSpan(XMLWriter $objWriter, $curColumn, $prevColumn): void
{
$diff = $curColumn - $prevColumn - 1;
if (1 === $diff) {
$objWriter->writeElement('table:table-cell');
} elseif ($diff > 1) {
$objWriter->startElement('table:table-cell');
$objWriter->writeAttribute('table:number-columns-repeated', $diff);
$objWriter->endElement();
}
}
/**
* Write XF cell styles.
*/
private function writeXfStyles(XMLWriter $writer, Spreadsheet $spreadsheet): void
{
foreach ($spreadsheet->getCellXfCollection() as $style) {
$writer->startElement('style:style');
$writer->writeAttribute('style:name', self::CELL_STYLE_PREFIX . $style->getIndex());
$writer->writeAttribute('style:family', 'table-cell');
$writer->writeAttribute('style:parent-style-name', 'Default');
// style:text-properties
// Font
$writer->startElement('style:text-properties');
$font = $style->getFont();
if ($font->getBold()) {
$writer->writeAttribute('fo:font-weight', 'bold');
$writer->writeAttribute('style:font-weight-complex', 'bold');
$writer->writeAttribute('style:font-weight-asian', 'bold');
}
if ($font->getItalic()) {
$writer->writeAttribute('fo:font-style', 'italic');
}
if ($color = $font->getColor()) {
$writer->writeAttribute('fo:color', sprintf('#%s', $color->getRGB()));
}
if ($family = $font->getName()) {
$writer->writeAttribute('fo:font-family', $family);
}
if ($size = $font->getSize()) {
$writer->writeAttribute('fo:font-size', sprintf('%.1Fpt', $size));
}
if ($font->getUnderline() && $font->getUnderline() != Font::UNDERLINE_NONE) {
$writer->writeAttribute('style:text-underline-style', 'solid');
$writer->writeAttribute('style:text-underline-width', 'auto');
$writer->writeAttribute('style:text-underline-color', 'font-color');
switch ($font->getUnderline()) {
case Font::UNDERLINE_DOUBLE:
$writer->writeAttribute('style:text-underline-type', 'double');
break;
case Font::UNDERLINE_SINGLE:
$writer->writeAttribute('style:text-underline-type', 'single');
break;
}
}
$writer->endElement(); // Close style:text-properties
// style:table-cell-properties
$writer->startElement('style:table-cell-properties');
$writer->writeAttribute('style:rotation-align', 'none');
// Fill
if ($fill = $style->getFill()) {
switch ($fill->getFillType()) {
case Fill::FILL_SOLID:
$writer->writeAttribute('fo:background-color', sprintf(
'#%s',
strtolower($fill->getStartColor()->getRGB())
));
break;
case Fill::FILL_GRADIENT_LINEAR:
case Fill::FILL_GRADIENT_PATH:
/// TODO :: To be implemented
break;
case Fill::FILL_NONE:
default:
}
}
$writer->endElement(); // Close style:table-cell-properties
// End
$writer->endElement(); // Close style:style
}
}
/**
* Write attributes for merged cell.
*/
private function writeCellMerge(XMLWriter $objWriter, Cell $cell): void
{
if (!$cell->isMergeRangeValueCell()) {
return;
}
$mergeRange = Coordinate::splitRange($cell->getMergeRange());
[$startCell, $endCell] = $mergeRange[0];
$start = Coordinate::coordinateFromString($startCell);
$end = Coordinate::coordinateFromString($endCell);
$columnSpan = Coordinate::columnIndexFromString($end[0]) - Coordinate::columnIndexFromString($start[0]) + 1;
$rowSpan = $end[1] - $start[1] + 1;
$objWriter->writeAttribute('table:number-columns-spanned', $columnSpan);
$objWriter->writeAttribute('table:number-rows-spanned', $rowSpan);
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\DefinedName;
class Formula
{
private $definedNames = [];
/**
* @param DefinedName[] $definedNames
*/
public function __construct(array $definedNames)
{
foreach ($definedNames as $definedName) {
$this->definedNames[] = $definedName->getName();
}
}
public function convertFormula(string $formula, string $worksheetName = ''): string
{
$formula = $this->convertCellReferences($formula, $worksheetName);
$formula = $this->convertDefinedNames($formula);
if (substr($formula, 0, 1) !== '=') {
$formula = '=' . $formula;
}
return 'of:' . $formula;
}
private function convertDefinedNames(string $formula): string
{
$splitCount = preg_match_all(
'/' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '/mui',
$formula,
$splitRanges,
PREG_OFFSET_CAPTURE
);
$lengths = array_map('strlen', array_column($splitRanges[0], 0));
$offsets = array_column($splitRanges[0], 1);
$values = array_column($splitRanges[0], 0);
while ($splitCount > 0) {
--$splitCount;
$length = $lengths[$splitCount];
$offset = $offsets[$splitCount];
$value = $values[$splitCount];
if (in_array($value, $this->definedNames, true)) {
$formula = substr($formula, 0, $offset) . '$$' . $value . substr($formula, $offset + $length);
}
}
return $formula;
}
private function convertCellReferences(string $formula, string $worksheetName): string
{
$splitCount = preg_match_all(
'/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
$formula,
$splitRanges,
PREG_OFFSET_CAPTURE
);
$lengths = array_map('strlen', array_column($splitRanges[0], 0));
$offsets = array_column($splitRanges[0], 1);
$worksheets = $splitRanges[2];
$columns = $splitRanges[6];
$rows = $splitRanges[7];
// Replace any commas in the formula with semi-colons for Ods
// If by chance there are commas in worksheet names, then they will be "fixed" again in the loop
// because we've already extracted worksheet names with our preg_match_all()
$formula = str_replace(',', ';', $formula);
while ($splitCount > 0) {
--$splitCount;
$length = $lengths[$splitCount];
$offset = $offsets[$splitCount];
$worksheet = $worksheets[$splitCount][0];
$column = $columns[$splitCount][0];
$row = $rows[$splitCount][0];
$newRange = '';
if (empty($worksheet)) {
if (($offset === 0) || ($formula[$offset - 1] !== ':')) {
// We need a worksheet
$worksheet = $worksheetName;
}
} else {
$worksheet = str_replace("''", "'", trim($worksheet, "'"));
}
if (!empty($worksheet)) {
$newRange = "['" . str_replace("'", "''", $worksheet) . "'";
} elseif (substr($formula, $offset - 1, 1) !== ':') {
$newRange = '[';
}
$newRange .= '.';
if (!empty($column)) {
$newRange .= $column;
}
if (!empty($row)) {
$newRange .= $row;
}
// close the wrapping [] unless this is the first part of a range
$newRange .= substr($formula, $offset + $length, 1) !== ':' ? ']' : '';
$formula = substr($formula, 0, $offset) . $newRange . substr($formula, $offset + $length);
}
return $formula;
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Meta extends WriterPart
{
/**
* Write meta.xml to XML format.
*
* @param Spreadsheet $spreadsheet
*
* @return string XML Output
*/
public function write(?Spreadsheet $spreadsheet = null)
{
if (!$spreadsheet) {
$spreadsheet = $this->getParentWriter()->getSpreadsheet();
}
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8');
// Meta
$objWriter->startElement('office:document-meta');
$objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0');
$objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
$objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
$objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0');
$objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office');
$objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#');
$objWriter->writeAttribute('office:version', '1.2');
$objWriter->startElement('office:meta');
$objWriter->writeElement('meta:initial-creator', $spreadsheet->getProperties()->getCreator());
$objWriter->writeElement('dc:creator', $spreadsheet->getProperties()->getCreator());
$objWriter->writeElement('meta:creation-date', date(DATE_W3C, $spreadsheet->getProperties()->getCreated()));
$objWriter->writeElement('dc:date', date(DATE_W3C, $spreadsheet->getProperties()->getCreated()));
$objWriter->writeElement('dc:title', $spreadsheet->getProperties()->getTitle());
$objWriter->writeElement('dc:description', $spreadsheet->getProperties()->getDescription());
$objWriter->writeElement('dc:subject', $spreadsheet->getProperties()->getSubject());
$keywords = explode(' ', $spreadsheet->getProperties()->getKeywords());
foreach ($keywords as $keyword) {
$objWriter->writeElement('meta:keyword', $keyword);
}
//<meta:document-statistic meta:table-count="XXX" meta:cell-count="XXX" meta:object-count="XXX"/>
$objWriter->startElement('meta:user-defined');
$objWriter->writeAttribute('meta:name', 'Company');
$objWriter->writeRaw($spreadsheet->getProperties()->getCompany());
$objWriter->endElement();
$objWriter->startElement('meta:user-defined');
$objWriter->writeAttribute('meta:name', 'category');
$objWriter->writeRaw($spreadsheet->getProperties()->getCategory());
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
return $objWriter->getData();
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
class MetaInf extends WriterPart
{
/**
* Write META-INF/manifest.xml to XML format.
*
* @return string XML Output
*/
public function writeManifest()
{
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8');
// Manifest
$objWriter->startElement('manifest:manifest');
$objWriter->writeAttribute('xmlns:manifest', 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0');
$objWriter->writeAttribute('manifest:version', '1.2');
$objWriter->startElement('manifest:file-entry');
$objWriter->writeAttribute('manifest:full-path', '/');
$objWriter->writeAttribute('manifest:version', '1.2');
$objWriter->writeAttribute('manifest:media-type', 'application/vnd.oasis.opendocument.spreadsheet');
$objWriter->endElement();
$objWriter->startElement('manifest:file-entry');
$objWriter->writeAttribute('manifest:full-path', 'meta.xml');
$objWriter->writeAttribute('manifest:media-type', 'text/xml');
$objWriter->endElement();
$objWriter->startElement('manifest:file-entry');
$objWriter->writeAttribute('manifest:full-path', 'settings.xml');
$objWriter->writeAttribute('manifest:media-type', 'text/xml');
$objWriter->endElement();
$objWriter->startElement('manifest:file-entry');
$objWriter->writeAttribute('manifest:full-path', 'content.xml');
$objWriter->writeAttribute('manifest:media-type', 'text/xml');
$objWriter->endElement();
$objWriter->startElement('manifest:file-entry');
$objWriter->writeAttribute('manifest:full-path', 'Thumbnails/thumbnail.png');
$objWriter->writeAttribute('manifest:media-type', 'image/png');
$objWriter->endElement();
$objWriter->startElement('manifest:file-entry');
$objWriter->writeAttribute('manifest:full-path', 'styles.xml');
$objWriter->writeAttribute('manifest:media-type', 'text/xml');
$objWriter->endElement();
$objWriter->endElement();
return $objWriter->getData();
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Mimetype extends WriterPart
{
/**
* Write mimetype to plain text format.
*
* @param Spreadsheet $spreadsheet
*
* @return string XML Output
*/
public function write(?Spreadsheet $spreadsheet = null)
{
return 'application/vnd.oasis.opendocument.spreadsheet';
}
}

View File

@@ -0,0 +1,126 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class NamedExpressions
{
private $objWriter;
private $spreadsheet;
private $formulaConvertor;
public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet, $formulaConvertor)
{
$this->objWriter = $objWriter;
$this->spreadsheet = $spreadsheet;
$this->formulaConvertor = $formulaConvertor;
}
public function write(): void
{
$this->objWriter->startElement('table:named-expressions');
$this->writeExpressions();
$this->objWriter->endElement();
}
private function writeExpressions(): void
{
$definedNames = $this->spreadsheet->getDefinedNames();
foreach ($definedNames as $definedName) {
if ($definedName->isFormula()) {
$this->objWriter->startElement('table:named-expression');
$this->writeNamedFormula($definedName, $this->spreadsheet->getActiveSheet());
} else {
$this->objWriter->startElement('table:named-range');
$this->writeNamedRange($definedName);
}
$this->objWriter->endElement();
}
}
private function writeNamedFormula(DefinedName $definedName, Worksheet $defaultWorksheet): void
{
$this->objWriter->writeAttribute('table:name', $definedName->getName());
$this->objWriter->writeAttribute(
'table:expression',
$this->formulaConvertor->convertFormula($definedName->getValue(), $definedName->getWorksheet()->getTitle())
);
$this->objWriter->writeAttribute('table:base-cell-address', $this->convertAddress(
$definedName,
"'" . (($definedName->getWorksheet() !== null) ? $definedName->getWorksheet()->getTitle() : $defaultWorksheet->getTitle()) . "'!\$A\$1"
));
}
private function writeNamedRange(DefinedName $definedName): void
{
$this->objWriter->writeAttribute('table:name', $definedName->getName());
$this->objWriter->writeAttribute('table:base-cell-address', $this->convertAddress(
$definedName,
"'" . $definedName->getWorksheet()->getTitle() . "'!\$A\$1"
));
$this->objWriter->writeAttribute('table:cell-range-address', $this->convertAddress($definedName, $definedName->getValue()));
}
private function convertAddress(DefinedName $definedName, string $address): string
{
$splitCount = preg_match_all(
'/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
$address,
$splitRanges,
PREG_OFFSET_CAPTURE
);
$lengths = array_map('strlen', array_column($splitRanges[0], 0));
$offsets = array_column($splitRanges[0], 1);
$worksheets = $splitRanges[2];
$columns = $splitRanges[6];
$rows = $splitRanges[7];
while ($splitCount > 0) {
--$splitCount;
$length = $lengths[$splitCount];
$offset = $offsets[$splitCount];
$worksheet = $worksheets[$splitCount][0];
$column = $columns[$splitCount][0];
$row = $rows[$splitCount][0];
$newRange = '';
if (empty($worksheet)) {
if (($offset === 0) || ($address[$offset - 1] !== ':')) {
// We need a worksheet
$worksheet = $definedName->getWorksheet()->getTitle();
}
} else {
$worksheet = str_replace("''", "'", trim($worksheet, "'"));
}
if (!empty($worksheet)) {
$newRange = "'" . str_replace("'", "''", $worksheet) . "'.";
}
if (!empty($column)) {
$newRange .= $column;
}
if (!empty($row)) {
$newRange .= $row;
}
$address = substr($address, 0, $offset) . $newRange . substr($address, $offset + $length);
}
if (substr($address, 0, 1) === '=') {
$address = substr($address, 1);
}
return $address;
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Settings extends WriterPart
{
/**
* Write settings.xml to XML format.
*
* @param Spreadsheet $spreadsheet
*
* @return string XML Output
*/
public function write(?Spreadsheet $spreadsheet = null)
{
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8');
// Settings
$objWriter->startElement('office:document-settings');
$objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0');
$objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
$objWriter->writeAttribute('xmlns:config', 'urn:oasis:names:tc:opendocument:xmlns:config:1.0');
$objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office');
$objWriter->writeAttribute('office:version', '1.2');
$objWriter->startElement('office:settings');
$objWriter->startElement('config:config-item-set');
$objWriter->writeAttribute('config:name', 'ooo:view-settings');
$objWriter->startElement('config:config-item-map-indexed');
$objWriter->writeAttribute('config:name', 'Views');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->startElement('config:config-item-set');
$objWriter->writeAttribute('config:name', 'ooo:configuration-settings');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
return $objWriter->getData();
}
}

View File

@@ -0,0 +1,68 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Styles extends WriterPart
{
/**
* Write styles.xml to XML format.
*
* @param Spreadsheet $spreadsheet
*
* @return string XML Output
*/
public function write(?Spreadsheet $spreadsheet = null)
{
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8');
// Content
$objWriter->startElement('office:document-styles');
$objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0');
$objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0');
$objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0');
$objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0');
$objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0');
$objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0');
$objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
$objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
$objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0');
$objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0');
$objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0');
$objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0');
$objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0');
$objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0');
$objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML');
$objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0');
$objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0');
$objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office');
$objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer');
$objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc');
$objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events');
$objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report');
$objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2');
$objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml');
$objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#');
$objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table');
$objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/');
$objWriter->writeAttribute('office:version', '1.2');
$objWriter->writeElement('office:font-face-decls');
$objWriter->writeElement('office:styles');
$objWriter->writeElement('office:automatic-styles');
$objWriter->writeElement('office:master-styles');
$objWriter->endElement();
return $objWriter->getData();
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Thumbnails extends WriterPart
{
/**
* Write Thumbnails/thumbnail.png to PNG format.
*
* @param Spreadsheet $spreadsheet
*
* @return string XML Output
*/
public function writeThumbnail(?Spreadsheet $spreadsheet = null)
{
return '';
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Writer\Ods;
abstract class WriterPart
{
/**
* Parent Ods object.
*
* @var Ods
*/
private $parentWriter;
/**
* Get Ods writer.
*
* @return Ods
*/
public function getParentWriter()
{
return $this->parentWriter;
}
/**
* Set parent Ods writer.
*/
public function __construct(Ods $writer)
{
$this->parentWriter = $writer;
}
}

View File

@@ -0,0 +1,253 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
abstract class Pdf extends Html
{
/**
* Temporary storage directory.
*
* @var string
*/
protected $tempDir = '';
/**
* Font.
*
* @var string
*/
protected $font = 'freesans';
/**
* Orientation (Over-ride).
*
* @var string
*/
protected $orientation;
/**
* Paper size (Over-ride).
*
* @var int
*/
protected $paperSize;
/**
* Paper Sizes xRef List.
*
* @var array
*/
protected static $paperSizes = [
PageSetup::PAPERSIZE_LETTER => 'LETTER', // (8.5 in. by 11 in.)
PageSetup::PAPERSIZE_LETTER_SMALL => 'LETTER', // (8.5 in. by 11 in.)
PageSetup::PAPERSIZE_TABLOID => [792.00, 1224.00], // (11 in. by 17 in.)
PageSetup::PAPERSIZE_LEDGER => [1224.00, 792.00], // (17 in. by 11 in.)
PageSetup::PAPERSIZE_LEGAL => 'LEGAL', // (8.5 in. by 14 in.)
PageSetup::PAPERSIZE_STATEMENT => [396.00, 612.00], // (5.5 in. by 8.5 in.)
PageSetup::PAPERSIZE_EXECUTIVE => 'EXECUTIVE', // (7.25 in. by 10.5 in.)
PageSetup::PAPERSIZE_A3 => 'A3', // (297 mm by 420 mm)
PageSetup::PAPERSIZE_A4 => 'A4', // (210 mm by 297 mm)
PageSetup::PAPERSIZE_A4_SMALL => 'A4', // (210 mm by 297 mm)
PageSetup::PAPERSIZE_A5 => 'A5', // (148 mm by 210 mm)
PageSetup::PAPERSIZE_B4 => 'B4', // (250 mm by 353 mm)
PageSetup::PAPERSIZE_B5 => 'B5', // (176 mm by 250 mm)
PageSetup::PAPERSIZE_FOLIO => 'FOLIO', // (8.5 in. by 13 in.)
PageSetup::PAPERSIZE_QUARTO => [609.45, 779.53], // (215 mm by 275 mm)
PageSetup::PAPERSIZE_STANDARD_1 => [720.00, 1008.00], // (10 in. by 14 in.)
PageSetup::PAPERSIZE_STANDARD_2 => [792.00, 1224.00], // (11 in. by 17 in.)
PageSetup::PAPERSIZE_NOTE => 'LETTER', // (8.5 in. by 11 in.)
PageSetup::PAPERSIZE_NO9_ENVELOPE => [279.00, 639.00], // (3.875 in. by 8.875 in.)
PageSetup::PAPERSIZE_NO10_ENVELOPE => [297.00, 684.00], // (4.125 in. by 9.5 in.)
PageSetup::PAPERSIZE_NO11_ENVELOPE => [324.00, 747.00], // (4.5 in. by 10.375 in.)
PageSetup::PAPERSIZE_NO12_ENVELOPE => [342.00, 792.00], // (4.75 in. by 11 in.)
PageSetup::PAPERSIZE_NO14_ENVELOPE => [360.00, 828.00], // (5 in. by 11.5 in.)
PageSetup::PAPERSIZE_C => [1224.00, 1584.00], // (17 in. by 22 in.)
PageSetup::PAPERSIZE_D => [1584.00, 2448.00], // (22 in. by 34 in.)
PageSetup::PAPERSIZE_E => [2448.00, 3168.00], // (34 in. by 44 in.)
PageSetup::PAPERSIZE_DL_ENVELOPE => [311.81, 623.62], // (110 mm by 220 mm)
PageSetup::PAPERSIZE_C5_ENVELOPE => 'C5', // (162 mm by 229 mm)
PageSetup::PAPERSIZE_C3_ENVELOPE => 'C3', // (324 mm by 458 mm)
PageSetup::PAPERSIZE_C4_ENVELOPE => 'C4', // (229 mm by 324 mm)
PageSetup::PAPERSIZE_C6_ENVELOPE => 'C6', // (114 mm by 162 mm)
PageSetup::PAPERSIZE_C65_ENVELOPE => [323.15, 649.13], // (114 mm by 229 mm)
PageSetup::PAPERSIZE_B4_ENVELOPE => 'B4', // (250 mm by 353 mm)
PageSetup::PAPERSIZE_B5_ENVELOPE => 'B5', // (176 mm by 250 mm)
PageSetup::PAPERSIZE_B6_ENVELOPE => [498.90, 354.33], // (176 mm by 125 mm)
PageSetup::PAPERSIZE_ITALY_ENVELOPE => [311.81, 651.97], // (110 mm by 230 mm)
PageSetup::PAPERSIZE_MONARCH_ENVELOPE => [279.00, 540.00], // (3.875 in. by 7.5 in.)
PageSetup::PAPERSIZE_6_3_4_ENVELOPE => [261.00, 468.00], // (3.625 in. by 6.5 in.)
PageSetup::PAPERSIZE_US_STANDARD_FANFOLD => [1071.00, 792.00], // (14.875 in. by 11 in.)
PageSetup::PAPERSIZE_GERMAN_STANDARD_FANFOLD => [612.00, 864.00], // (8.5 in. by 12 in.)
PageSetup::PAPERSIZE_GERMAN_LEGAL_FANFOLD => 'FOLIO', // (8.5 in. by 13 in.)
PageSetup::PAPERSIZE_ISO_B4 => 'B4', // (250 mm by 353 mm)
PageSetup::PAPERSIZE_JAPANESE_DOUBLE_POSTCARD => [566.93, 419.53], // (200 mm by 148 mm)
PageSetup::PAPERSIZE_STANDARD_PAPER_1 => [648.00, 792.00], // (9 in. by 11 in.)
PageSetup::PAPERSIZE_STANDARD_PAPER_2 => [720.00, 792.00], // (10 in. by 11 in.)
PageSetup::PAPERSIZE_STANDARD_PAPER_3 => [1080.00, 792.00], // (15 in. by 11 in.)
PageSetup::PAPERSIZE_INVITE_ENVELOPE => [623.62, 623.62], // (220 mm by 220 mm)
PageSetup::PAPERSIZE_LETTER_EXTRA_PAPER => [667.80, 864.00], // (9.275 in. by 12 in.)
PageSetup::PAPERSIZE_LEGAL_EXTRA_PAPER => [667.80, 1080.00], // (9.275 in. by 15 in.)
PageSetup::PAPERSIZE_TABLOID_EXTRA_PAPER => [841.68, 1296.00], // (11.69 in. by 18 in.)
PageSetup::PAPERSIZE_A4_EXTRA_PAPER => [668.98, 912.76], // (236 mm by 322 mm)
PageSetup::PAPERSIZE_LETTER_TRANSVERSE_PAPER => [595.80, 792.00], // (8.275 in. by 11 in.)
PageSetup::PAPERSIZE_A4_TRANSVERSE_PAPER => 'A4', // (210 mm by 297 mm)
PageSetup::PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER => [667.80, 864.00], // (9.275 in. by 12 in.)
PageSetup::PAPERSIZE_SUPERA_SUPERA_A4_PAPER => [643.46, 1009.13], // (227 mm by 356 mm)
PageSetup::PAPERSIZE_SUPERB_SUPERB_A3_PAPER => [864.57, 1380.47], // (305 mm by 487 mm)
PageSetup::PAPERSIZE_LETTER_PLUS_PAPER => [612.00, 913.68], // (8.5 in. by 12.69 in.)
PageSetup::PAPERSIZE_A4_PLUS_PAPER => [595.28, 935.43], // (210 mm by 330 mm)
PageSetup::PAPERSIZE_A5_TRANSVERSE_PAPER => 'A5', // (148 mm by 210 mm)
PageSetup::PAPERSIZE_JIS_B5_TRANSVERSE_PAPER => [515.91, 728.50], // (182 mm by 257 mm)
PageSetup::PAPERSIZE_A3_EXTRA_PAPER => [912.76, 1261.42], // (322 mm by 445 mm)
PageSetup::PAPERSIZE_A5_EXTRA_PAPER => [493.23, 666.14], // (174 mm by 235 mm)
PageSetup::PAPERSIZE_ISO_B5_EXTRA_PAPER => [569.76, 782.36], // (201 mm by 276 mm)
PageSetup::PAPERSIZE_A2_PAPER => 'A2', // (420 mm by 594 mm)
PageSetup::PAPERSIZE_A3_TRANSVERSE_PAPER => 'A3', // (297 mm by 420 mm)
PageSetup::PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER => [912.76, 1261.42], // (322 mm by 445 mm)
];
/**
* Create a new PDF Writer instance.
*
* @param Spreadsheet $spreadsheet Spreadsheet object
*/
public function __construct(Spreadsheet $spreadsheet)
{
parent::__construct($spreadsheet);
//$this->setUseInlineCss(true);
$this->tempDir = File::sysGetTempDir() . '/phpsppdf';
$this->isPdf = true;
}
/**
* Get Font.
*
* @return string
*/
public function getFont()
{
return $this->font;
}
/**
* Set font. Examples:
* 'arialunicid0-chinese-simplified'
* 'arialunicid0-chinese-traditional'
* 'arialunicid0-korean'
* 'arialunicid0-japanese'.
*
* @param string $fontName
*
* @return $this
*/
public function setFont($fontName)
{
$this->font = $fontName;
return $this;
}
/**
* Get Paper Size.
*
* @return int
*/
public function getPaperSize()
{
return $this->paperSize;
}
/**
* Set Paper Size.
*
* @param string $pValue Paper size see PageSetup::PAPERSIZE_*
*
* @return self
*/
public function setPaperSize($pValue)
{
$this->paperSize = $pValue;
return $this;
}
/**
* Get Orientation.
*
* @return string
*/
public function getOrientation()
{
return $this->orientation;
}
/**
* Set Orientation.
*
* @param string $pValue Page orientation see PageSetup::ORIENTATION_*
*
* @return self
*/
public function setOrientation($pValue)
{
$this->orientation = $pValue;
return $this;
}
/**
* Get temporary storage directory.
*
* @return string
*/
public function getTempDir()
{
return $this->tempDir;
}
/**
* Set temporary storage directory.
*
* @param string $pValue Temporary storage directory
*
* @return self
*/
public function setTempDir($pValue)
{
if (is_dir($pValue)) {
$this->tempDir = $pValue;
} else {
throw new WriterException("Directory does not exist: $pValue");
}
return $this;
}
/**
* Save Spreadsheet to PDF file, pre-save.
*
* @param string $pFilename Name of the file to save as
*
* @return resource
*/
protected function prepareForSave($pFilename)
{
// Open file
$this->openFileHandle($pFilename);
return $this->fileHandle;
}
/**
* Save PhpSpreadsheet to PDF file, post-save.
*/
protected function restoreStateAfterSave(): void
{
$this->maybeCloseFileHandle();
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Pdf;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Writer\Pdf;
class Dompdf extends Pdf
{
/**
* Gets the implementation of external PDF library that should be used.
*
* @return \Dompdf\Dompdf implementation
*/
protected function createExternalWriterInstance()
{
return new \Dompdf\Dompdf();
}
/**
* Save Spreadsheet to file.
*
* @param string $pFilename Name of the file to save as
*/
public function save($pFilename): void
{
$fileHandle = parent::prepareForSave($pFilename);
// Default PDF paper size
$paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.)
// Check for paper size and page orientation
if ($this->getSheetIndex() === null) {
$orientation = ($this->spreadsheet->getSheet(0)->getPageSetup()->getOrientation()
== PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
$printPaperSize = $this->spreadsheet->getSheet(0)->getPageSetup()->getPaperSize();
} else {
$orientation = ($this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation()
== PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
$printPaperSize = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize();
}
$orientation = ($orientation == 'L') ? 'landscape' : 'portrait';
// Override Page Orientation
if ($this->getOrientation() !== null) {
$orientation = ($this->getOrientation() == PageSetup::ORIENTATION_DEFAULT)
? PageSetup::ORIENTATION_PORTRAIT
: $this->getOrientation();
}
// Override Paper Size
if ($this->getPaperSize() !== null) {
$printPaperSize = $this->getPaperSize();
}
if (isset(self::$paperSizes[$printPaperSize])) {
$paperSize = self::$paperSizes[$printPaperSize];
}
// Create PDF
$pdf = $this->createExternalWriterInstance();
$pdf->setPaper(strtolower($paperSize), $orientation);
$pdf->loadHtml($this->generateHTMLAll());
$pdf->render();
// Write to file
fwrite($fileHandle, $pdf->output());
parent::restoreStateAfterSave();
}
}

View File

@@ -0,0 +1,106 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Pdf;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Writer\Pdf;
class Mpdf extends Pdf
{
/**
* Gets the implementation of external PDF library that should be used.
*
* @param array $config Configuration array
*
* @return \Mpdf\Mpdf implementation
*/
protected function createExternalWriterInstance($config)
{
return new \Mpdf\Mpdf($config);
}
/**
* Save Spreadsheet to file.
*
* @param string $pFilename Name of the file to save as
*/
public function save($pFilename): void
{
$fileHandle = parent::prepareForSave($pFilename);
// Default PDF paper size
$paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.)
// Check for paper size and page orientation
if (null === $this->getSheetIndex()) {
$orientation = ($this->spreadsheet->getSheet(0)->getPageSetup()->getOrientation()
== PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
$printPaperSize = $this->spreadsheet->getSheet(0)->getPageSetup()->getPaperSize();
} else {
$orientation = ($this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation()
== PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
$printPaperSize = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize();
}
$this->setOrientation($orientation);
// Override Page Orientation
if (null !== $this->getOrientation()) {
$orientation = ($this->getOrientation() == PageSetup::ORIENTATION_DEFAULT)
? PageSetup::ORIENTATION_PORTRAIT
: $this->getOrientation();
}
$orientation = strtoupper($orientation);
// Override Paper Size
if (null !== $this->getPaperSize()) {
$printPaperSize = $this->getPaperSize();
}
if (isset(self::$paperSizes[$printPaperSize])) {
$paperSize = self::$paperSizes[$printPaperSize];
}
// Create PDF
$config = ['tempDir' => $this->tempDir . '/mpdf'];
$pdf = $this->createExternalWriterInstance($config);
$ortmp = $orientation;
$pdf->_setPageSize(strtoupper($paperSize), $ortmp);
$pdf->DefOrientation = $orientation;
$pdf->AddPageByArray([
'orientation' => $orientation,
'margin-left' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getLeft()),
'margin-right' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getRight()),
'margin-top' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getTop()),
'margin-bottom' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getBottom()),
]);
// Document info
$pdf->SetTitle($this->spreadsheet->getProperties()->getTitle());
$pdf->SetAuthor($this->spreadsheet->getProperties()->getCreator());
$pdf->SetSubject($this->spreadsheet->getProperties()->getSubject());
$pdf->SetKeywords($this->spreadsheet->getProperties()->getKeywords());
$pdf->SetCreator($this->spreadsheet->getProperties()->getCreator());
$html = $this->generateHTMLAll();
foreach (\array_chunk(\explode(PHP_EOL, $html), 1000) as $lines) {
$pdf->WriteHTML(\implode(PHP_EOL, $lines));
}
// Write to file
fwrite($fileHandle, $pdf->Output('', 'S'));
parent::restoreStateAfterSave();
}
/**
* Convert inches to mm.
*
* @param float $inches
*
* @return float
*/
private function inchesToMm($inches)
{
return $inches * 25.4;
}
}

View File

@@ -0,0 +1,104 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Pdf;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Writer\Pdf;
class Tcpdf extends Pdf
{
/**
* Create a new PDF Writer instance.
*
* @param Spreadsheet $spreadsheet Spreadsheet object
*/
public function __construct(Spreadsheet $spreadsheet)
{
parent::__construct($spreadsheet);
$this->setUseInlineCss(true);
}
/**
* Gets the implementation of external PDF library that should be used.
*
* @param string $orientation Page orientation
* @param string $unit Unit measure
* @param string $paperSize Paper size
*
* @return \TCPDF implementation
*/
protected function createExternalWriterInstance($orientation, $unit, $paperSize)
{
return new \TCPDF($orientation, $unit, $paperSize);
}
/**
* Save Spreadsheet to file.
*
* @param string $pFilename Name of the file to save as
*/
public function save($pFilename): void
{
$fileHandle = parent::prepareForSave($pFilename);
// Default PDF paper size
$paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.)
// Check for paper size and page orientation
if ($this->getSheetIndex() === null) {
$orientation = ($this->spreadsheet->getSheet(0)->getPageSetup()->getOrientation()
== PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
$printPaperSize = $this->spreadsheet->getSheet(0)->getPageSetup()->getPaperSize();
$printMargins = $this->spreadsheet->getSheet(0)->getPageMargins();
} else {
$orientation = ($this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation()
== PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
$printPaperSize = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize();
$printMargins = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageMargins();
}
// Override Page Orientation
if ($this->getOrientation() !== null) {
$orientation = ($this->getOrientation() == PageSetup::ORIENTATION_LANDSCAPE)
? 'L'
: 'P';
}
// Override Paper Size
if ($this->getPaperSize() !== null) {
$printPaperSize = $this->getPaperSize();
}
if (isset(self::$paperSizes[$printPaperSize])) {
$paperSize = self::$paperSizes[$printPaperSize];
}
// Create PDF
$pdf = $this->createExternalWriterInstance($orientation, 'pt', $paperSize);
$pdf->setFontSubsetting(false);
// Set margins, converting inches to points (using 72 dpi)
$pdf->SetMargins($printMargins->getLeft() * 72, $printMargins->getTop() * 72, $printMargins->getRight() * 72);
$pdf->SetAutoPageBreak(true, $printMargins->getBottom() * 72);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
// Set the appropriate font
$pdf->SetFont($this->getFont());
$pdf->writeHTML($this->generateHTMLAll());
// Document info
$pdf->SetTitle($this->spreadsheet->getProperties()->getTitle());
$pdf->SetAuthor($this->spreadsheet->getProperties()->getCreator());
$pdf->SetSubject($this->spreadsheet->getProperties()->getSubject());
$pdf->SetKeywords($this->spreadsheet->getProperties()->getKeywords());
$pdf->SetCreator($this->spreadsheet->getProperties()->getCreator());
// Write to file
fwrite($fileHandle, $pdf->output($pFilename, 'S'));
parent::restoreStateAfterSave();
}
}

View File

@@ -0,0 +1,901 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\RichText\Run;
use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing;
use PhpOffice\PhpSpreadsheet\Shared\Escher;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE\Blip;
use PhpOffice\PhpSpreadsheet\Shared\OLE;
use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\File;
use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\Root;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
class Xls extends BaseWriter
{
/**
* PhpSpreadsheet object.
*
* @var Spreadsheet
*/
private $spreadsheet;
/**
* Total number of shared strings in workbook.
*
* @var int
*/
private $strTotal = 0;
/**
* Number of unique shared strings in workbook.
*
* @var int
*/
private $strUnique = 0;
/**
* Array of unique shared strings in workbook.
*
* @var array
*/
private $strTable = [];
/**
* Color cache. Mapping between RGB value and color index.
*
* @var array
*/
private $colors;
/**
* Formula parser.
*
* @var \PhpOffice\PhpSpreadsheet\Writer\Xls\Parser
*/
private $parser;
/**
* Identifier clusters for drawings. Used in MSODRAWINGGROUP record.
*
* @var array
*/
private $IDCLs;
/**
* Basic OLE object summary information.
*
* @var array
*/
private $summaryInformation;
/**
* Extended OLE object document summary information.
*
* @var array
*/
private $documentSummaryInformation;
/**
* @var \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook
*/
private $writerWorkbook;
/**
* @var \PhpOffice\PhpSpreadsheet\Writer\Xls\Worksheet[]
*/
private $writerWorksheets;
/**
* Create a new Xls Writer.
*
* @param Spreadsheet $spreadsheet PhpSpreadsheet object
*/
public function __construct(Spreadsheet $spreadsheet)
{
$this->spreadsheet = $spreadsheet;
$this->parser = new Xls\Parser($spreadsheet);
}
/**
* Save Spreadsheet to file.
*
* @param resource|string $pFilename
*/
public function save($pFilename): void
{
// garbage collect
$this->spreadsheet->garbageCollect();
$saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog();
Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false);
$saveDateReturnType = Functions::getReturnDateType();
Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
// initialize colors array
$this->colors = [];
// Initialise workbook writer
$this->writerWorkbook = new Xls\Workbook($this->spreadsheet, $this->strTotal, $this->strUnique, $this->strTable, $this->colors, $this->parser);
// Initialise worksheet writers
$countSheets = $this->spreadsheet->getSheetCount();
for ($i = 0; $i < $countSheets; ++$i) {
$this->writerWorksheets[$i] = new Xls\Worksheet($this->strTotal, $this->strUnique, $this->strTable, $this->colors, $this->parser, $this->preCalculateFormulas, $this->spreadsheet->getSheet($i));
}
// build Escher objects. Escher objects for workbooks needs to be build before Escher object for workbook.
$this->buildWorksheetEschers();
$this->buildWorkbookEscher();
// add 15 identical cell style Xfs
// for now, we use the first cellXf instead of cellStyleXf
$cellXfCollection = $this->spreadsheet->getCellXfCollection();
for ($i = 0; $i < 15; ++$i) {
$this->writerWorkbook->addXfWriter($cellXfCollection[0], true);
}
// add all the cell Xfs
foreach ($this->spreadsheet->getCellXfCollection() as $style) {
$this->writerWorkbook->addXfWriter($style, false);
}
// add fonts from rich text eleemnts
for ($i = 0; $i < $countSheets; ++$i) {
foreach ($this->writerWorksheets[$i]->phpSheet->getCoordinates() as $coordinate) {
$cell = $this->writerWorksheets[$i]->phpSheet->getCell($coordinate);
$cVal = $cell->getValue();
if ($cVal instanceof RichText) {
$elements = $cVal->getRichTextElements();
foreach ($elements as $element) {
if ($element instanceof Run) {
$font = $element->getFont();
$this->writerWorksheets[$i]->fontHashIndex[$font->getHashCode()] = $this->writerWorkbook->addFont($font);
}
}
}
}
}
// initialize OLE file
$workbookStreamName = 'Workbook';
$OLE = new File(OLE::ascToUcs($workbookStreamName));
// Write the worksheet streams before the global workbook stream,
// because the byte sizes of these are needed in the global workbook stream
$worksheetSizes = [];
for ($i = 0; $i < $countSheets; ++$i) {
$this->writerWorksheets[$i]->close();
$worksheetSizes[] = $this->writerWorksheets[$i]->_datasize;
}
// add binary data for global workbook stream
$OLE->append($this->writerWorkbook->writeWorkbook($worksheetSizes));
// add binary data for sheet streams
for ($i = 0; $i < $countSheets; ++$i) {
$OLE->append($this->writerWorksheets[$i]->getData());
}
$this->documentSummaryInformation = $this->writeDocumentSummaryInformation();
// initialize OLE Document Summary Information
if (isset($this->documentSummaryInformation) && !empty($this->documentSummaryInformation)) {
$OLE_DocumentSummaryInformation = new File(OLE::ascToUcs(chr(5) . 'DocumentSummaryInformation'));
$OLE_DocumentSummaryInformation->append($this->documentSummaryInformation);
}
$this->summaryInformation = $this->writeSummaryInformation();
// initialize OLE Summary Information
if (isset($this->summaryInformation) && !empty($this->summaryInformation)) {
$OLE_SummaryInformation = new File(OLE::ascToUcs(chr(5) . 'SummaryInformation'));
$OLE_SummaryInformation->append($this->summaryInformation);
}
// define OLE Parts
$arrRootData = [$OLE];
// initialize OLE Properties file
if (isset($OLE_SummaryInformation)) {
$arrRootData[] = $OLE_SummaryInformation;
}
// initialize OLE Extended Properties file
if (isset($OLE_DocumentSummaryInformation)) {
$arrRootData[] = $OLE_DocumentSummaryInformation;
}
$root = new Root(time(), time(), $arrRootData);
// save the OLE file
$this->openFileHandle($pFilename);
$root->save($this->fileHandle);
$this->maybeCloseFileHandle();
Functions::setReturnDateType($saveDateReturnType);
Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
}
/**
* Build the Worksheet Escher objects.
*/
private function buildWorksheetEschers(): void
{
// 1-based index to BstoreContainer
$blipIndex = 0;
$lastReducedSpId = 0;
$lastSpId = 0;
foreach ($this->spreadsheet->getAllsheets() as $sheet) {
// sheet index
$sheetIndex = $sheet->getParent()->getIndex($sheet);
$escher = null;
// check if there are any shapes for this sheet
$filterRange = $sheet->getAutoFilter()->getRange();
if (count($sheet->getDrawingCollection()) == 0 && empty($filterRange)) {
continue;
}
// create intermediate Escher object
$escher = new Escher();
// dgContainer
$dgContainer = new DgContainer();
// set the drawing index (we use sheet index + 1)
$dgId = $sheet->getParent()->getIndex($sheet) + 1;
$dgContainer->setDgId($dgId);
$escher->setDgContainer($dgContainer);
// spgrContainer
$spgrContainer = new SpgrContainer();
$dgContainer->setSpgrContainer($spgrContainer);
// add one shape which is the group shape
$spContainer = new SpContainer();
$spContainer->setSpgr(true);
$spContainer->setSpType(0);
$spContainer->setSpId(($sheet->getParent()->getIndex($sheet) + 1) << 10);
$spgrContainer->addChild($spContainer);
// add the shapes
$countShapes[$sheetIndex] = 0; // count number of shapes (minus group shape), in sheet
foreach ($sheet->getDrawingCollection() as $drawing) {
++$blipIndex;
++$countShapes[$sheetIndex];
// add the shape
$spContainer = new SpContainer();
// set the shape type
$spContainer->setSpType(0x004B);
// set the shape flag
$spContainer->setSpFlag(0x02);
// set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index)
$reducedSpId = $countShapes[$sheetIndex];
$spId = $reducedSpId | ($sheet->getParent()->getIndex($sheet) + 1) << 10;
$spContainer->setSpId($spId);
// keep track of last reducedSpId
$lastReducedSpId = $reducedSpId;
// keep track of last spId
$lastSpId = $spId;
// set the BLIP index
$spContainer->setOPT(0x4104, $blipIndex);
// set coordinates and offsets, client anchor
$coordinates = $drawing->getCoordinates();
$offsetX = $drawing->getOffsetX();
$offsetY = $drawing->getOffsetY();
$width = $drawing->getWidth();
$height = $drawing->getHeight();
$twoAnchor = \PhpOffice\PhpSpreadsheet\Shared\Xls::oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height);
$spContainer->setStartCoordinates($twoAnchor['startCoordinates']);
$spContainer->setStartOffsetX($twoAnchor['startOffsetX']);
$spContainer->setStartOffsetY($twoAnchor['startOffsetY']);
$spContainer->setEndCoordinates($twoAnchor['endCoordinates']);
$spContainer->setEndOffsetX($twoAnchor['endOffsetX']);
$spContainer->setEndOffsetY($twoAnchor['endOffsetY']);
$spgrContainer->addChild($spContainer);
}
// AutoFilters
if (!empty($filterRange)) {
$rangeBounds = Coordinate::rangeBoundaries($filterRange);
$iNumColStart = $rangeBounds[0][0];
$iNumColEnd = $rangeBounds[1][0];
$iInc = $iNumColStart;
while ($iInc <= $iNumColEnd) {
++$countShapes[$sheetIndex];
// create an Drawing Object for the dropdown
$oDrawing = new BaseDrawing();
// get the coordinates of drawing
$cDrawing = Coordinate::stringFromColumnIndex($iInc) . $rangeBounds[0][1];
$oDrawing->setCoordinates($cDrawing);
$oDrawing->setWorksheet($sheet);
// add the shape
$spContainer = new SpContainer();
// set the shape type
$spContainer->setSpType(0x00C9);
// set the shape flag
$spContainer->setSpFlag(0x01);
// set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index)
$reducedSpId = $countShapes[$sheetIndex];
$spId = $reducedSpId | ($sheet->getParent()->getIndex($sheet) + 1) << 10;
$spContainer->setSpId($spId);
// keep track of last reducedSpId
$lastReducedSpId = $reducedSpId;
// keep track of last spId
$lastSpId = $spId;
$spContainer->setOPT(0x007F, 0x01040104); // Protection -> fLockAgainstGrouping
$spContainer->setOPT(0x00BF, 0x00080008); // Text -> fFitTextToShape
$spContainer->setOPT(0x01BF, 0x00010000); // Fill Style -> fNoFillHitTest
$spContainer->setOPT(0x01FF, 0x00080000); // Line Style -> fNoLineDrawDash
$spContainer->setOPT(0x03BF, 0x000A0000); // Group Shape -> fPrint
// set coordinates and offsets, client anchor
$endCoordinates = Coordinate::stringFromColumnIndex($iInc);
$endCoordinates .= $rangeBounds[0][1] + 1;
$spContainer->setStartCoordinates($cDrawing);
$spContainer->setStartOffsetX(0);
$spContainer->setStartOffsetY(0);
$spContainer->setEndCoordinates($endCoordinates);
$spContainer->setEndOffsetX(0);
$spContainer->setEndOffsetY(0);
$spgrContainer->addChild($spContainer);
++$iInc;
}
}
// identifier clusters, used for workbook Escher object
$this->IDCLs[$dgId] = $lastReducedSpId;
// set last shape index
$dgContainer->setLastSpId($lastSpId);
// set the Escher object
$this->writerWorksheets[$sheetIndex]->setEscher($escher);
}
}
private function processMemoryDrawing(BstoreContainer &$bstoreContainer, BaseDrawing $drawing, string $renderingFunctionx): void
{
switch ($renderingFunctionx) {
case MemoryDrawing::RENDERING_JPEG:
$blipType = BSE::BLIPTYPE_JPEG;
$renderingFunction = 'imagejpeg';
break;
default:
$blipType = BSE::BLIPTYPE_PNG;
$renderingFunction = 'imagepng';
break;
}
ob_start();
call_user_func($renderingFunction, $drawing->getImageResource());
$blipData = ob_get_contents();
ob_end_clean();
$blip = new Blip();
$blip->setData($blipData);
$BSE = new BSE();
$BSE->setBlipType($blipType);
$BSE->setBlip($blip);
$bstoreContainer->addBSE($BSE);
}
private function processDrawing(BstoreContainer &$bstoreContainer, BaseDrawing $drawing): void
{
$blipData = '';
$filename = $drawing->getPath();
[$imagesx, $imagesy, $imageFormat] = getimagesize($filename);
switch ($imageFormat) {
case 1: // GIF, not supported by BIFF8, we convert to PNG
$blipType = BSE::BLIPTYPE_PNG;
ob_start();
imagepng(imagecreatefromgif($filename));
$blipData = ob_get_contents();
ob_end_clean();
break;
case 2: // JPEG
$blipType = BSE::BLIPTYPE_JPEG;
$blipData = file_get_contents($filename);
break;
case 3: // PNG
$blipType = BSE::BLIPTYPE_PNG;
$blipData = file_get_contents($filename);
break;
case 6: // Windows DIB (BMP), we convert to PNG
$blipType = BSE::BLIPTYPE_PNG;
ob_start();
imagepng(SharedDrawing::imagecreatefrombmp($filename));
$blipData = ob_get_contents();
ob_end_clean();
break;
}
if ($blipData) {
$blip = new Blip();
$blip->setData($blipData);
$BSE = new BSE();
$BSE->setBlipType($blipType);
$BSE->setBlip($blip);
$bstoreContainer->addBSE($BSE);
}
}
private function processBaseDrawing(BstoreContainer &$bstoreContainer, BaseDrawing $drawing): void
{
if ($drawing instanceof Drawing) {
$this->processDrawing($bstoreContainer, $drawing);
} elseif ($drawing instanceof MemoryDrawing) {
$this->processMemoryDrawing($bstoreContainer, $drawing, $drawing->getRenderingFunction());
}
}
private function checkForDrawings(): bool
{
// any drawings in this workbook?
$found = false;
foreach ($this->spreadsheet->getAllSheets() as $sheet) {
if (count($sheet->getDrawingCollection()) > 0) {
$found = true;
break;
}
}
return $found;
}
/**
* Build the Escher object corresponding to the MSODRAWINGGROUP record.
*/
private function buildWorkbookEscher(): void
{
// nothing to do if there are no drawings
if (!$this->checkForDrawings()) {
return;
}
// if we reach here, then there are drawings in the workbook
$escher = new Escher();
// dggContainer
$dggContainer = new DggContainer();
$escher->setDggContainer($dggContainer);
// set IDCLs (identifier clusters)
$dggContainer->setIDCLs($this->IDCLs);
// this loop is for determining maximum shape identifier of all drawing
$spIdMax = 0;
$totalCountShapes = 0;
$countDrawings = 0;
foreach ($this->spreadsheet->getAllsheets() as $sheet) {
$sheetCountShapes = 0; // count number of shapes (minus group shape), in sheet
$addCount = 0;
foreach ($sheet->getDrawingCollection() as $drawing) {
$addCount = 1;
++$sheetCountShapes;
++$totalCountShapes;
$spId = $sheetCountShapes | ($this->spreadsheet->getIndex($sheet) + 1) << 10;
$spIdMax = max($spId, $spIdMax);
}
$countDrawings += $addCount;
}
$dggContainer->setSpIdMax($spIdMax + 1);
$dggContainer->setCDgSaved($countDrawings);
$dggContainer->setCSpSaved($totalCountShapes + $countDrawings); // total number of shapes incl. one group shapes per drawing
// bstoreContainer
$bstoreContainer = new BstoreContainer();
$dggContainer->setBstoreContainer($bstoreContainer);
// the BSE's (all the images)
foreach ($this->spreadsheet->getAllsheets() as $sheet) {
foreach ($sheet->getDrawingCollection() as $drawing) {
$this->processBaseDrawing($bstoreContainer, $drawing);
}
}
// Set the Escher object
$this->writerWorkbook->setEscher($escher);
}
/**
* Build the OLE Part for DocumentSummary Information.
*
* @return string
*/
private function writeDocumentSummaryInformation()
{
// offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
$data = pack('v', 0xFFFE);
// offset: 2; size: 2;
$data .= pack('v', 0x0000);
// offset: 4; size: 2; OS version
$data .= pack('v', 0x0106);
// offset: 6; size: 2; OS indicator
$data .= pack('v', 0x0002);
// offset: 8; size: 16
$data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00);
// offset: 24; size: 4; section count
$data .= pack('V', 0x0001);
// offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae
$data .= pack('vvvvvvvv', 0xD502, 0xD5CD, 0x2E9C, 0x101B, 0x9793, 0x0008, 0x2C2B, 0xAEF9);
// offset: 44; size: 4; offset of the start
$data .= pack('V', 0x30);
// SECTION
$dataSection = [];
$dataSection_NumProps = 0;
$dataSection_Summary = '';
$dataSection_Content = '';
// GKPIDDSI_CODEPAGE: CodePage
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x01],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x02], // 2 byte signed integer
'data' => ['data' => 1252],
];
++$dataSection_NumProps;
// GKPIDDSI_CATEGORY : Category
$dataProp = $this->spreadsheet->getProperties()->getCategory();
if ($dataProp) {
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x02],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x1E],
'data' => ['data' => $dataProp, 'length' => strlen($dataProp)],
];
++$dataSection_NumProps;
}
// GKPIDDSI_VERSION :Version of the application that wrote the property storage
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x17],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x03],
'data' => ['pack' => 'V', 'data' => 0x000C0000],
];
++$dataSection_NumProps;
// GKPIDDSI_SCALE : FALSE
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x0B],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x0B],
'data' => ['data' => false],
];
++$dataSection_NumProps;
// GKPIDDSI_LINKSDIRTY : True if any of the values for the linked properties have changed outside of the application
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x10],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x0B],
'data' => ['data' => false],
];
++$dataSection_NumProps;
// GKPIDDSI_SHAREDOC : FALSE
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x13],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x0B],
'data' => ['data' => false],
];
++$dataSection_NumProps;
// GKPIDDSI_HYPERLINKSCHANGED : True if any of the values for the _PID_LINKS (hyperlink text) have changed outside of the application
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x16],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x0B],
'data' => ['data' => false],
];
++$dataSection_NumProps;
// GKPIDDSI_DOCSPARTS
// MS-OSHARED p75 (2.3.3.2.2.1)
// Structure is VtVecUnalignedLpstrValue (2.3.3.1.9)
// cElements
$dataProp = pack('v', 0x0001);
$dataProp .= pack('v', 0x0000);
// array of UnalignedLpstr
// cch
$dataProp .= pack('v', 0x000A);
$dataProp .= pack('v', 0x0000);
// value
$dataProp .= 'Worksheet' . chr(0);
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x0D],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x101E],
'data' => ['data' => $dataProp, 'length' => strlen($dataProp)],
];
++$dataSection_NumProps;
// GKPIDDSI_HEADINGPAIR
// VtVecHeadingPairValue
// cElements
$dataProp = pack('v', 0x0002);
$dataProp .= pack('v', 0x0000);
// Array of vtHeadingPair
// vtUnalignedString - headingString
// stringType
$dataProp .= pack('v', 0x001E);
// padding
$dataProp .= pack('v', 0x0000);
// UnalignedLpstr
// cch
$dataProp .= pack('v', 0x0013);
$dataProp .= pack('v', 0x0000);
// value
$dataProp .= 'Feuilles de calcul';
// vtUnalignedString - headingParts
// wType : 0x0003 = 32 bit signed integer
$dataProp .= pack('v', 0x0300);
// padding
$dataProp .= pack('v', 0x0000);
// value
$dataProp .= pack('v', 0x0100);
$dataProp .= pack('v', 0x0000);
$dataProp .= pack('v', 0x0000);
$dataProp .= pack('v', 0x0000);
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x0C],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x100C],
'data' => ['data' => $dataProp, 'length' => strlen($dataProp)],
];
++$dataSection_NumProps;
// 4 Section Length
// 4 Property count
// 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4))
$dataSection_Content_Offset = 8 + $dataSection_NumProps * 8;
foreach ($dataSection as $dataProp) {
// Summary
$dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']);
// Offset
$dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset);
// DataType
$dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']);
// Data
if ($dataProp['type']['data'] == 0x02) { // 2 byte signed integer
$dataSection_Content .= pack('V', $dataProp['data']['data']);
$dataSection_Content_Offset += 4 + 4;
} elseif ($dataProp['type']['data'] == 0x03) { // 4 byte signed integer
$dataSection_Content .= pack('V', $dataProp['data']['data']);
$dataSection_Content_Offset += 4 + 4;
} elseif ($dataProp['type']['data'] == 0x0B) { // Boolean
$dataSection_Content .= pack('V', (int) $dataProp['data']['data']);
$dataSection_Content_Offset += 4 + 4;
} elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length
// Null-terminated string
$dataProp['data']['data'] .= chr(0);
++$dataProp['data']['length'];
// Complete the string with null string for being a %4
$dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4) == 4 ? 0 : (4 - $dataProp['data']['length'] % 4));
$dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT);
$dataSection_Content .= pack('V', $dataProp['data']['length']);
$dataSection_Content .= $dataProp['data']['data'];
$dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']);
// Condition below can never be true
//} elseif ($dataProp['type']['data'] == 0x40) { // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
// $dataSection_Content .= $dataProp['data']['data'];
// $dataSection_Content_Offset += 4 + 8;
} else {
$dataSection_Content .= $dataProp['data']['data'];
$dataSection_Content_Offset += 4 + $dataProp['data']['length'];
}
}
// Now $dataSection_Content_Offset contains the size of the content
// section header
// offset: $secOffset; size: 4; section length
// + x Size of the content (summary + content)
$data .= pack('V', $dataSection_Content_Offset);
// offset: $secOffset+4; size: 4; property count
$data .= pack('V', $dataSection_NumProps);
// Section Summary
$data .= $dataSection_Summary;
// Section Content
$data .= $dataSection_Content;
return $data;
}
private function writeSummaryPropOle(int $dataProp, int &$dataSection_NumProps, array &$dataSection, int $sumdata, int $typdata): void
{
if ($dataProp) {
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => $sumdata],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => $typdata], // null-terminated string prepended by dword string length
'data' => ['data' => OLE::localDateToOLE($dataProp)],
];
++$dataSection_NumProps;
}
}
private function writeSummaryProp(string $dataProp, int &$dataSection_NumProps, array &$dataSection, int $sumdata, int $typdata): void
{
if ($dataProp) {
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => $sumdata],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => $typdata], // null-terminated string prepended by dword string length
'data' => ['data' => $dataProp, 'length' => strlen($dataProp)],
];
++$dataSection_NumProps;
}
}
/**
* Build the OLE Part for Summary Information.
*
* @return string
*/
private function writeSummaryInformation()
{
// offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
$data = pack('v', 0xFFFE);
// offset: 2; size: 2;
$data .= pack('v', 0x0000);
// offset: 4; size: 2; OS version
$data .= pack('v', 0x0106);
// offset: 6; size: 2; OS indicator
$data .= pack('v', 0x0002);
// offset: 8; size: 16
$data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00);
// offset: 24; size: 4; section count
$data .= pack('V', 0x0001);
// offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9
$data .= pack('vvvvvvvv', 0x85E0, 0xF29F, 0x4FF9, 0x1068, 0x91AB, 0x0008, 0x272B, 0xD9B3);
// offset: 44; size: 4; offset of the start
$data .= pack('V', 0x30);
// SECTION
$dataSection = [];
$dataSection_NumProps = 0;
$dataSection_Summary = '';
$dataSection_Content = '';
// CodePage : CP-1252
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x01],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x02], // 2 byte signed integer
'data' => ['data' => 1252],
];
++$dataSection_NumProps;
$props = $this->spreadsheet->getProperties();
$this->writeSummaryProp($props->getTitle(), $dataSection_NumProps, $dataSection, 0x02, 0x1e);
$this->writeSummaryProp($props->getSubject(), $dataSection_NumProps, $dataSection, 0x03, 0x1e);
$this->writeSummaryProp($props->getCreator(), $dataSection_NumProps, $dataSection, 0x04, 0x1e);
$this->writeSummaryProp($props->getKeywords(), $dataSection_NumProps, $dataSection, 0x05, 0x1e);
$this->writeSummaryProp($props->getDescription(), $dataSection_NumProps, $dataSection, 0x06, 0x1e);
$this->writeSummaryProp($props->getLastModifiedBy(), $dataSection_NumProps, $dataSection, 0x08, 0x1e);
$this->writeSummaryPropOle($props->getCreated(), $dataSection_NumProps, $dataSection, 0x0c, 0x40);
$this->writeSummaryPropOle($props->getModified(), $dataSection_NumProps, $dataSection, 0x0d, 0x40);
// Security
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x13],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x03], // 4 byte signed integer
'data' => ['data' => 0x00],
];
++$dataSection_NumProps;
// 4 Section Length
// 4 Property count
// 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4))
$dataSection_Content_Offset = 8 + $dataSection_NumProps * 8;
foreach ($dataSection as $dataProp) {
// Summary
$dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']);
// Offset
$dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset);
// DataType
$dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']);
// Data
if ($dataProp['type']['data'] == 0x02) { // 2 byte signed integer
$dataSection_Content .= pack('V', $dataProp['data']['data']);
$dataSection_Content_Offset += 4 + 4;
} elseif ($dataProp['type']['data'] == 0x03) { // 4 byte signed integer
$dataSection_Content .= pack('V', $dataProp['data']['data']);
$dataSection_Content_Offset += 4 + 4;
} elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length
// Null-terminated string
$dataProp['data']['data'] .= chr(0);
++$dataProp['data']['length'];
// Complete the string with null string for being a %4
$dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4) == 4 ? 0 : (4 - $dataProp['data']['length'] % 4));
$dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT);
$dataSection_Content .= pack('V', $dataProp['data']['length']);
$dataSection_Content .= $dataProp['data']['data'];
$dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']);
} elseif ($dataProp['type']['data'] == 0x40) { // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
$dataSection_Content .= $dataProp['data']['data'];
$dataSection_Content_Offset += 4 + 8;
}
// Data Type Not Used at the moment
}
// Now $dataSection_Content_Offset contains the size of the content
// section header
// offset: $secOffset; size: 4; section length
// + x Size of the content (summary + content)
$data .= pack('V', $dataSection_Content_Offset);
// offset: $secOffset+4; size: 4; property count
$data .= pack('V', $dataSection_NumProps);
// Section Summary
$data .= $dataSection_Summary;
// Section Content
$data .= $dataSection_Content;
return $data;
}
}

View File

@@ -0,0 +1,224 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
// Original file header of PEAR::Spreadsheet_Excel_Writer_BIFFwriter (used as the base for this class):
// -----------------------------------------------------------------------------------------
// * Module written/ported by Xavier Noguer <xnoguer@rezebra.com>
// *
// * The majority of this is _NOT_ my code. I simply ported it from the
// * PERL Spreadsheet::WriteExcel module.
// *
// * The author of the Spreadsheet::WriteExcel module is John McNamara
// * <jmcnamara@cpan.org>
// *
// * I _DO_ maintain this code, and John McNamara has nothing to do with the
// * porting of this code to PHP. Any questions directly related to this
// * class library should be directed to me.
// *
// * License Information:
// *
// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets
// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com
// *
// * This library is free software; you can redistribute it and/or
// * modify it under the terms of the GNU Lesser General Public
// * License as published by the Free Software Foundation; either
// * version 2.1 of the License, or (at your option) any later version.
// *
// * This library is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// * Lesser General Public License for more details.
// *
// * You should have received a copy of the GNU Lesser General Public
// * License along with this library; if not, write to the Free Software
// * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// */
class BIFFwriter
{
/**
* The byte order of this architecture. 0 => little endian, 1 => big endian.
*
* @var int
*/
private static $byteOrder;
/**
* The string containing the data of the BIFF stream.
*
* @var string
*/
public $_data;
/**
* The size of the data in bytes. Should be the same as strlen($this->_data).
*
* @var int
*/
public $_datasize;
/**
* The maximum length for a BIFF record (excluding record header and length field). See addContinue().
*
* @var int
*
* @see addContinue()
*/
private $limit = 8224;
/**
* Constructor.
*/
public function __construct()
{
$this->_data = '';
$this->_datasize = 0;
}
/**
* Determine the byte order and store it as class data to avoid
* recalculating it for each call to new().
*
* @return int
*/
public static function getByteOrder()
{
if (!isset(self::$byteOrder)) {
// Check if "pack" gives the required IEEE 64bit float
$teststr = pack('d', 1.2345);
$number = pack('C8', 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F);
if ($number == $teststr) {
$byte_order = 0; // Little Endian
} elseif ($number == strrev($teststr)) {
$byte_order = 1; // Big Endian
} else {
// Give up. I'll fix this in a later version.
throw new WriterException('Required floating point format not supported on this platform.');
}
self::$byteOrder = $byte_order;
}
return self::$byteOrder;
}
/**
* General storage function.
*
* @param string $data binary data to append
*/
protected function append($data): void
{
if (strlen($data) - 4 > $this->limit) {
$data = $this->addContinue($data);
}
$this->_data .= $data;
$this->_datasize += strlen($data);
}
/**
* General storage function like append, but returns string instead of modifying $this->_data.
*
* @param string $data binary data to write
*
* @return string
*/
public function writeData($data)
{
if (strlen($data) - 4 > $this->limit) {
$data = $this->addContinue($data);
}
$this->_datasize += strlen($data);
return $data;
}
/**
* Writes Excel BOF record to indicate the beginning of a stream or
* sub-stream in the BIFF file.
*
* @param int $type type of BIFF file to write: 0x0005 Workbook,
* 0x0010 Worksheet
*/
protected function storeBof($type): void
{
$record = 0x0809; // Record identifier (BIFF5-BIFF8)
$length = 0x0010;
// by inspection of real files, MS Office Excel 2007 writes the following
$unknown = pack('VV', 0x000100D1, 0x00000406);
$build = 0x0DBB; // Excel 97
$year = 0x07CC; // Excel 97
$version = 0x0600; // BIFF8
$header = pack('vv', $record, $length);
$data = pack('vvvv', $version, $type, $build, $year);
$this->append($header . $data . $unknown);
}
/**
* Writes Excel EOF record to indicate the end of a BIFF stream.
*/
protected function storeEof(): void
{
$record = 0x000A; // Record identifier
$length = 0x0000; // Number of bytes to follow
$header = pack('vv', $record, $length);
$this->append($header);
}
/**
* Writes Excel EOF record to indicate the end of a BIFF stream.
*/
public function writeEof()
{
$record = 0x000A; // Record identifier
$length = 0x0000; // Number of bytes to follow
$header = pack('vv', $record, $length);
return $this->writeData($header);
}
/**
* Excel limits the size of BIFF records. In Excel 5 the limit is 2084 bytes. In
* Excel 97 the limit is 8228 bytes. Records that are longer than these limits
* must be split up into CONTINUE blocks.
*
* This function takes a long BIFF record and inserts CONTINUE records as
* necessary.
*
* @param string $data The original binary data to be written
*
* @return string A very convenient string of continue blocks
*/
private function addContinue($data)
{
$limit = $this->limit;
$record = 0x003C; // Record identifier
// The first 2080/8224 bytes remain intact. However, we have to change
// the length field of the record.
$tmp = substr($data, 0, 2) . pack('v', $limit) . substr($data, 4, $limit);
$header = pack('vv', $record, $limit); // Headers for continue records
// Retrieve chunks of 2080/8224 bytes +4 for the header.
$data_length = strlen($data);
for ($i = $limit + 4; $i < ($data_length - $limit); $i += $limit) {
$tmp .= $header;
$tmp .= substr($data, $i, $limit);
}
// Retrieve the last chunk of data
$header = pack('vv', $record, strlen($data) - $i);
$tmp .= $header;
$tmp .= substr($data, $i);
return $tmp;
}
}

View File

@@ -0,0 +1,510 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE\Blip;
class Escher
{
/**
* The object we are writing.
*/
private $object;
/**
* The written binary data.
*/
private $data;
/**
* Shape offsets. Positions in binary stream where a new shape record begins.
*
* @var array
*/
private $spOffsets;
/**
* Shape types.
*
* @var array
*/
private $spTypes;
/**
* Constructor.
*
* @param mixed $object
*/
public function __construct($object)
{
$this->object = $object;
}
/**
* Process the object to be written.
*
* @return string
*/
public function close()
{
// initialize
$this->data = '';
switch (get_class($this->object)) {
case \PhpOffice\PhpSpreadsheet\Shared\Escher::class:
if ($dggContainer = $this->object->getDggContainer()) {
$writer = new self($dggContainer);
$this->data = $writer->close();
} elseif ($dgContainer = $this->object->getDgContainer()) {
$writer = new self($dgContainer);
$this->data = $writer->close();
$this->spOffsets = $writer->getSpOffsets();
$this->spTypes = $writer->getSpTypes();
}
break;
case DggContainer::class:
// this is a container record
// initialize
$innerData = '';
// write the dgg
$recVer = 0x0;
$recInstance = 0x0000;
$recType = 0xF006;
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
// dgg data
$dggData =
pack(
'VVVV',
$this->object->getSpIdMax(), // maximum shape identifier increased by one
$this->object->getCDgSaved() + 1, // number of file identifier clusters increased by one
$this->object->getCSpSaved(),
$this->object->getCDgSaved() // count total number of drawings saved
);
// add file identifier clusters (one per drawing)
$IDCLs = $this->object->getIDCLs();
foreach ($IDCLs as $dgId => $maxReducedSpId) {
$dggData .= pack('VV', $dgId, $maxReducedSpId + 1);
}
$header = pack('vvV', $recVerInstance, $recType, strlen($dggData));
$innerData .= $header . $dggData;
// write the bstoreContainer
if ($bstoreContainer = $this->object->getBstoreContainer()) {
$writer = new self($bstoreContainer);
$innerData .= $writer->close();
}
// write the record
$recVer = 0xF;
$recInstance = 0x0000;
$recType = 0xF000;
$length = strlen($innerData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header . $innerData;
break;
case BstoreContainer::class:
// this is a container record
// initialize
$innerData = '';
// treat the inner data
if ($BSECollection = $this->object->getBSECollection()) {
foreach ($BSECollection as $BSE) {
$writer = new self($BSE);
$innerData .= $writer->close();
}
}
// write the record
$recVer = 0xF;
$recInstance = count($this->object->getBSECollection());
$recType = 0xF001;
$length = strlen($innerData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header . $innerData;
break;
case BSE::class:
// this is a semi-container record
// initialize
$innerData = '';
// here we treat the inner data
if ($blip = $this->object->getBlip()) {
$writer = new self($blip);
$innerData .= $writer->close();
}
// initialize
$data = '';
$btWin32 = $this->object->getBlipType();
$btMacOS = $this->object->getBlipType();
$data .= pack('CC', $btWin32, $btMacOS);
$rgbUid = pack('VVVV', 0, 0, 0, 0); // todo
$data .= $rgbUid;
$tag = 0;
$size = strlen($innerData);
$cRef = 1;
$foDelay = 0; //todo
$unused1 = 0x0;
$cbName = 0x0;
$unused2 = 0x0;
$unused3 = 0x0;
$data .= pack('vVVVCCCC', $tag, $size, $cRef, $foDelay, $unused1, $cbName, $unused2, $unused3);
$data .= $innerData;
// write the record
$recVer = 0x2;
$recInstance = $this->object->getBlipType();
$recType = 0xF007;
$length = strlen($data);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header;
$this->data .= $data;
break;
case Blip::class:
// this is an atom record
// write the record
switch ($this->object->getParent()->getBlipType()) {
case BSE::BLIPTYPE_JPEG:
// initialize
$innerData = '';
$rgbUid1 = pack('VVVV', 0, 0, 0, 0); // todo
$innerData .= $rgbUid1;
$tag = 0xFF; // todo
$innerData .= pack('C', $tag);
$innerData .= $this->object->getData();
$recVer = 0x0;
$recInstance = 0x46A;
$recType = 0xF01D;
$length = strlen($innerData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header;
$this->data .= $innerData;
break;
case BSE::BLIPTYPE_PNG:
// initialize
$innerData = '';
$rgbUid1 = pack('VVVV', 0, 0, 0, 0); // todo
$innerData .= $rgbUid1;
$tag = 0xFF; // todo
$innerData .= pack('C', $tag);
$innerData .= $this->object->getData();
$recVer = 0x0;
$recInstance = 0x6E0;
$recType = 0xF01E;
$length = strlen($innerData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header;
$this->data .= $innerData;
break;
}
break;
case DgContainer::class:
// this is a container record
// initialize
$innerData = '';
// write the dg
$recVer = 0x0;
$recInstance = $this->object->getDgId();
$recType = 0xF008;
$length = 8;
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
// number of shapes in this drawing (including group shape)
$countShapes = count($this->object->getSpgrContainer()->getChildren());
$innerData .= $header . pack('VV', $countShapes, $this->object->getLastSpId());
// write the spgrContainer
if ($spgrContainer = $this->object->getSpgrContainer()) {
$writer = new self($spgrContainer);
$innerData .= $writer->close();
// get the shape offsets relative to the spgrContainer record
$spOffsets = $writer->getSpOffsets();
$spTypes = $writer->getSpTypes();
// save the shape offsets relative to dgContainer
foreach ($spOffsets as &$spOffset) {
$spOffset += 24; // add length of dgContainer header data (8 bytes) plus dg data (16 bytes)
}
$this->spOffsets = $spOffsets;
$this->spTypes = $spTypes;
}
// write the record
$recVer = 0xF;
$recInstance = 0x0000;
$recType = 0xF002;
$length = strlen($innerData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header . $innerData;
break;
case SpgrContainer::class:
// this is a container record
// initialize
$innerData = '';
// initialize spape offsets
$totalSize = 8;
$spOffsets = [];
$spTypes = [];
// treat the inner data
foreach ($this->object->getChildren() as $spContainer) {
$writer = new self($spContainer);
$spData = $writer->close();
$innerData .= $spData;
// save the shape offsets (where new shape records begin)
$totalSize += strlen($spData);
$spOffsets[] = $totalSize;
$spTypes = array_merge($spTypes, $writer->getSpTypes());
}
// write the record
$recVer = 0xF;
$recInstance = 0x0000;
$recType = 0xF003;
$length = strlen($innerData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header . $innerData;
$this->spOffsets = $spOffsets;
$this->spTypes = $spTypes;
break;
case SpContainer::class:
// initialize
$data = '';
// build the data
// write group shape record, if necessary?
if ($this->object->getSpgr()) {
$recVer = 0x1;
$recInstance = 0x0000;
$recType = 0xF009;
$length = 0x00000010;
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$data .= $header . pack('VVVV', 0, 0, 0, 0);
}
$this->spTypes[] = ($this->object->getSpType());
// write the shape record
$recVer = 0x2;
$recInstance = $this->object->getSpType(); // shape type
$recType = 0xF00A;
$length = 0x00000008;
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$data .= $header . pack('VV', $this->object->getSpId(), $this->object->getSpgr() ? 0x0005 : 0x0A00);
// the options
if ($this->object->getOPTCollection()) {
$optData = '';
$recVer = 0x3;
$recInstance = count($this->object->getOPTCollection());
$recType = 0xF00B;
foreach ($this->object->getOPTCollection() as $property => $value) {
$optData .= pack('vV', $property, $value);
}
$length = strlen($optData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$data .= $header . $optData;
}
// the client anchor
if ($this->object->getStartCoordinates()) {
$clientAnchorData = '';
$recVer = 0x0;
$recInstance = 0x0;
$recType = 0xF010;
// start coordinates
[$column, $row] = Coordinate::coordinateFromString($this->object->getStartCoordinates());
$c1 = Coordinate::columnIndexFromString($column) - 1;
$r1 = $row - 1;
// start offsetX
$startOffsetX = $this->object->getStartOffsetX();
// start offsetY
$startOffsetY = $this->object->getStartOffsetY();
// end coordinates
[$column, $row] = Coordinate::coordinateFromString($this->object->getEndCoordinates());
$c2 = Coordinate::columnIndexFromString($column) - 1;
$r2 = $row - 1;
// end offsetX
$endOffsetX = $this->object->getEndOffsetX();
// end offsetY
$endOffsetY = $this->object->getEndOffsetY();
$clientAnchorData = pack('vvvvvvvvv', $this->object->getSpFlag(), $c1, $startOffsetX, $r1, $startOffsetY, $c2, $endOffsetX, $r2, $endOffsetY);
$length = strlen($clientAnchorData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$data .= $header . $clientAnchorData;
}
// the client data, just empty for now
if (!$this->object->getSpgr()) {
$clientDataData = '';
$recVer = 0x0;
$recInstance = 0x0;
$recType = 0xF011;
$length = strlen($clientDataData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$data .= $header . $clientDataData;
}
// write the record
$recVer = 0xF;
$recInstance = 0x0000;
$recType = 0xF004;
$length = strlen($data);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header . $data;
break;
}
return $this->data;
}
/**
* Gets the shape offsets.
*
* @return array
*/
public function getSpOffsets()
{
return $this->spOffsets;
}
/**
* Gets the shape types.
*
* @return array
*/
public function getSpTypes()
{
return $this->spTypes;
}
}

View File

@@ -0,0 +1,147 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
class Font
{
/**
* Color index.
*
* @var int
*/
private $colorIndex;
/**
* Font.
*
* @var \PhpOffice\PhpSpreadsheet\Style\Font
*/
private $font;
/**
* Constructor.
*/
public function __construct(\PhpOffice\PhpSpreadsheet\Style\Font $font)
{
$this->colorIndex = 0x7FFF;
$this->font = $font;
}
/**
* Set the color index.
*
* @param int $colorIndex
*/
public function setColorIndex($colorIndex): void
{
$this->colorIndex = $colorIndex;
}
/**
* Get font record data.
*
* @return string
*/
public function writeFont()
{
$font_outline = 0;
$font_shadow = 0;
$icv = $this->colorIndex; // Index to color palette
if ($this->font->getSuperscript()) {
$sss = 1;
} elseif ($this->font->getSubscript()) {
$sss = 2;
} else {
$sss = 0;
}
$bFamily = 0; // Font family
$bCharSet = \PhpOffice\PhpSpreadsheet\Shared\Font::getCharsetFromFontName($this->font->getName()); // Character set
$record = 0x31; // Record identifier
$reserved = 0x00; // Reserved
$grbit = 0x00; // Font attributes
if ($this->font->getItalic()) {
$grbit |= 0x02;
}
if ($this->font->getStrikethrough()) {
$grbit |= 0x08;
}
if ($font_outline) {
$grbit |= 0x10;
}
if ($font_shadow) {
$grbit |= 0x20;
}
$data = pack(
'vvvvvCCCC',
// Fontsize (in twips)
$this->font->getSize() * 20,
$grbit,
// Colour
$icv,
// Font weight
self::mapBold($this->font->getBold()),
// Superscript/Subscript
$sss,
self::mapUnderline($this->font->getUnderline()),
$bFamily,
$bCharSet,
$reserved
);
$data .= StringHelper::UTF8toBIFF8UnicodeShort($this->font->getName());
$length = strlen($data);
$header = pack('vv', $record, $length);
return $header . $data;
}
/**
* Map to BIFF5-BIFF8 codes for bold.
*
* @param bool $bold
*
* @return int
*/
private static function mapBold($bold)
{
if ($bold) {
return 0x2BC; // 700 = Bold font weight
}
return 0x190; // 400 = Normal font weight
}
/**
* Map of BIFF2-BIFF8 codes for underline styles.
*
* @var array of int
*/
private static $mapUnderline = [
\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_NONE => 0x00,
\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE => 0x01,
\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE => 0x02,
\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING => 0x21,
\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLEACCOUNTING => 0x22,
];
/**
* Map underline.
*
* @param string $underline
*
* @return int
*/
private static function mapUnderline($underline)
{
if (isset(self::$mapUnderline[$underline])) {
return self::$mapUnderline[$underline];
}
return 0x00;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,548 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Borders;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Protection;
use PhpOffice\PhpSpreadsheet\Style\Style;
// Original file header of PEAR::Spreadsheet_Excel_Writer_Format (used as the base for this class):
// -----------------------------------------------------------------------------------------
// /*
// * Module written/ported by Xavier Noguer <xnoguer@rezebra.com>
// *
// * The majority of this is _NOT_ my code. I simply ported it from the
// * PERL Spreadsheet::WriteExcel module.
// *
// * The author of the Spreadsheet::WriteExcel module is John McNamara
// * <jmcnamara@cpan.org>
// *
// * I _DO_ maintain this code, and John McNamara has nothing to do with the
// * porting of this code to PHP. Any questions directly related to this
// * class library should be directed to me.
// *
// * License Information:
// *
// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets
// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com
// *
// * This library is free software; you can redistribute it and/or
// * modify it under the terms of the GNU Lesser General Public
// * License as published by the Free Software Foundation; either
// * version 2.1 of the License, or (at your option) any later version.
// *
// * This library is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// * Lesser General Public License for more details.
// *
// * You should have received a copy of the GNU Lesser General Public
// * License along with this library; if not, write to the Free Software
// * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// */
class Xf
{
/**
* Style XF or a cell XF ?
*
* @var bool
*/
private $isStyleXf;
/**
* Index to the FONT record. Index 4 does not exist.
*
* @var int
*/
private $fontIndex;
/**
* An index (2 bytes) to a FORMAT record (number format).
*
* @var int
*/
private $numberFormatIndex;
/**
* 1 bit, apparently not used.
*
* @var int
*/
private $textJustLast;
/**
* The cell's foreground color.
*
* @var int
*/
private $foregroundColor;
/**
* The cell's background color.
*
* @var int
*/
private $backgroundColor;
/**
* Color of the bottom border of the cell.
*
* @var int
*/
private $bottomBorderColor;
/**
* Color of the top border of the cell.
*
* @var int
*/
private $topBorderColor;
/**
* Color of the left border of the cell.
*
* @var int
*/
private $leftBorderColor;
/**
* Color of the right border of the cell.
*
* @var int
*/
private $rightBorderColor;
/**
* Constructor.
*
* @param Style $style The XF format
*/
public function __construct(Style $style)
{
$this->isStyleXf = false;
$this->fontIndex = 0;
$this->numberFormatIndex = 0;
$this->textJustLast = 0;
$this->foregroundColor = 0x40;
$this->backgroundColor = 0x41;
$this->_diag = 0;
$this->bottomBorderColor = 0x40;
$this->topBorderColor = 0x40;
$this->leftBorderColor = 0x40;
$this->rightBorderColor = 0x40;
$this->_diag_color = 0x40;
$this->_style = $style;
}
/**
* Generate an Excel BIFF XF record (style or cell).
*
* @return string The XF record
*/
public function writeXf()
{
// Set the type of the XF record and some of the attributes.
if ($this->isStyleXf) {
$style = 0xFFF5;
} else {
$style = self::mapLocked($this->_style->getProtection()->getLocked());
$style |= self::mapHidden($this->_style->getProtection()->getHidden()) << 1;
}
// Flags to indicate if attributes have been set.
$atr_num = ($this->numberFormatIndex != 0) ? 1 : 0;
$atr_fnt = ($this->fontIndex != 0) ? 1 : 0;
$atr_alc = ((int) $this->_style->getAlignment()->getWrapText()) ? 1 : 0;
$atr_bdr = (self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) ||
self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) ||
self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) ||
self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle())) ? 1 : 0;
$atr_pat = (($this->foregroundColor != 0x40) ||
($this->backgroundColor != 0x41) ||
self::mapFillType($this->_style->getFill()->getFillType())) ? 1 : 0;
$atr_prot = self::mapLocked($this->_style->getProtection()->getLocked())
| self::mapHidden($this->_style->getProtection()->getHidden());
// Zero the default border colour if the border has not been set.
if (self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) == 0) {
$this->bottomBorderColor = 0;
}
if (self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) == 0) {
$this->topBorderColor = 0;
}
if (self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) == 0) {
$this->rightBorderColor = 0;
}
if (self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) == 0) {
$this->leftBorderColor = 0;
}
if (self::mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) == 0) {
$this->_diag_color = 0;
}
$record = 0x00E0; // Record identifier
$length = 0x0014; // Number of bytes to follow
$ifnt = $this->fontIndex; // Index to FONT record
$ifmt = $this->numberFormatIndex; // Index to FORMAT record
$align = $this->mapHAlign($this->_style->getAlignment()->getHorizontal()); // Alignment
$align |= (int) $this->_style->getAlignment()->getWrapText() << 3;
$align |= self::mapVAlign($this->_style->getAlignment()->getVertical()) << 4;
$align |= $this->textJustLast << 7;
$used_attrib = $atr_num << 2;
$used_attrib |= $atr_fnt << 3;
$used_attrib |= $atr_alc << 4;
$used_attrib |= $atr_bdr << 5;
$used_attrib |= $atr_pat << 6;
$used_attrib |= $atr_prot << 7;
$icv = $this->foregroundColor; // fg and bg pattern colors
$icv |= $this->backgroundColor << 7;
$border1 = self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()); // Border line style and color
$border1 |= self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) << 4;
$border1 |= self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) << 8;
$border1 |= self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) << 12;
$border1 |= $this->leftBorderColor << 16;
$border1 |= $this->rightBorderColor << 23;
$diagonalDirection = $this->_style->getBorders()->getDiagonalDirection();
$diag_tl_to_rb = $diagonalDirection == Borders::DIAGONAL_BOTH
|| $diagonalDirection == Borders::DIAGONAL_DOWN;
$diag_tr_to_lb = $diagonalDirection == Borders::DIAGONAL_BOTH
|| $diagonalDirection == Borders::DIAGONAL_UP;
$border1 |= $diag_tl_to_rb << 30;
$border1 |= $diag_tr_to_lb << 31;
$border2 = $this->topBorderColor; // Border color
$border2 |= $this->bottomBorderColor << 7;
$border2 |= $this->_diag_color << 14;
$border2 |= self::mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) << 21;
$border2 |= self::mapFillType($this->_style->getFill()->getFillType()) << 26;
$header = pack('vv', $record, $length);
//BIFF8 options: identation, shrinkToFit and text direction
$biff8_options = $this->_style->getAlignment()->getIndent();
$biff8_options |= (int) $this->_style->getAlignment()->getShrinkToFit() << 4;
$data = pack('vvvC', $ifnt, $ifmt, $style, $align);
$data .= pack('CCC', self::mapTextRotation($this->_style->getAlignment()->getTextRotation()), $biff8_options, $used_attrib);
$data .= pack('VVv', $border1, $border2, $icv);
return $header . $data;
}
/**
* Is this a style XF ?
*
* @param bool $value
*/
public function setIsStyleXf($value): void
{
$this->isStyleXf = $value;
}
/**
* Sets the cell's bottom border color.
*
* @param int $colorIndex Color index
*/
public function setBottomColor($colorIndex): void
{
$this->bottomBorderColor = $colorIndex;
}
/**
* Sets the cell's top border color.
*
* @param int $colorIndex Color index
*/
public function setTopColor($colorIndex): void
{
$this->topBorderColor = $colorIndex;
}
/**
* Sets the cell's left border color.
*
* @param int $colorIndex Color index
*/
public function setLeftColor($colorIndex): void
{
$this->leftBorderColor = $colorIndex;
}
/**
* Sets the cell's right border color.
*
* @param int $colorIndex Color index
*/
public function setRightColor($colorIndex): void
{
$this->rightBorderColor = $colorIndex;
}
/**
* Sets the cell's diagonal border color.
*
* @param int $colorIndex Color index
*/
public function setDiagColor($colorIndex): void
{
$this->_diag_color = $colorIndex;
}
/**
* Sets the cell's foreground color.
*
* @param int $colorIndex Color index
*/
public function setFgColor($colorIndex): void
{
$this->foregroundColor = $colorIndex;
}
/**
* Sets the cell's background color.
*
* @param int $colorIndex Color index
*/
public function setBgColor($colorIndex): void
{
$this->backgroundColor = $colorIndex;
}
/**
* Sets the index to the number format record
* It can be date, time, currency, etc...
*
* @param int $numberFormatIndex Index to format record
*/
public function setNumberFormatIndex($numberFormatIndex): void
{
$this->numberFormatIndex = $numberFormatIndex;
}
/**
* Set the font index.
*
* @param int $value Font index, note that value 4 does not exist
*/
public function setFontIndex($value): void
{
$this->fontIndex = $value;
}
/**
* Map of BIFF2-BIFF8 codes for border styles.
*
* @var array of int
*/
private static $mapBorderStyles = [
Border::BORDER_NONE => 0x00,
Border::BORDER_THIN => 0x01,
Border::BORDER_MEDIUM => 0x02,
Border::BORDER_DASHED => 0x03,
Border::BORDER_DOTTED => 0x04,
Border::BORDER_THICK => 0x05,
Border::BORDER_DOUBLE => 0x06,
Border::BORDER_HAIR => 0x07,
Border::BORDER_MEDIUMDASHED => 0x08,
Border::BORDER_DASHDOT => 0x09,
Border::BORDER_MEDIUMDASHDOT => 0x0A,
Border::BORDER_DASHDOTDOT => 0x0B,
Border::BORDER_MEDIUMDASHDOTDOT => 0x0C,
Border::BORDER_SLANTDASHDOT => 0x0D,
];
/**
* Map border style.
*
* @param string $borderStyle
*
* @return int
*/
private static function mapBorderStyle($borderStyle)
{
if (isset(self::$mapBorderStyles[$borderStyle])) {
return self::$mapBorderStyles[$borderStyle];
}
return 0x00;
}
/**
* Map of BIFF2-BIFF8 codes for fill types.
*
* @var array of int
*/
private static $mapFillTypes = [
Fill::FILL_NONE => 0x00,
Fill::FILL_SOLID => 0x01,
Fill::FILL_PATTERN_MEDIUMGRAY => 0x02,
Fill::FILL_PATTERN_DARKGRAY => 0x03,
Fill::FILL_PATTERN_LIGHTGRAY => 0x04,
Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05,
Fill::FILL_PATTERN_DARKVERTICAL => 0x06,
Fill::FILL_PATTERN_DARKDOWN => 0x07,
Fill::FILL_PATTERN_DARKUP => 0x08,
Fill::FILL_PATTERN_DARKGRID => 0x09,
Fill::FILL_PATTERN_DARKTRELLIS => 0x0A,
Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B,
Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C,
Fill::FILL_PATTERN_LIGHTDOWN => 0x0D,
Fill::FILL_PATTERN_LIGHTUP => 0x0E,
Fill::FILL_PATTERN_LIGHTGRID => 0x0F,
Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10,
Fill::FILL_PATTERN_GRAY125 => 0x11,
Fill::FILL_PATTERN_GRAY0625 => 0x12,
Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8
Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8
];
/**
* Map fill type.
*
* @param string $fillType
*
* @return int
*/
private static function mapFillType($fillType)
{
if (isset(self::$mapFillTypes[$fillType])) {
return self::$mapFillTypes[$fillType];
}
return 0x00;
}
/**
* Map of BIFF2-BIFF8 codes for horizontal alignment.
*
* @var array of int
*/
private static $mapHAlignments = [
Alignment::HORIZONTAL_GENERAL => 0,
Alignment::HORIZONTAL_LEFT => 1,
Alignment::HORIZONTAL_CENTER => 2,
Alignment::HORIZONTAL_RIGHT => 3,
Alignment::HORIZONTAL_FILL => 4,
Alignment::HORIZONTAL_JUSTIFY => 5,
Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6,
];
/**
* Map to BIFF2-BIFF8 codes for horizontal alignment.
*
* @param string $hAlign
*
* @return int
*/
private function mapHAlign($hAlign)
{
if (isset(self::$mapHAlignments[$hAlign])) {
return self::$mapHAlignments[$hAlign];
}
return 0;
}
/**
* Map of BIFF2-BIFF8 codes for vertical alignment.
*
* @var array of int
*/
private static $mapVAlignments = [
Alignment::VERTICAL_TOP => 0,
Alignment::VERTICAL_CENTER => 1,
Alignment::VERTICAL_BOTTOM => 2,
Alignment::VERTICAL_JUSTIFY => 3,
];
/**
* Map to BIFF2-BIFF8 codes for vertical alignment.
*
* @param string $vAlign
*
* @return int
*/
private static function mapVAlign($vAlign)
{
if (isset(self::$mapVAlignments[$vAlign])) {
return self::$mapVAlignments[$vAlign];
}
return 2;
}
/**
* Map to BIFF8 codes for text rotation angle.
*
* @param int $textRotation
*
* @return int
*/
private static function mapTextRotation($textRotation)
{
if ($textRotation >= 0) {
return $textRotation;
} elseif ($textRotation == -165) {
return 255;
} elseif ($textRotation < 0) {
return 90 - $textRotation;
}
}
/**
* Map locked.
*
* @param string $locked
*
* @return int
*/
private static function mapLocked($locked)
{
switch ($locked) {
case Protection::PROTECTION_INHERIT:
return 1;
case Protection::PROTECTION_PROTECTED:
return 1;
case Protection::PROTECTION_UNPROTECTED:
return 0;
default:
return 1;
}
}
/**
* Map hidden.
*
* @param string $hidden
*
* @return int
*/
private static function mapHidden($hidden)
{
switch ($hidden) {
case Protection::PROTECTION_INHERIT:
return 0;
case Protection::PROTECTION_PROTECTED:
return 1;
case Protection::PROTECTION_UNPROTECTED:
return 0;
default:
return 0;
}
}
}

View File

@@ -0,0 +1,548 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\HashTable;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing as WorksheetDrawing;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Chart;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Comments;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\ContentTypes;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\DocProps;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Drawing;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsRibbon;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsVBA;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\StringTable;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Style;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Theme;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Workbook;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet;
use ZipArchive;
use ZipStream\Exception\OverflowException;
use ZipStream\Option\Archive;
use ZipStream\ZipStream;
class Xlsx extends BaseWriter
{
/**
* Office2003 compatibility.
*
* @var bool
*/
private $office2003compatibility = false;
/**
* Private writer parts.
*
* @var Xlsx\WriterPart[]
*/
private $writerParts = [];
/**
* Private Spreadsheet.
*
* @var Spreadsheet
*/
private $spreadSheet;
/**
* Private string table.
*
* @var string[]
*/
private $stringTable = [];
/**
* Private unique Conditional HashTable.
*
* @var HashTable
*/
private $stylesConditionalHashTable;
/**
* Private unique Style HashTable.
*
* @var HashTable
*/
private $styleHashTable;
/**
* Private unique Fill HashTable.
*
* @var HashTable
*/
private $fillHashTable;
/**
* Private unique \PhpOffice\PhpSpreadsheet\Style\Font HashTable.
*
* @var HashTable
*/
private $fontHashTable;
/**
* Private unique Borders HashTable.
*
* @var HashTable
*/
private $bordersHashTable;
/**
* Private unique NumberFormat HashTable.
*
* @var HashTable
*/
private $numFmtHashTable;
/**
* Private unique \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable.
*
* @var HashTable
*/
private $drawingHashTable;
/**
* Private handle for zip stream.
*
* @var ZipStream
*/
private $zip;
/**
* Create a new Xlsx Writer.
*/
public function __construct(Spreadsheet $spreadsheet)
{
// Assign PhpSpreadsheet
$this->setSpreadsheet($spreadsheet);
$writerPartsArray = [
'stringtable' => StringTable::class,
'contenttypes' => ContentTypes::class,
'docprops' => DocProps::class,
'rels' => Rels::class,
'theme' => Theme::class,
'style' => Style::class,
'workbook' => Workbook::class,
'worksheet' => Worksheet::class,
'drawing' => Drawing::class,
'comments' => Comments::class,
'chart' => Chart::class,
'relsvba' => RelsVBA::class,
'relsribbonobjects' => RelsRibbon::class,
];
// Initialise writer parts
// and Assign their parent IWriters
foreach ($writerPartsArray as $writer => $class) {
$this->writerParts[$writer] = new $class($this);
}
$hashTablesArray = ['stylesConditionalHashTable', 'fillHashTable', 'fontHashTable',
'bordersHashTable', 'numFmtHashTable', 'drawingHashTable',
'styleHashTable',
];
// Set HashTable variables
foreach ($hashTablesArray as $tableName) {
$this->$tableName = new HashTable();
}
}
/**
* Get writer part.
*
* @param string $pPartName Writer part name
*
* @return \PhpOffice\PhpSpreadsheet\Writer\Xlsx\WriterPart
*/
public function getWriterPart($pPartName)
{
if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) {
return $this->writerParts[strtolower($pPartName)];
}
return null;
}
/**
* Save PhpSpreadsheet to file.
*
* @param resource|string $pFilename
*/
public function save($pFilename): void
{
// garbage collect
$this->pathNames = [];
$this->spreadSheet->garbageCollect();
$this->openFileHandle($pFilename);
$saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog();
Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false);
$saveDateReturnType = Functions::getReturnDateType();
Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
// Create string lookup table
$this->stringTable = [];
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
$this->stringTable = $this->getWriterPart('StringTable')->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable);
}
// Create styles dictionaries
$this->styleHashTable->addFromSource($this->getWriterPart('Style')->allStyles($this->spreadSheet));
$this->stylesConditionalHashTable->addFromSource($this->getWriterPart('Style')->allConditionalStyles($this->spreadSheet));
$this->fillHashTable->addFromSource($this->getWriterPart('Style')->allFills($this->spreadSheet));
$this->fontHashTable->addFromSource($this->getWriterPart('Style')->allFonts($this->spreadSheet));
$this->bordersHashTable->addFromSource($this->getWriterPart('Style')->allBorders($this->spreadSheet));
$this->numFmtHashTable->addFromSource($this->getWriterPart('Style')->allNumberFormats($this->spreadSheet));
// Create drawing dictionary
$this->drawingHashTable->addFromSource($this->getWriterPart('Drawing')->allDrawings($this->spreadSheet));
$options = new Archive();
$options->setEnableZip64(false);
$options->setOutputStream($this->fileHandle);
$this->zip = new ZipStream(null, $options);
// Add [Content_Types].xml to ZIP file
$this->addZipFile('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->spreadSheet, $this->includeCharts));
//if hasMacros, add the vbaProject.bin file, Certificate file(if exists)
if ($this->spreadSheet->hasMacros()) {
$macrosCode = $this->spreadSheet->getMacrosCode();
if ($macrosCode !== null) {
// we have the code ?
$this->addZipFile('xl/vbaProject.bin', $macrosCode); //allways in 'xl', allways named vbaProject.bin
if ($this->spreadSheet->hasMacrosCertificate()) {
//signed macros ?
// Yes : add the certificate file and the related rels file
$this->addZipFile('xl/vbaProjectSignature.bin', $this->spreadSheet->getMacrosCertificate());
$this->addZipFile('xl/_rels/vbaProject.bin.rels', $this->getWriterPart('RelsVBA')->writeVBARelationships($this->spreadSheet));
}
}
}
//a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels)
if ($this->spreadSheet->hasRibbon()) {
$tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target');
$this->addZipFile($tmpRibbonTarget, $this->spreadSheet->getRibbonXMLData('data'));
if ($this->spreadSheet->hasRibbonBinObjects()) {
$tmpRootPath = dirname($tmpRibbonTarget) . '/';
$ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write
foreach ($ribbonBinObjects as $aPath => $aContent) {
$this->addZipFile($tmpRootPath . $aPath, $aContent);
}
//the rels for files
$this->addZipFile($tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->spreadSheet));
}
}
// Add relationships to ZIP file
$this->addZipFile('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->spreadSheet));
$this->addZipFile('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->spreadSheet));
// Add document properties to ZIP file
$this->addZipFile('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->spreadSheet));
$this->addZipFile('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->spreadSheet));
$customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->spreadSheet);
if ($customPropertiesPart !== null) {
$this->addZipFile('docProps/custom.xml', $customPropertiesPart);
}
// Add theme to ZIP file
$this->addZipFile('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->spreadSheet));
// Add string table to ZIP file
$this->addZipFile('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->stringTable));
// Add styles to ZIP file
$this->addZipFile('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->spreadSheet));
// Add workbook to ZIP file
$this->addZipFile('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas));
$chartCount = 0;
// Add worksheets
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
$this->addZipFile('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts));
if ($this->includeCharts) {
$charts = $this->spreadSheet->getSheet($i)->getChartCollection();
if (count($charts) > 0) {
foreach ($charts as $chart) {
$this->addZipFile('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart, $this->preCalculateFormulas));
++$chartCount;
}
}
}
}
$chartRef1 = 0;
// Add worksheet relationships (drawings, ...)
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
// Add relationships
$this->addZipFile('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts));
// Add unparsedLoadedData
$sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName();
$unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData();
if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'])) {
foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'] as $ctrlProp) {
$this->addZipFile($ctrlProp['filePath'], $ctrlProp['content']);
}
}
if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'])) {
foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'] as $ctrlProp) {
$this->addZipFile($ctrlProp['filePath'], $ctrlProp['content']);
}
}
$drawings = $this->spreadSheet->getSheet($i)->getDrawingCollection();
$drawingCount = count($drawings);
if ($this->includeCharts) {
$chartCount = $this->spreadSheet->getSheet($i)->getChartCount();
}
// Add drawing and image relationship parts
if (($drawingCount > 0) || ($chartCount > 0)) {
// Drawing relationships
$this->addZipFile('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts));
// Drawings
$this->addZipFile('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts));
} elseif (isset($unparsedLoadedData['sheets'][$sheetCodeName]['drawingAlternateContents'])) {
// Drawings
$this->addZipFile('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts));
}
// Add unparsed drawings
if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['Drawings'])) {
foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['Drawings'] as $relId => $drawingXml) {
$drawingFile = array_search($relId, $unparsedLoadedData['sheets'][$sheetCodeName]['drawingOriginalIds']);
if ($drawingFile !== false) {
$drawingFile = ltrim($drawingFile, '.');
$this->addZipFile('xl' . $drawingFile, $drawingXml);
}
}
}
// Add comment relationship parts
if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) {
// VML Comments
$this->addZipFile('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->spreadSheet->getSheet($i)));
// Comments
$this->addZipFile('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->spreadSheet->getSheet($i)));
}
// Add unparsed relationship parts
if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'])) {
foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'] as $vmlDrawing) {
$this->addZipFile($vmlDrawing['filePath'], $vmlDrawing['content']);
}
}
// Add header/footer relationship parts
if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
// VML Drawings
$this->addZipFile('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i)));
// VML Drawing relationships
$this->addZipFile('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i)));
// Media
foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
$this->addZipFile('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath()));
}
}
}
// Add media
for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) {
if ($this->getDrawingHashTable()->getByIndex($i) instanceof WorksheetDrawing) {
$imageContents = null;
$imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
if (strpos($imagePath, 'zip://') !== false) {
$imagePath = substr($imagePath, 6);
$imagePathSplitted = explode('#', $imagePath);
$imageZip = new ZipArchive();
$imageZip->open($imagePathSplitted[0]);
$imageContents = $imageZip->getFromName($imagePathSplitted[1]);
$imageZip->close();
unset($imageZip);
} else {
$imageContents = file_get_contents($imagePath);
}
$this->addZipFile('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
} elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) {
ob_start();
call_user_func(
$this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(),
$this->getDrawingHashTable()->getByIndex($i)->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
$this->addZipFile('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
}
}
Functions::setReturnDateType($saveDateReturnType);
Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
// Close file
try {
$this->zip->finish();
} catch (OverflowException $e) {
throw new WriterException('Could not close resource.');
}
$this->maybeCloseFileHandle();
}
/**
* Get Spreadsheet object.
*
* @return Spreadsheet
*/
public function getSpreadsheet()
{
return $this->spreadSheet;
}
/**
* Set Spreadsheet object.
*
* @param Spreadsheet $spreadsheet PhpSpreadsheet object
*
* @return $this
*/
public function setSpreadsheet(Spreadsheet $spreadsheet)
{
$this->spreadSheet = $spreadsheet;
return $this;
}
/**
* Get string table.
*
* @return string[]
*/
public function getStringTable()
{
return $this->stringTable;
}
/**
* Get Style HashTable.
*
* @return HashTable
*/
public function getStyleHashTable()
{
return $this->styleHashTable;
}
/**
* Get Conditional HashTable.
*
* @return HashTable
*/
public function getStylesConditionalHashTable()
{
return $this->stylesConditionalHashTable;
}
/**
* Get Fill HashTable.
*
* @return HashTable
*/
public function getFillHashTable()
{
return $this->fillHashTable;
}
/**
* Get \PhpOffice\PhpSpreadsheet\Style\Font HashTable.
*
* @return HashTable
*/
public function getFontHashTable()
{
return $this->fontHashTable;
}
/**
* Get Borders HashTable.
*
* @return HashTable
*/
public function getBordersHashTable()
{
return $this->bordersHashTable;
}
/**
* Get NumberFormat HashTable.
*
* @return HashTable
*/
public function getNumFmtHashTable()
{
return $this->numFmtHashTable;
}
/**
* Get \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable.
*
* @return HashTable
*/
public function getDrawingHashTable()
{
return $this->drawingHashTable;
}
/**
* Get Office2003 compatibility.
*
* @return bool
*/
public function getOffice2003Compatibility()
{
return $this->office2003compatibility;
}
/**
* Set Office2003 compatibility.
*
* @param bool $pValue Office2003 compatibility?
*
* @return $this
*/
public function setOffice2003Compatibility($pValue)
{
$this->office2003compatibility = $pValue;
return $this;
}
private $pathNames = [];
private function addZipFile(string $path, string $content): void
{
if (!in_array($path, $this->pathNames)) {
$this->pathNames[] = $path;
$this->zip->addFile($path, $content);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,232 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Comment;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
class Comments extends WriterPart
{
/**
* Write comments to XML format.
*
* @return string XML Output
*/
public function writeComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Comments cache
$comments = $pWorksheet->getComments();
// Authors cache
$authors = [];
$authorId = 0;
foreach ($comments as $comment) {
if (!isset($authors[$comment->getAuthor()])) {
$authors[$comment->getAuthor()] = $authorId++;
}
}
// comments
$objWriter->startElement('comments');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
// Loop through authors
$objWriter->startElement('authors');
foreach ($authors as $author => $index) {
$objWriter->writeElement('author', $author);
}
$objWriter->endElement();
// Loop through comments
$objWriter->startElement('commentList');
foreach ($comments as $key => $value) {
$this->writeComment($objWriter, $key, $value, $authors);
}
$objWriter->endElement();
$objWriter->endElement();
// Return
return $objWriter->getData();
}
/**
* Write comment to XML format.
*
* @param XMLWriter $objWriter XML Writer
* @param string $pCellReference Cell reference
* @param Comment $pComment Comment
* @param array $pAuthors Array of authors
*/
private function writeComment(XMLWriter $objWriter, $pCellReference, Comment $pComment, array $pAuthors): void
{
// comment
$objWriter->startElement('comment');
$objWriter->writeAttribute('ref', $pCellReference);
$objWriter->writeAttribute('authorId', $pAuthors[$pComment->getAuthor()]);
// text
$objWriter->startElement('text');
$this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $pComment->getText());
$objWriter->endElement();
$objWriter->endElement();
}
/**
* Write VML comments to XML format.
*
* @return string XML Output
*/
public function writeVMLComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Comments cache
$comments = $pWorksheet->getComments();
// xml
$objWriter->startElement('xml');
$objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml');
$objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office');
$objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel');
// o:shapelayout
$objWriter->startElement('o:shapelayout');
$objWriter->writeAttribute('v:ext', 'edit');
// o:idmap
$objWriter->startElement('o:idmap');
$objWriter->writeAttribute('v:ext', 'edit');
$objWriter->writeAttribute('data', '1');
$objWriter->endElement();
$objWriter->endElement();
// v:shapetype
$objWriter->startElement('v:shapetype');
$objWriter->writeAttribute('id', '_x0000_t202');
$objWriter->writeAttribute('coordsize', '21600,21600');
$objWriter->writeAttribute('o:spt', '202');
$objWriter->writeAttribute('path', 'm,l,21600r21600,l21600,xe');
// v:stroke
$objWriter->startElement('v:stroke');
$objWriter->writeAttribute('joinstyle', 'miter');
$objWriter->endElement();
// v:path
$objWriter->startElement('v:path');
$objWriter->writeAttribute('gradientshapeok', 't');
$objWriter->writeAttribute('o:connecttype', 'rect');
$objWriter->endElement();
$objWriter->endElement();
// Loop through comments
foreach ($comments as $key => $value) {
$this->writeVMLComment($objWriter, $key, $value);
}
$objWriter->endElement();
// Return
return $objWriter->getData();
}
/**
* Write VML comment to XML format.
*
* @param XMLWriter $objWriter XML Writer
* @param string $pCellReference Cell reference, eg: 'A1'
* @param Comment $pComment Comment
*/
private function writeVMLComment(XMLWriter $objWriter, $pCellReference, Comment $pComment): void
{
// Metadata
[$column, $row] = Coordinate::coordinateFromString($pCellReference);
$column = Coordinate::columnIndexFromString($column);
$id = 1024 + $column + $row;
$id = substr($id, 0, 4);
// v:shape
$objWriter->startElement('v:shape');
$objWriter->writeAttribute('id', '_x0000_s' . $id);
$objWriter->writeAttribute('type', '#_x0000_t202');
$objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $pComment->getMarginLeft() . ';margin-top:' . $pComment->getMarginTop() . ';width:' . $pComment->getWidth() . ';height:' . $pComment->getHeight() . ';z-index:1;visibility:' . ($pComment->getVisible() ? 'visible' : 'hidden'));
$objWriter->writeAttribute('fillcolor', '#' . $pComment->getFillColor()->getRGB());
$objWriter->writeAttribute('o:insetmode', 'auto');
// v:fill
$objWriter->startElement('v:fill');
$objWriter->writeAttribute('color2', '#' . $pComment->getFillColor()->getRGB());
$objWriter->endElement();
// v:shadow
$objWriter->startElement('v:shadow');
$objWriter->writeAttribute('on', 't');
$objWriter->writeAttribute('color', 'black');
$objWriter->writeAttribute('obscured', 't');
$objWriter->endElement();
// v:path
$objWriter->startElement('v:path');
$objWriter->writeAttribute('o:connecttype', 'none');
$objWriter->endElement();
// v:textbox
$objWriter->startElement('v:textbox');
$objWriter->writeAttribute('style', 'mso-direction-alt:auto');
// div
$objWriter->startElement('div');
$objWriter->writeAttribute('style', 'text-align:left');
$objWriter->endElement();
$objWriter->endElement();
// x:ClientData
$objWriter->startElement('x:ClientData');
$objWriter->writeAttribute('ObjectType', 'Note');
// x:MoveWithCells
$objWriter->writeElement('x:MoveWithCells', '');
// x:SizeWithCells
$objWriter->writeElement('x:SizeWithCells', '');
// x:AutoFill
$objWriter->writeElement('x:AutoFill', 'False');
// x:Row
$objWriter->writeElement('x:Row', ($row - 1));
// x:Column
$objWriter->writeElement('x:Column', ($column - 1));
$objWriter->endElement();
$objWriter->endElement();
}
}

View File

@@ -0,0 +1,240 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
class ContentTypes extends WriterPart
{
/**
* Write content types to XML format.
*
* @param bool $includeCharts Flag indicating if we should include drawing details for charts
*
* @return string XML Output
*/
public function writeContentTypes(Spreadsheet $spreadsheet, $includeCharts = false)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Types
$objWriter->startElement('Types');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/content-types');
// Theme
$this->writeOverrideContentType($objWriter, '/xl/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml');
// Styles
$this->writeOverrideContentType($objWriter, '/xl/styles.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml');
// Rels
$this->writeDefaultContentType($objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml');
// XML
$this->writeDefaultContentType($objWriter, 'xml', 'application/xml');
// VML
$this->writeDefaultContentType($objWriter, 'vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing');
// Workbook
if ($spreadsheet->hasMacros()) { //Macros in workbook ?
// Yes : not standard content but "macroEnabled"
$this->writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.ms-excel.sheet.macroEnabled.main+xml');
//... and define a new type for the VBA project
// Better use Override, because we can use 'bin' also for xl\printerSettings\printerSettings1.bin
$this->writeOverrideContentType($objWriter, '/xl/vbaProject.bin', 'application/vnd.ms-office.vbaProject');
if ($spreadsheet->hasMacrosCertificate()) {
// signed macros ?
// Yes : add needed information
$this->writeOverrideContentType($objWriter, '/xl/vbaProjectSignature.bin', 'application/vnd.ms-office.vbaProjectSignature');
}
} else {
// no macros in workbook, so standard type
$this->writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml');
}
// DocProps
$this->writeOverrideContentType($objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml');
$this->writeOverrideContentType($objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml');
$customPropertyList = $spreadsheet->getProperties()->getCustomProperties();
if (!empty($customPropertyList)) {
$this->writeOverrideContentType($objWriter, '/docProps/custom.xml', 'application/vnd.openxmlformats-officedocument.custom-properties+xml');
}
// Worksheets
$sheetCount = $spreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
$this->writeOverrideContentType($objWriter, '/xl/worksheets/sheet' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml');
}
// Shared strings
$this->writeOverrideContentType($objWriter, '/xl/sharedStrings.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml');
// Add worksheet relationship content types
$unparsedLoadedData = $spreadsheet->getUnparsedLoadedData();
$chart = 1;
for ($i = 0; $i < $sheetCount; ++$i) {
$drawings = $spreadsheet->getSheet($i)->getDrawingCollection();
$drawingCount = count($drawings);
$chartCount = ($includeCharts) ? $spreadsheet->getSheet($i)->getChartCount() : 0;
$hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$spreadsheet->getSheet($i)->getCodeName()]['drawingOriginalIds']);
// We need a drawing relationship for the worksheet if we have either drawings or charts
if (($drawingCount > 0) || ($chartCount > 0) || $hasUnparsedDrawing) {
$this->writeOverrideContentType($objWriter, '/xl/drawings/drawing' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.drawing+xml');
}
// If we have charts, then we need a chart relationship for every individual chart
if ($chartCount > 0) {
for ($c = 0; $c < $chartCount; ++$c) {
$this->writeOverrideContentType($objWriter, '/xl/charts/chart' . $chart++ . '.xml', 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml');
}
}
}
// Comments
for ($i = 0; $i < $sheetCount; ++$i) {
if (count($spreadsheet->getSheet($i)->getComments()) > 0) {
$this->writeOverrideContentType($objWriter, '/xl/comments' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml');
}
}
// Add media content-types
$aMediaContentTypes = [];
$mediaCount = $this->getParentWriter()->getDrawingHashTable()->count();
for ($i = 0; $i < $mediaCount; ++$i) {
$extension = '';
$mimeType = '';
if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof \PhpOffice\PhpSpreadsheet\Worksheet\Drawing) {
$extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension());
$mimeType = $this->getImageMimeType($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath());
} elseif ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) {
$extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType());
$extension = explode('/', $extension);
$extension = $extension[1];
$mimeType = $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType();
}
if (!isset($aMediaContentTypes[$extension])) {
$aMediaContentTypes[$extension] = $mimeType;
$this->writeDefaultContentType($objWriter, $extension, $mimeType);
}
}
if ($spreadsheet->hasRibbonBinObjects()) {
// Some additional objects in the ribbon ?
// we need to write "Extension" but not already write for media content
$tabRibbonTypes = array_diff($spreadsheet->getRibbonBinObjects('types'), array_keys($aMediaContentTypes));
foreach ($tabRibbonTypes as $aRibbonType) {
$mimeType = 'image/.' . $aRibbonType; //we wrote $mimeType like customUI Editor
$this->writeDefaultContentType($objWriter, $aRibbonType, $mimeType);
}
}
$sheetCount = $spreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
if (count($spreadsheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
foreach ($spreadsheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
if (!isset($aMediaContentTypes[strtolower($image->getExtension())])) {
$aMediaContentTypes[strtolower($image->getExtension())] = $this->getImageMimeType($image->getPath());
$this->writeDefaultContentType($objWriter, strtolower($image->getExtension()), $aMediaContentTypes[strtolower($image->getExtension())]);
}
}
}
}
// unparsed defaults
if (isset($unparsedLoadedData['default_content_types'])) {
foreach ($unparsedLoadedData['default_content_types'] as $extName => $contentType) {
$this->writeDefaultContentType($objWriter, $extName, $contentType);
}
}
// unparsed overrides
if (isset($unparsedLoadedData['override_content_types'])) {
foreach ($unparsedLoadedData['override_content_types'] as $partName => $overrideType) {
$this->writeOverrideContentType($objWriter, $partName, $overrideType);
}
}
$objWriter->endElement();
// Return
return $objWriter->getData();
}
/**
* Get image mime type.
*
* @param string $pFile Filename
*
* @return string Mime Type
*/
private function getImageMimeType($pFile)
{
if (File::fileExists($pFile)) {
$image = getimagesize($pFile);
return image_type_to_mime_type($image[2]);
}
throw new WriterException("File $pFile does not exist");
}
/**
* Write Default content type.
*
* @param XMLWriter $objWriter XML Writer
* @param string $pPartname Part name
* @param string $pContentType Content type
*/
private function writeDefaultContentType(XMLWriter $objWriter, $pPartname, $pContentType): void
{
if ($pPartname != '' && $pContentType != '') {
// Write content type
$objWriter->startElement('Default');
$objWriter->writeAttribute('Extension', $pPartname);
$objWriter->writeAttribute('ContentType', $pContentType);
$objWriter->endElement();
} else {
throw new WriterException('Invalid parameters passed.');
}
}
/**
* Write Override content type.
*
* @param XMLWriter $objWriter XML Writer
* @param string $pPartname Part name
* @param string $pContentType Content type
*/
private function writeOverrideContentType(XMLWriter $objWriter, $pPartname, $pContentType): void
{
if ($pPartname != '' && $pContentType != '') {
// Write content type
$objWriter->startElement('Override');
$objWriter->writeAttribute('PartName', $pPartname);
$objWriter->writeAttribute('ContentType', $pContentType);
$objWriter->endElement();
} else {
throw new WriterException('Invalid parameters passed.');
}
}
}

View File

@@ -0,0 +1,223 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class DefinedNames
{
private $objWriter;
private $spreadsheet;
public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet)
{
$this->objWriter = $objWriter;
$this->spreadsheet = $spreadsheet;
}
public function write(): void
{
// Write defined names
$this->objWriter->startElement('definedNames');
// Named ranges
if (count($this->spreadsheet->getDefinedNames()) > 0) {
// Named ranges
$this->writeNamedRangesAndFormulae();
}
// Other defined names
$sheetCount = $this->spreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
// NamedRange for autoFilter
$this->writeNamedRangeForAutofilter($this->spreadsheet->getSheet($i), $i);
// NamedRange for Print_Titles
$this->writeNamedRangeForPrintTitles($this->spreadsheet->getSheet($i), $i);
// NamedRange for Print_Area
$this->writeNamedRangeForPrintArea($this->spreadsheet->getSheet($i), $i);
}
$this->objWriter->endElement();
}
/**
* Write defined names.
*/
private function writeNamedRangesAndFormulae(): void
{
// Loop named ranges
$definedNames = $this->spreadsheet->getDefinedNames();
foreach ($definedNames as $definedName) {
$this->writeDefinedName($definedName);
}
}
/**
* Write Defined Name for named range.
*/
private function writeDefinedName(DefinedName $pDefinedName): void
{
// definedName for named range
$this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', $pDefinedName->getName());
if ($pDefinedName->getLocalOnly() && $pDefinedName->getScope() !== null) {
$this->objWriter->writeAttribute('localSheetId', $pDefinedName->getScope()->getParent()->getIndex($pDefinedName->getScope()));
}
$definedRange = $pDefinedName->getValue();
$splitCount = preg_match_all(
'/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
$definedRange,
$splitRanges,
PREG_OFFSET_CAPTURE
);
$lengths = array_map('strlen', array_column($splitRanges[0], 0));
$offsets = array_column($splitRanges[0], 1);
$worksheets = $splitRanges[2];
$columns = $splitRanges[6];
$rows = $splitRanges[7];
while ($splitCount > 0) {
--$splitCount;
$length = $lengths[$splitCount];
$offset = $offsets[$splitCount];
$worksheet = $worksheets[$splitCount][0];
$column = $columns[$splitCount][0];
$row = $rows[$splitCount][0];
$newRange = '';
if (empty($worksheet)) {
if (($offset === 0) || ($definedRange[$offset - 1] !== ':')) {
// We should have a worksheet
$worksheet = $pDefinedName->getWorksheet()->getTitle();
}
} else {
$worksheet = str_replace("''", "'", trim($worksheet, "'"));
}
if (!empty($worksheet)) {
$newRange = "'" . str_replace("'", "''", $worksheet) . "'!";
}
if (!empty($column)) {
$newRange .= $column;
}
if (!empty($row)) {
$newRange .= $row;
}
$definedRange = substr($definedRange, 0, $offset) . $newRange . substr($definedRange, $offset + $length);
}
if (substr($definedRange, 0, 1) === '=') {
$definedRange = substr($definedRange, 1);
}
$this->objWriter->writeRawData($definedRange);
$this->objWriter->endElement();
}
/**
* Write Defined Name for autoFilter.
*/
private function writeNamedRangeForAutofilter(Worksheet $pSheet, int $pSheetId = 0): void
{
// NamedRange for autoFilter
$autoFilterRange = $pSheet->getAutoFilter()->getRange();
if (!empty($autoFilterRange)) {
$this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', '_xlnm._FilterDatabase');
$this->objWriter->writeAttribute('localSheetId', $pSheetId);
$this->objWriter->writeAttribute('hidden', '1');
// Create absolute coordinate and write as raw text
$range = Coordinate::splitRange($autoFilterRange);
$range = $range[0];
// Strip any worksheet ref so we can make the cell ref absolute
[$ws, $range[0]] = Worksheet::extractSheetTitle($range[0], true);
$range[0] = Coordinate::absoluteCoordinate($range[0]);
$range[1] = Coordinate::absoluteCoordinate($range[1]);
$range = implode(':', $range);
$this->objWriter->writeRawData('\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . $range);
$this->objWriter->endElement();
}
}
/**
* Write Defined Name for PrintTitles.
*/
private function writeNamedRangeForPrintTitles(Worksheet $pSheet, int $pSheetId = 0): void
{
// NamedRange for PrintTitles
if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
$this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', '_xlnm.Print_Titles');
$this->objWriter->writeAttribute('localSheetId', $pSheetId);
// Setting string
$settingString = '';
// Columns to repeat
if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
$repeat = $pSheet->getPageSetup()->getColumnsToRepeatAtLeft();
$settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
}
// Rows to repeat
if ($pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
$settingString .= ',';
}
$repeat = $pSheet->getPageSetup()->getRowsToRepeatAtTop();
$settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
}
$this->objWriter->writeRawData($settingString);
$this->objWriter->endElement();
}
}
/**
* Write Defined Name for PrintTitles.
*/
private function writeNamedRangeForPrintArea(Worksheet $pSheet, int $pSheetId = 0): void
{
// NamedRange for PrintArea
if ($pSheet->getPageSetup()->isPrintAreaSet()) {
$this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', '_xlnm.Print_Area');
$this->objWriter->writeAttribute('localSheetId', $pSheetId);
// Print area
$printArea = Coordinate::splitRange($pSheet->getPageSetup()->getPrintArea());
$chunks = [];
foreach ($printArea as $printAreaRect) {
$printAreaRect[0] = Coordinate::absoluteReference($printAreaRect[0]);
$printAreaRect[1] = Coordinate::absoluteReference($printAreaRect[1]);
$chunks[] = '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . implode(':', $printAreaRect);
}
$this->objWriter->writeRawData(implode(',', $chunks));
$this->objWriter->endElement();
}
}
}

View File

@@ -0,0 +1,239 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class DocProps extends WriterPart
{
/**
* Write docProps/app.xml to XML format.
*
* @return string XML Output
*/
public function writeDocPropsApp(Spreadsheet $spreadsheet)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Properties
$objWriter->startElement('Properties');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties');
$objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
// Application
$objWriter->writeElement('Application', 'Microsoft Excel');
// DocSecurity
$objWriter->writeElement('DocSecurity', '0');
// ScaleCrop
$objWriter->writeElement('ScaleCrop', 'false');
// HeadingPairs
$objWriter->startElement('HeadingPairs');
// Vector
$objWriter->startElement('vt:vector');
$objWriter->writeAttribute('size', '2');
$objWriter->writeAttribute('baseType', 'variant');
// Variant
$objWriter->startElement('vt:variant');
$objWriter->writeElement('vt:lpstr', 'Worksheets');
$objWriter->endElement();
// Variant
$objWriter->startElement('vt:variant');
$objWriter->writeElement('vt:i4', $spreadsheet->getSheetCount());
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// TitlesOfParts
$objWriter->startElement('TitlesOfParts');
// Vector
$objWriter->startElement('vt:vector');
$objWriter->writeAttribute('size', $spreadsheet->getSheetCount());
$objWriter->writeAttribute('baseType', 'lpstr');
$sheetCount = $spreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
$objWriter->writeElement('vt:lpstr', $spreadsheet->getSheet($i)->getTitle());
}
$objWriter->endElement();
$objWriter->endElement();
// Company
$objWriter->writeElement('Company', $spreadsheet->getProperties()->getCompany());
// Company
$objWriter->writeElement('Manager', $spreadsheet->getProperties()->getManager());
// LinksUpToDate
$objWriter->writeElement('LinksUpToDate', 'false');
// SharedDoc
$objWriter->writeElement('SharedDoc', 'false');
// HyperlinksChanged
$objWriter->writeElement('HyperlinksChanged', 'false');
// AppVersion
$objWriter->writeElement('AppVersion', '12.0000');
$objWriter->endElement();
// Return
return $objWriter->getData();
}
/**
* Write docProps/core.xml to XML format.
*
* @return string XML Output
*/
public function writeDocPropsCore(Spreadsheet $spreadsheet)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// cp:coreProperties
$objWriter->startElement('cp:coreProperties');
$objWriter->writeAttribute('xmlns:cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties');
$objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
$objWriter->writeAttribute('xmlns:dcterms', 'http://purl.org/dc/terms/');
$objWriter->writeAttribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/');
$objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
// dc:creator
$objWriter->writeElement('dc:creator', $spreadsheet->getProperties()->getCreator());
// cp:lastModifiedBy
$objWriter->writeElement('cp:lastModifiedBy', $spreadsheet->getProperties()->getLastModifiedBy());
// dcterms:created
$objWriter->startElement('dcterms:created');
$objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF');
$objWriter->writeRawData(date(DATE_W3C, $spreadsheet->getProperties()->getCreated()));
$objWriter->endElement();
// dcterms:modified
$objWriter->startElement('dcterms:modified');
$objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF');
$objWriter->writeRawData(date(DATE_W3C, $spreadsheet->getProperties()->getModified()));
$objWriter->endElement();
// dc:title
$objWriter->writeElement('dc:title', $spreadsheet->getProperties()->getTitle());
// dc:description
$objWriter->writeElement('dc:description', $spreadsheet->getProperties()->getDescription());
// dc:subject
$objWriter->writeElement('dc:subject', $spreadsheet->getProperties()->getSubject());
// cp:keywords
$objWriter->writeElement('cp:keywords', $spreadsheet->getProperties()->getKeywords());
// cp:category
$objWriter->writeElement('cp:category', $spreadsheet->getProperties()->getCategory());
$objWriter->endElement();
// Return
return $objWriter->getData();
}
/**
* Write docProps/custom.xml to XML format.
*
* @return string XML Output
*/
public function writeDocPropsCustom(Spreadsheet $spreadsheet)
{
$customPropertyList = $spreadsheet->getProperties()->getCustomProperties();
if (empty($customPropertyList)) {
return;
}
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// cp:coreProperties
$objWriter->startElement('Properties');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties');
$objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
foreach ($customPropertyList as $key => $customProperty) {
$propertyValue = $spreadsheet->getProperties()->getCustomPropertyValue($customProperty);
$propertyType = $spreadsheet->getProperties()->getCustomPropertyType($customProperty);
$objWriter->startElement('property');
$objWriter->writeAttribute('fmtid', '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}');
$objWriter->writeAttribute('pid', $key + 2);
$objWriter->writeAttribute('name', $customProperty);
switch ($propertyType) {
case 'i':
$objWriter->writeElement('vt:i4', $propertyValue);
break;
case 'f':
$objWriter->writeElement('vt:r8', $propertyValue);
break;
case 'b':
$objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false');
break;
case 'd':
$objWriter->startElement('vt:filetime');
$objWriter->writeRawData(date(DATE_W3C, $propertyValue));
$objWriter->endElement();
break;
default:
$objWriter->writeElement('vt:lpwstr', $propertyValue);
break;
}
$objWriter->endElement();
}
$objWriter->endElement();
return $objWriter->getData();
}
}

View File

@@ -0,0 +1,505 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing;
use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
class Drawing extends WriterPart
{
/**
* Write drawings to XML format.
*
* @param bool $includeCharts Flag indicating if we should include drawing details for charts
*
* @return string XML Output
*/
public function writeDrawings(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet, $includeCharts = false)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// xdr:wsDr
$objWriter->startElement('xdr:wsDr');
$objWriter->writeAttribute('xmlns:xdr', 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
$objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
// Loop through images and write drawings
$i = 1;
$iterator = $pWorksheet->getDrawingCollection()->getIterator();
while ($iterator->valid()) {
/** @var BaseDrawing $pDrawing */
$pDrawing = $iterator->current();
$pRelationId = $i;
$hlinkClickId = $pDrawing->getHyperlink() === null ? null : ++$i;
$this->writeDrawing($objWriter, $pDrawing, $pRelationId, $hlinkClickId);
$iterator->next();
++$i;
}
if ($includeCharts) {
$chartCount = $pWorksheet->getChartCount();
// Loop through charts and write the chart position
if ($chartCount > 0) {
for ($c = 0; $c < $chartCount; ++$c) {
$this->writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c + $i);
}
}
}
// unparsed AlternateContent
$unparsedLoadedData = $pWorksheet->getParent()->getUnparsedLoadedData();
if (isset($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()]['drawingAlternateContents'])) {
foreach ($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()]['drawingAlternateContents'] as $drawingAlternateContent) {
$objWriter->writeRaw($drawingAlternateContent);
}
}
$objWriter->endElement();
// Return
return $objWriter->getData();
}
/**
* Write drawings to XML format.
*
* @param XMLWriter $objWriter XML Writer
* @param int $pRelationId
*/
public function writeChart(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Chart\Chart $pChart, $pRelationId = -1): void
{
$tl = $pChart->getTopLeftPosition();
$tl['colRow'] = Coordinate::coordinateFromString($tl['cell']);
$br = $pChart->getBottomRightPosition();
$br['colRow'] = Coordinate::coordinateFromString($br['cell']);
$objWriter->startElement('xdr:twoCellAnchor');
$objWriter->startElement('xdr:from');
$objWriter->writeElement('xdr:col', Coordinate::columnIndexFromString($tl['colRow'][0]) - 1);
$objWriter->writeElement('xdr:colOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($tl['xOffset']));
$objWriter->writeElement('xdr:row', $tl['colRow'][1] - 1);
$objWriter->writeElement('xdr:rowOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($tl['yOffset']));
$objWriter->endElement();
$objWriter->startElement('xdr:to');
$objWriter->writeElement('xdr:col', Coordinate::columnIndexFromString($br['colRow'][0]) - 1);
$objWriter->writeElement('xdr:colOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($br['xOffset']));
$objWriter->writeElement('xdr:row', $br['colRow'][1] - 1);
$objWriter->writeElement('xdr:rowOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($br['yOffset']));
$objWriter->endElement();
$objWriter->startElement('xdr:graphicFrame');
$objWriter->writeAttribute('macro', '');
$objWriter->startElement('xdr:nvGraphicFramePr');
$objWriter->startElement('xdr:cNvPr');
$objWriter->writeAttribute('name', 'Chart ' . $pRelationId);
$objWriter->writeAttribute('id', 1025 * $pRelationId);
$objWriter->endElement();
$objWriter->startElement('xdr:cNvGraphicFramePr');
$objWriter->startElement('a:graphicFrameLocks');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->startElement('xdr:xfrm');
$objWriter->startElement('a:off');
$objWriter->writeAttribute('x', '0');
$objWriter->writeAttribute('y', '0');
$objWriter->endElement();
$objWriter->startElement('a:ext');
$objWriter->writeAttribute('cx', '0');
$objWriter->writeAttribute('cy', '0');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->startElement('a:graphic');
$objWriter->startElement('a:graphicData');
$objWriter->writeAttribute('uri', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
$objWriter->startElement('c:chart');
$objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
$objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
$objWriter->writeAttribute('r:id', 'rId' . $pRelationId);
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->startElement('xdr:clientData');
$objWriter->endElement();
$objWriter->endElement();
}
/**
* Write drawings to XML format.
*
* @param XMLWriter $objWriter XML Writer
* @param int $pRelationId
* @param null|int $hlinkClickId
*/
public function writeDrawing(XMLWriter $objWriter, BaseDrawing $pDrawing, $pRelationId = -1, $hlinkClickId = null): void
{
if ($pRelationId >= 0) {
// xdr:oneCellAnchor
$objWriter->startElement('xdr:oneCellAnchor');
// Image location
$aCoordinates = Coordinate::coordinateFromString($pDrawing->getCoordinates());
$aCoordinates[0] = Coordinate::columnIndexFromString($aCoordinates[0]);
// xdr:from
$objWriter->startElement('xdr:from');
$objWriter->writeElement('xdr:col', $aCoordinates[0] - 1);
$objWriter->writeElement('xdr:colOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getOffsetX()));
$objWriter->writeElement('xdr:row', $aCoordinates[1] - 1);
$objWriter->writeElement('xdr:rowOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getOffsetY()));
$objWriter->endElement();
// xdr:ext
$objWriter->startElement('xdr:ext');
$objWriter->writeAttribute('cx', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getWidth()));
$objWriter->writeAttribute('cy', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getHeight()));
$objWriter->endElement();
// xdr:pic
$objWriter->startElement('xdr:pic');
// xdr:nvPicPr
$objWriter->startElement('xdr:nvPicPr');
// xdr:cNvPr
$objWriter->startElement('xdr:cNvPr');
$objWriter->writeAttribute('id', $pRelationId);
$objWriter->writeAttribute('name', $pDrawing->getName());
$objWriter->writeAttribute('descr', $pDrawing->getDescription());
//a:hlinkClick
$this->writeHyperLinkDrawing($objWriter, $hlinkClickId);
$objWriter->endElement();
// xdr:cNvPicPr
$objWriter->startElement('xdr:cNvPicPr');
// a:picLocks
$objWriter->startElement('a:picLocks');
$objWriter->writeAttribute('noChangeAspect', '1');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// xdr:blipFill
$objWriter->startElement('xdr:blipFill');
// a:blip
$objWriter->startElement('a:blip');
$objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
$objWriter->writeAttribute('r:embed', 'rId' . $pRelationId);
$objWriter->endElement();
// a:stretch
$objWriter->startElement('a:stretch');
$objWriter->writeElement('a:fillRect', null);
$objWriter->endElement();
$objWriter->endElement();
// xdr:spPr
$objWriter->startElement('xdr:spPr');
// a:xfrm
$objWriter->startElement('a:xfrm');
$objWriter->writeAttribute('rot', \PhpOffice\PhpSpreadsheet\Shared\Drawing::degreesToAngle($pDrawing->getRotation()));
$objWriter->endElement();
// a:prstGeom
$objWriter->startElement('a:prstGeom');
$objWriter->writeAttribute('prst', 'rect');
// a:avLst
$objWriter->writeElement('a:avLst', null);
$objWriter->endElement();
if ($pDrawing->getShadow()->getVisible()) {
// a:effectLst
$objWriter->startElement('a:effectLst');
// a:outerShdw
$objWriter->startElement('a:outerShdw');
$objWriter->writeAttribute('blurRad', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getShadow()->getBlurRadius()));
$objWriter->writeAttribute('dist', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getShadow()->getDistance()));
$objWriter->writeAttribute('dir', \PhpOffice\PhpSpreadsheet\Shared\Drawing::degreesToAngle($pDrawing->getShadow()->getDirection()));
$objWriter->writeAttribute('algn', $pDrawing->getShadow()->getAlignment());
$objWriter->writeAttribute('rotWithShape', '0');
// a:srgbClr
$objWriter->startElement('a:srgbClr');
$objWriter->writeAttribute('val', $pDrawing->getShadow()->getColor()->getRGB());
// a:alpha
$objWriter->startElement('a:alpha');
$objWriter->writeAttribute('val', $pDrawing->getShadow()->getAlpha() * 1000);
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
}
$objWriter->endElement();
$objWriter->endElement();
// xdr:clientData
$objWriter->writeElement('xdr:clientData', null);
$objWriter->endElement();
} else {
throw new WriterException('Invalid parameters passed.');
}
}
/**
* Write VML header/footer images to XML format.
*
* @return string XML Output
*/
public function writeVMLHeaderFooterImages(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Header/footer images
$images = $pWorksheet->getHeaderFooter()->getImages();
// xml
$objWriter->startElement('xml');
$objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml');
$objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office');
$objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel');
// o:shapelayout
$objWriter->startElement('o:shapelayout');
$objWriter->writeAttribute('v:ext', 'edit');
// o:idmap
$objWriter->startElement('o:idmap');
$objWriter->writeAttribute('v:ext', 'edit');
$objWriter->writeAttribute('data', '1');
$objWriter->endElement();
$objWriter->endElement();
// v:shapetype
$objWriter->startElement('v:shapetype');
$objWriter->writeAttribute('id', '_x0000_t75');
$objWriter->writeAttribute('coordsize', '21600,21600');
$objWriter->writeAttribute('o:spt', '75');
$objWriter->writeAttribute('o:preferrelative', 't');
$objWriter->writeAttribute('path', 'm@4@5l@4@11@9@11@9@5xe');
$objWriter->writeAttribute('filled', 'f');
$objWriter->writeAttribute('stroked', 'f');
// v:stroke
$objWriter->startElement('v:stroke');
$objWriter->writeAttribute('joinstyle', 'miter');
$objWriter->endElement();
// v:formulas
$objWriter->startElement('v:formulas');
// v:f
$objWriter->startElement('v:f');
$objWriter->writeAttribute('eqn', 'if lineDrawn pixelLineWidth 0');
$objWriter->endElement();
// v:f
$objWriter->startElement('v:f');
$objWriter->writeAttribute('eqn', 'sum @0 1 0');
$objWriter->endElement();
// v:f
$objWriter->startElement('v:f');
$objWriter->writeAttribute('eqn', 'sum 0 0 @1');
$objWriter->endElement();
// v:f
$objWriter->startElement('v:f');
$objWriter->writeAttribute('eqn', 'prod @2 1 2');
$objWriter->endElement();
// v:f
$objWriter->startElement('v:f');
$objWriter->writeAttribute('eqn', 'prod @3 21600 pixelWidth');
$objWriter->endElement();
// v:f
$objWriter->startElement('v:f');
$objWriter->writeAttribute('eqn', 'prod @3 21600 pixelHeight');
$objWriter->endElement();
// v:f
$objWriter->startElement('v:f');
$objWriter->writeAttribute('eqn', 'sum @0 0 1');
$objWriter->endElement();
// v:f
$objWriter->startElement('v:f');
$objWriter->writeAttribute('eqn', 'prod @6 1 2');
$objWriter->endElement();
// v:f
$objWriter->startElement('v:f');
$objWriter->writeAttribute('eqn', 'prod @7 21600 pixelWidth');
$objWriter->endElement();
// v:f
$objWriter->startElement('v:f');
$objWriter->writeAttribute('eqn', 'sum @8 21600 0');
$objWriter->endElement();
// v:f
$objWriter->startElement('v:f');
$objWriter->writeAttribute('eqn', 'prod @7 21600 pixelHeight');
$objWriter->endElement();
// v:f
$objWriter->startElement('v:f');
$objWriter->writeAttribute('eqn', 'sum @10 21600 0');
$objWriter->endElement();
$objWriter->endElement();
// v:path
$objWriter->startElement('v:path');
$objWriter->writeAttribute('o:extrusionok', 'f');
$objWriter->writeAttribute('gradientshapeok', 't');
$objWriter->writeAttribute('o:connecttype', 'rect');
$objWriter->endElement();
// o:lock
$objWriter->startElement('o:lock');
$objWriter->writeAttribute('v:ext', 'edit');
$objWriter->writeAttribute('aspectratio', 't');
$objWriter->endElement();
$objWriter->endElement();
// Loop through images
foreach ($images as $key => $value) {
$this->writeVMLHeaderFooterImage($objWriter, $key, $value);
}
$objWriter->endElement();
// Return
return $objWriter->getData();
}
/**
* Write VML comment to XML format.
*
* @param XMLWriter $objWriter XML Writer
* @param string $pReference Reference
* @param HeaderFooterDrawing $pImage Image
*/
private function writeVMLHeaderFooterImage(XMLWriter $objWriter, $pReference, HeaderFooterDrawing $pImage): void
{
// Calculate object id
preg_match('{(\d+)}', md5($pReference), $m);
$id = 1500 + (substr($m[1], 0, 2) * 1);
// Calculate offset
$width = $pImage->getWidth();
$height = $pImage->getHeight();
$marginLeft = $pImage->getOffsetX();
$marginTop = $pImage->getOffsetY();
// v:shape
$objWriter->startElement('v:shape');
$objWriter->writeAttribute('id', $pReference);
$objWriter->writeAttribute('o:spid', '_x0000_s' . $id);
$objWriter->writeAttribute('type', '#_x0000_t75');
$objWriter->writeAttribute('style', "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1");
// v:imagedata
$objWriter->startElement('v:imagedata');
$objWriter->writeAttribute('o:relid', 'rId' . $pReference);
$objWriter->writeAttribute('o:title', $pImage->getName());
$objWriter->endElement();
// o:lock
$objWriter->startElement('o:lock');
$objWriter->writeAttribute('v:ext', 'edit');
$objWriter->writeAttribute('textRotation', 't');
$objWriter->endElement();
$objWriter->endElement();
}
/**
* Get an array of all drawings.
*
* @return \PhpOffice\PhpSpreadsheet\Worksheet\Drawing[] All drawings in PhpSpreadsheet
*/
public function allDrawings(Spreadsheet $spreadsheet)
{
// Get an array of all drawings
$aDrawings = [];
// Loop through PhpSpreadsheet
$sheetCount = $spreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
// Loop through images and add to array
$iterator = $spreadsheet->getSheet($i)->getDrawingCollection()->getIterator();
while ($iterator->valid()) {
$aDrawings[] = $iterator->current();
$iterator->next();
}
}
return $aDrawings;
}
/**
* @param null|int $hlinkClickId
*/
private function writeHyperLinkDrawing(XMLWriter $objWriter, $hlinkClickId): void
{
if ($hlinkClickId === null) {
return;
}
$objWriter->startElement('a:hlinkClick');
$objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
$objWriter->writeAttribute('r:id', 'rId' . $hlinkClickId);
$objWriter->endElement();
}
}

View File

@@ -0,0 +1,451 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
class Rels extends WriterPart
{
/**
* Write relationships to XML format.
*
* @return string XML Output
*/
public function writeRelationships(Spreadsheet $spreadsheet)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Relationships
$objWriter->startElement('Relationships');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
$customPropertyList = $spreadsheet->getProperties()->getCustomProperties();
if (!empty($customPropertyList)) {
// Relationship docProps/app.xml
$this->writeRelationship(
$objWriter,
4,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties',
'docProps/custom.xml'
);
}
// Relationship docProps/app.xml
$this->writeRelationship(
$objWriter,
3,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties',
'docProps/app.xml'
);
// Relationship docProps/core.xml
$this->writeRelationship(
$objWriter,
2,
'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties',
'docProps/core.xml'
);
// Relationship xl/workbook.xml
$this->writeRelationship(
$objWriter,
1,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument',
'xl/workbook.xml'
);
// a custom UI in workbook ?
if ($spreadsheet->hasRibbon()) {
$this->writeRelationShip(
$objWriter,
5,
'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility',
$spreadsheet->getRibbonXMLData('target')
);
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write workbook relationships to XML format.
*
* @return string XML Output
*/
public function writeWorkbookRelationships(Spreadsheet $spreadsheet)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Relationships
$objWriter->startElement('Relationships');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
// Relationship styles.xml
$this->writeRelationship(
$objWriter,
1,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',
'styles.xml'
);
// Relationship theme/theme1.xml
$this->writeRelationship(
$objWriter,
2,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
'theme/theme1.xml'
);
// Relationship sharedStrings.xml
$this->writeRelationship(
$objWriter,
3,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings',
'sharedStrings.xml'
);
// Relationships with sheets
$sheetCount = $spreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
$this->writeRelationship(
$objWriter,
($i + 1 + 3),
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet',
'worksheets/sheet' . ($i + 1) . '.xml'
);
}
// Relationships for vbaProject if needed
// id : just after the last sheet
if ($spreadsheet->hasMacros()) {
$this->writeRelationShip(
$objWriter,
($i + 1 + 3),
'http://schemas.microsoft.com/office/2006/relationships/vbaProject',
'vbaProject.bin'
);
++$i; //increment i if needed for an another relation
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write worksheet relationships to XML format.
*
* Numbering is as follows:
* rId1 - Drawings
* rId_hyperlink_x - Hyperlinks
*
* @param int $pWorksheetId
* @param bool $includeCharts Flag indicating if we should write charts
*
* @return string XML Output
*/
public function writeWorksheetRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet, $pWorksheetId = 1, $includeCharts = false)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Relationships
$objWriter->startElement('Relationships');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
// Write drawing relationships?
$drawingOriginalIds = [];
$unparsedLoadedData = $pWorksheet->getParent()->getUnparsedLoadedData();
if (isset($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()]['drawingOriginalIds'])) {
$drawingOriginalIds = $unparsedLoadedData['sheets'][$pWorksheet->getCodeName()]['drawingOriginalIds'];
}
if ($includeCharts) {
$charts = $pWorksheet->getChartCollection();
} else {
$charts = [];
}
if (($pWorksheet->getDrawingCollection()->count() > 0) || (count($charts) > 0) || $drawingOriginalIds) {
$rId = 1;
// Use original $relPath to get original $rId.
// Take first. In future can be overwritten.
// (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet::writeDrawings)
reset($drawingOriginalIds);
$relPath = key($drawingOriginalIds);
if (isset($drawingOriginalIds[$relPath])) {
$rId = (int) (substr($drawingOriginalIds[$relPath], 3));
}
// Generate new $relPath to write drawing relationship
$relPath = '../drawings/drawing' . $pWorksheetId . '.xml';
$this->writeRelationship(
$objWriter,
$rId,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing',
$relPath
);
}
// Write hyperlink relationships?
$i = 1;
foreach ($pWorksheet->getHyperlinkCollection() as $hyperlink) {
if (!$hyperlink->isInternal()) {
$this->writeRelationship(
$objWriter,
'_hyperlink_' . $i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
$hyperlink->getUrl(),
'External'
);
++$i;
}
}
// Write comments relationship?
$i = 1;
if (count($pWorksheet->getComments()) > 0) {
$this->writeRelationship(
$objWriter,
'_comments_vml' . $i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
'../drawings/vmlDrawing' . $pWorksheetId . '.vml'
);
$this->writeRelationship(
$objWriter,
'_comments' . $i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments',
'../comments' . $pWorksheetId . '.xml'
);
}
// Write header/footer relationship?
$i = 1;
if (count($pWorksheet->getHeaderFooter()->getImages()) > 0) {
$this->writeRelationship(
$objWriter,
'_headerfooter_vml' . $i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
'../drawings/vmlDrawingHF' . $pWorksheetId . '.vml'
);
}
$this->writeUnparsedRelationship($pWorksheet, $objWriter, 'ctrlProps', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp');
$this->writeUnparsedRelationship($pWorksheet, $objWriter, 'vmlDrawings', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing');
$this->writeUnparsedRelationship($pWorksheet, $objWriter, 'printerSettings', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings');
$objWriter->endElement();
return $objWriter->getData();
}
private function writeUnparsedRelationship(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet, XMLWriter $objWriter, $relationship, $type): void
{
$unparsedLoadedData = $pWorksheet->getParent()->getUnparsedLoadedData();
if (!isset($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()][$relationship])) {
return;
}
foreach ($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()][$relationship] as $rId => $value) {
$this->writeRelationship(
$objWriter,
$rId,
$type,
$value['relFilePath']
);
}
}
/**
* Write drawing relationships to XML format.
*
* @param int &$chartRef Chart ID
* @param bool $includeCharts Flag indicating if we should write charts
*
* @return string XML Output
*/
public function writeDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet, &$chartRef, $includeCharts = false)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Relationships
$objWriter->startElement('Relationships');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
// Loop through images and write relationships
$i = 1;
$iterator = $pWorksheet->getDrawingCollection()->getIterator();
while ($iterator->valid()) {
if (
$iterator->current() instanceof \PhpOffice\PhpSpreadsheet\Worksheet\Drawing
|| $iterator->current() instanceof MemoryDrawing
) {
// Write relationship for image drawing
/** @var \PhpOffice\PhpSpreadsheet\Worksheet\Drawing $drawing */
$drawing = $iterator->current();
$this->writeRelationship(
$objWriter,
$i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
'../media/' . str_replace(' ', '', $drawing->getIndexedFilename())
);
$i = $this->writeDrawingHyperLink($objWriter, $drawing, $i);
}
$iterator->next();
++$i;
}
if ($includeCharts) {
// Loop through charts and write relationships
$chartCount = $pWorksheet->getChartCount();
if ($chartCount > 0) {
for ($c = 0; $c < $chartCount; ++$c) {
$this->writeRelationship(
$objWriter,
$i++,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart',
'../charts/chart' . ++$chartRef . '.xml'
);
}
}
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write header/footer drawing relationships to XML format.
*
* @return string XML Output
*/
public function writeHeaderFooterDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Relationships
$objWriter->startElement('Relationships');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
// Loop through images and write relationships
foreach ($pWorksheet->getHeaderFooter()->getImages() as $key => $value) {
// Write relationship for image drawing
$this->writeRelationship(
$objWriter,
$key,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
'../media/' . $value->getIndexedFilename()
);
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write Override content type.
*
* @param XMLWriter $objWriter XML Writer
* @param int $pId Relationship ID. rId will be prepended!
* @param string $pType Relationship type
* @param string $pTarget Relationship target
* @param string $pTargetMode Relationship target mode
*/
private function writeRelationship(XMLWriter $objWriter, $pId, $pType, $pTarget, $pTargetMode = ''): void
{
if ($pType != '' && $pTarget != '') {
// Write relationship
$objWriter->startElement('Relationship');
$objWriter->writeAttribute('Id', 'rId' . $pId);
$objWriter->writeAttribute('Type', $pType);
$objWriter->writeAttribute('Target', $pTarget);
if ($pTargetMode != '') {
$objWriter->writeAttribute('TargetMode', $pTargetMode);
}
$objWriter->endElement();
} else {
throw new WriterException('Invalid parameters passed.');
}
}
/**
* @param $objWriter
* @param \PhpOffice\PhpSpreadsheet\Worksheet\Drawing $drawing
* @param $i
*
* @return int
*/
private function writeDrawingHyperLink($objWriter, $drawing, $i)
{
if ($drawing->getHyperlink() === null) {
return $i;
}
++$i;
$this->writeRelationship(
$objWriter,
$i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
$drawing->getHyperlink()->getUrl(),
$drawing->getHyperlink()->getTypeHyperlink()
);
return $i;
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class RelsRibbon extends WriterPart
{
/**
* Write relationships for additional objects of custom UI (ribbon).
*
* @return string XML Output
*/
public function writeRibbonRelationships(Spreadsheet $spreadsheet)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Relationships
$objWriter->startElement('Relationships');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
$localRels = $spreadsheet->getRibbonBinObjects('names');
if (is_array($localRels)) {
foreach ($localRels as $aId => $aTarget) {
$objWriter->startElement('Relationship');
$objWriter->writeAttribute('Id', $aId);
$objWriter->writeAttribute('Type', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image');
$objWriter->writeAttribute('Target', $aTarget);
$objWriter->endElement();
}
}
$objWriter->endElement();
return $objWriter->getData();
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class RelsVBA extends WriterPart
{
/**
* Write relationships for a signed VBA Project.
*
* @return string XML Output
*/
public function writeVBARelationships(Spreadsheet $spreadsheet)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Relationships
$objWriter->startElement('Relationships');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
$objWriter->startElement('Relationship');
$objWriter->writeAttribute('Id', 'rId1');
$objWriter->writeAttribute('Type', 'http://schemas.microsoft.com/office/2006/relationships/vbaProjectSignature');
$objWriter->writeAttribute('Target', 'vbaProjectSignature.bin');
$objWriter->endElement();
$objWriter->endElement();
return $objWriter->getData();
}
}

View File

@@ -0,0 +1,282 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\RichText\Run;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class StringTable extends WriterPart
{
/**
* Create worksheet stringtable.
*
* @param Worksheet $pSheet Worksheet
* @param string[] $pExistingTable Existing table to eventually merge with
*
* @return string[] String table for worksheet
*/
public function createStringTable(Worksheet $pSheet, $pExistingTable = null)
{
// Create string lookup table
$aStringTable = [];
$cellCollection = null;
$aFlippedStringTable = null; // For faster lookup
// Is an existing table given?
if (($pExistingTable !== null) && is_array($pExistingTable)) {
$aStringTable = $pExistingTable;
}
// Fill index array
$aFlippedStringTable = $this->flipStringTable($aStringTable);
// Loop through cells
foreach ($pSheet->getCoordinates() as $coordinate) {
$cell = $pSheet->getCell($coordinate);
$cellValue = $cell->getValue();
if (
!is_object($cellValue) &&
($cellValue !== null) &&
$cellValue !== '' &&
!isset($aFlippedStringTable[$cellValue]) &&
($cell->getDataType() == DataType::TYPE_STRING || $cell->getDataType() == DataType::TYPE_STRING2 || $cell->getDataType() == DataType::TYPE_NULL)
) {
$aStringTable[] = $cellValue;
$aFlippedStringTable[$cellValue] = true;
} elseif (
$cellValue instanceof RichText &&
($cellValue !== null) &&
!isset($aFlippedStringTable[$cellValue->getHashCode()])
) {
$aStringTable[] = $cellValue;
$aFlippedStringTable[$cellValue->getHashCode()] = true;
}
}
return $aStringTable;
}
/**
* Write string table to XML format.
*
* @param string[] $pStringTable
*
* @return string XML Output
*/
public function writeStringTable(array $pStringTable)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// String table
$objWriter->startElement('sst');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
$objWriter->writeAttribute('uniqueCount', count($pStringTable));
// Loop through string table
foreach ($pStringTable as $textElement) {
$objWriter->startElement('si');
if (!$textElement instanceof RichText) {
$textToWrite = StringHelper::controlCharacterPHP2OOXML($textElement);
$objWriter->startElement('t');
if ($textToWrite !== trim($textToWrite)) {
$objWriter->writeAttribute('xml:space', 'preserve');
}
$objWriter->writeRawData($textToWrite);
$objWriter->endElement();
} elseif ($textElement instanceof RichText) {
$this->writeRichText($objWriter, $textElement);
}
$objWriter->endElement();
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write Rich Text.
*
* @param XMLWriter $objWriter XML Writer
* @param RichText $pRichText Rich text
* @param string $prefix Optional Namespace prefix
*/
public function writeRichText(XMLWriter $objWriter, RichText $pRichText, $prefix = null): void
{
if ($prefix !== null) {
$prefix .= ':';
}
// Loop through rich text elements
$elements = $pRichText->getRichTextElements();
foreach ($elements as $element) {
// r
$objWriter->startElement($prefix . 'r');
// rPr
if ($element instanceof Run) {
// rPr
$objWriter->startElement($prefix . 'rPr');
// rFont
$objWriter->startElement($prefix . 'rFont');
$objWriter->writeAttribute('val', $element->getFont()->getName());
$objWriter->endElement();
// Bold
$objWriter->startElement($prefix . 'b');
$objWriter->writeAttribute('val', ($element->getFont()->getBold() ? 'true' : 'false'));
$objWriter->endElement();
// Italic
$objWriter->startElement($prefix . 'i');
$objWriter->writeAttribute('val', ($element->getFont()->getItalic() ? 'true' : 'false'));
$objWriter->endElement();
// Superscript / subscript
if ($element->getFont()->getSuperscript() || $element->getFont()->getSubscript()) {
$objWriter->startElement($prefix . 'vertAlign');
if ($element->getFont()->getSuperscript()) {
$objWriter->writeAttribute('val', 'superscript');
} elseif ($element->getFont()->getSubscript()) {
$objWriter->writeAttribute('val', 'subscript');
}
$objWriter->endElement();
}
// Strikethrough
$objWriter->startElement($prefix . 'strike');
$objWriter->writeAttribute('val', ($element->getFont()->getStrikethrough() ? 'true' : 'false'));
$objWriter->endElement();
// Color
$objWriter->startElement($prefix . 'color');
$objWriter->writeAttribute('rgb', $element->getFont()->getColor()->getARGB());
$objWriter->endElement();
// Size
$objWriter->startElement($prefix . 'sz');
$objWriter->writeAttribute('val', $element->getFont()->getSize());
$objWriter->endElement();
// Underline
$objWriter->startElement($prefix . 'u');
$objWriter->writeAttribute('val', $element->getFont()->getUnderline());
$objWriter->endElement();
$objWriter->endElement();
}
// t
$objWriter->startElement($prefix . 't');
$objWriter->writeAttribute('xml:space', 'preserve');
$objWriter->writeRawData(StringHelper::controlCharacterPHP2OOXML($element->getText()));
$objWriter->endElement();
$objWriter->endElement();
}
}
/**
* Write Rich Text.
*
* @param XMLWriter $objWriter XML Writer
* @param RichText|string $pRichText text string or Rich text
* @param string $prefix Optional Namespace prefix
*/
public function writeRichTextForCharts(XMLWriter $objWriter, $pRichText = null, $prefix = null): void
{
if (!$pRichText instanceof RichText) {
$textRun = $pRichText;
$pRichText = new RichText();
$pRichText->createTextRun($textRun);
}
if ($prefix !== null) {
$prefix .= ':';
}
// Loop through rich text elements
$elements = $pRichText->getRichTextElements();
foreach ($elements as $element) {
// r
$objWriter->startElement($prefix . 'r');
// rPr
$objWriter->startElement($prefix . 'rPr');
// Bold
$objWriter->writeAttribute('b', ($element->getFont()->getBold() ? 1 : 0));
// Italic
$objWriter->writeAttribute('i', ($element->getFont()->getItalic() ? 1 : 0));
// Underline
$underlineType = $element->getFont()->getUnderline();
switch ($underlineType) {
case 'single':
$underlineType = 'sng';
break;
case 'double':
$underlineType = 'dbl';
break;
}
$objWriter->writeAttribute('u', $underlineType);
// Strikethrough
$objWriter->writeAttribute('strike', ($element->getFont()->getStrikethrough() ? 'sngStrike' : 'noStrike'));
// rFont
$objWriter->startElement($prefix . 'latin');
$objWriter->writeAttribute('typeface', $element->getFont()->getName());
$objWriter->endElement();
$objWriter->endElement();
// t
$objWriter->startElement($prefix . 't');
$objWriter->writeRawData(StringHelper::controlCharacterPHP2OOXML($element->getText()));
$objWriter->endElement();
$objWriter->endElement();
}
}
/**
* Flip string table (for index searching).
*
* @param array $stringTable Stringtable
*
* @return array
*/
public function flipStringTable(array $stringTable)
{
// Return value
$returnValue = [];
// Loop through stringtable and add flipped items to $returnValue
foreach ($stringTable as $key => $value) {
if (!$value instanceof RichText) {
$returnValue[$value] = $key;
} elseif ($value instanceof RichText) {
$returnValue[$value->getHashCode()] = $key;
}
}
return $returnValue;
}
}

View File

@@ -0,0 +1,676 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Borders;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Font;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Protection;
class Style extends WriterPart
{
/**
* Write styles to XML format.
*
* @return string XML Output
*/
public function writeStyles(Spreadsheet $spreadsheet)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// styleSheet
$objWriter->startElement('styleSheet');
$objWriter->writeAttribute('xml:space', 'preserve');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
// numFmts
$objWriter->startElement('numFmts');
$objWriter->writeAttribute('count', $this->getParentWriter()->getNumFmtHashTable()->count());
// numFmt
for ($i = 0; $i < $this->getParentWriter()->getNumFmtHashTable()->count(); ++$i) {
$this->writeNumFmt($objWriter, $this->getParentWriter()->getNumFmtHashTable()->getByIndex($i), $i);
}
$objWriter->endElement();
// fonts
$objWriter->startElement('fonts');
$objWriter->writeAttribute('count', $this->getParentWriter()->getFontHashTable()->count());
// font
for ($i = 0; $i < $this->getParentWriter()->getFontHashTable()->count(); ++$i) {
$this->writeFont($objWriter, $this->getParentWriter()->getFontHashTable()->getByIndex($i));
}
$objWriter->endElement();
// fills
$objWriter->startElement('fills');
$objWriter->writeAttribute('count', $this->getParentWriter()->getFillHashTable()->count());
// fill
for ($i = 0; $i < $this->getParentWriter()->getFillHashTable()->count(); ++$i) {
$this->writeFill($objWriter, $this->getParentWriter()->getFillHashTable()->getByIndex($i));
}
$objWriter->endElement();
// borders
$objWriter->startElement('borders');
$objWriter->writeAttribute('count', $this->getParentWriter()->getBordersHashTable()->count());
// border
for ($i = 0; $i < $this->getParentWriter()->getBordersHashTable()->count(); ++$i) {
$this->writeBorder($objWriter, $this->getParentWriter()->getBordersHashTable()->getByIndex($i));
}
$objWriter->endElement();
// cellStyleXfs
$objWriter->startElement('cellStyleXfs');
$objWriter->writeAttribute('count', 1);
// xf
$objWriter->startElement('xf');
$objWriter->writeAttribute('numFmtId', 0);
$objWriter->writeAttribute('fontId', 0);
$objWriter->writeAttribute('fillId', 0);
$objWriter->writeAttribute('borderId', 0);
$objWriter->endElement();
$objWriter->endElement();
// cellXfs
$objWriter->startElement('cellXfs');
$objWriter->writeAttribute('count', count($spreadsheet->getCellXfCollection()));
// xf
foreach ($spreadsheet->getCellXfCollection() as $cellXf) {
$this->writeCellStyleXf($objWriter, $cellXf, $spreadsheet);
}
$objWriter->endElement();
// cellStyles
$objWriter->startElement('cellStyles');
$objWriter->writeAttribute('count', 1);
// cellStyle
$objWriter->startElement('cellStyle');
$objWriter->writeAttribute('name', 'Normal');
$objWriter->writeAttribute('xfId', 0);
$objWriter->writeAttribute('builtinId', 0);
$objWriter->endElement();
$objWriter->endElement();
// dxfs
$objWriter->startElement('dxfs');
$objWriter->writeAttribute('count', $this->getParentWriter()->getStylesConditionalHashTable()->count());
// dxf
for ($i = 0; $i < $this->getParentWriter()->getStylesConditionalHashTable()->count(); ++$i) {
$this->writeCellStyleDxf($objWriter, $this->getParentWriter()->getStylesConditionalHashTable()->getByIndex($i)->getStyle());
}
$objWriter->endElement();
// tableStyles
$objWriter->startElement('tableStyles');
$objWriter->writeAttribute('defaultTableStyle', 'TableStyleMedium9');
$objWriter->writeAttribute('defaultPivotStyle', 'PivotTableStyle1');
$objWriter->endElement();
$objWriter->endElement();
// Return
return $objWriter->getData();
}
/**
* Write Fill.
*
* @param XMLWriter $objWriter XML Writer
* @param Fill $pFill Fill style
*/
private function writeFill(XMLWriter $objWriter, Fill $pFill): void
{
// Check if this is a pattern type or gradient type
if (
$pFill->getFillType() === Fill::FILL_GRADIENT_LINEAR ||
$pFill->getFillType() === Fill::FILL_GRADIENT_PATH
) {
// Gradient fill
$this->writeGradientFill($objWriter, $pFill);
} elseif ($pFill->getFillType() !== null) {
// Pattern fill
$this->writePatternFill($objWriter, $pFill);
}
}
/**
* Write Gradient Fill.
*
* @param XMLWriter $objWriter XML Writer
* @param Fill $pFill Fill style
*/
private function writeGradientFill(XMLWriter $objWriter, Fill $pFill): void
{
// fill
$objWriter->startElement('fill');
// gradientFill
$objWriter->startElement('gradientFill');
$objWriter->writeAttribute('type', $pFill->getFillType());
$objWriter->writeAttribute('degree', $pFill->getRotation());
// stop
$objWriter->startElement('stop');
$objWriter->writeAttribute('position', '0');
// color
$objWriter->startElement('color');
$objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB());
$objWriter->endElement();
$objWriter->endElement();
// stop
$objWriter->startElement('stop');
$objWriter->writeAttribute('position', '1');
// color
$objWriter->startElement('color');
$objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB());
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
}
/**
* Write Pattern Fill.
*
* @param XMLWriter $objWriter XML Writer
* @param Fill $pFill Fill style
*/
private function writePatternFill(XMLWriter $objWriter, Fill $pFill): void
{
// fill
$objWriter->startElement('fill');
// patternFill
$objWriter->startElement('patternFill');
$objWriter->writeAttribute('patternType', $pFill->getFillType());
if ($pFill->getFillType() !== Fill::FILL_NONE) {
// fgColor
if ($pFill->getStartColor()->getARGB()) {
$objWriter->startElement('fgColor');
$objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB());
$objWriter->endElement();
}
}
if ($pFill->getFillType() !== Fill::FILL_NONE) {
// bgColor
if ($pFill->getEndColor()->getARGB()) {
$objWriter->startElement('bgColor');
$objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB());
$objWriter->endElement();
}
}
$objWriter->endElement();
$objWriter->endElement();
}
/**
* Write Font.
*
* @param XMLWriter $objWriter XML Writer
* @param Font $pFont Font style
*/
private function writeFont(XMLWriter $objWriter, Font $pFont): void
{
// font
$objWriter->startElement('font');
// Weird! The order of these elements actually makes a difference when opening Xlsx
// files in Excel2003 with the compatibility pack. It's not documented behaviour,
// and makes for a real WTF!
// Bold. We explicitly write this element also when false (like MS Office Excel 2007 does
// for conditional formatting). Otherwise it will apparently not be picked up in conditional
// formatting style dialog
if ($pFont->getBold() !== null) {
$objWriter->startElement('b');
$objWriter->writeAttribute('val', $pFont->getBold() ? '1' : '0');
$objWriter->endElement();
}
// Italic
if ($pFont->getItalic() !== null) {
$objWriter->startElement('i');
$objWriter->writeAttribute('val', $pFont->getItalic() ? '1' : '0');
$objWriter->endElement();
}
// Strikethrough
if ($pFont->getStrikethrough() !== null) {
$objWriter->startElement('strike');
$objWriter->writeAttribute('val', $pFont->getStrikethrough() ? '1' : '0');
$objWriter->endElement();
}
// Underline
if ($pFont->getUnderline() !== null) {
$objWriter->startElement('u');
$objWriter->writeAttribute('val', $pFont->getUnderline());
$objWriter->endElement();
}
// Superscript / subscript
if ($pFont->getSuperscript() === true || $pFont->getSubscript() === true) {
$objWriter->startElement('vertAlign');
if ($pFont->getSuperscript() === true) {
$objWriter->writeAttribute('val', 'superscript');
} elseif ($pFont->getSubscript() === true) {
$objWriter->writeAttribute('val', 'subscript');
}
$objWriter->endElement();
}
// Size
if ($pFont->getSize() !== null) {
$objWriter->startElement('sz');
$objWriter->writeAttribute('val', StringHelper::formatNumber($pFont->getSize()));
$objWriter->endElement();
}
// Foreground color
if ($pFont->getColor()->getARGB() !== null) {
$objWriter->startElement('color');
$objWriter->writeAttribute('rgb', $pFont->getColor()->getARGB());
$objWriter->endElement();
}
// Name
if ($pFont->getName() !== null) {
$objWriter->startElement('name');
$objWriter->writeAttribute('val', $pFont->getName());
$objWriter->endElement();
}
$objWriter->endElement();
}
/**
* Write Border.
*
* @param XMLWriter $objWriter XML Writer
* @param Borders $pBorders Borders style
*/
private function writeBorder(XMLWriter $objWriter, Borders $pBorders): void
{
// Write border
$objWriter->startElement('border');
// Diagonal?
switch ($pBorders->getDiagonalDirection()) {
case Borders::DIAGONAL_UP:
$objWriter->writeAttribute('diagonalUp', 'true');
$objWriter->writeAttribute('diagonalDown', 'false');
break;
case Borders::DIAGONAL_DOWN:
$objWriter->writeAttribute('diagonalUp', 'false');
$objWriter->writeAttribute('diagonalDown', 'true');
break;
case Borders::DIAGONAL_BOTH:
$objWriter->writeAttribute('diagonalUp', 'true');
$objWriter->writeAttribute('diagonalDown', 'true');
break;
}
// BorderPr
$this->writeBorderPr($objWriter, 'left', $pBorders->getLeft());
$this->writeBorderPr($objWriter, 'right', $pBorders->getRight());
$this->writeBorderPr($objWriter, 'top', $pBorders->getTop());
$this->writeBorderPr($objWriter, 'bottom', $pBorders->getBottom());
$this->writeBorderPr($objWriter, 'diagonal', $pBorders->getDiagonal());
$objWriter->endElement();
}
/**
* Write Cell Style Xf.
*
* @param XMLWriter $objWriter XML Writer
* @param \PhpOffice\PhpSpreadsheet\Style\Style $pStyle Style
* @param Spreadsheet $spreadsheet Workbook
*/
private function writeCellStyleXf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $pStyle, Spreadsheet $spreadsheet): void
{
// xf
$objWriter->startElement('xf');
$objWriter->writeAttribute('xfId', 0);
$objWriter->writeAttribute('fontId', (int) $this->getParentWriter()->getFontHashTable()->getIndexForHashCode($pStyle->getFont()->getHashCode()));
if ($pStyle->getQuotePrefix()) {
$objWriter->writeAttribute('quotePrefix', 1);
}
if ($pStyle->getNumberFormat()->getBuiltInFormatCode() === false) {
$objWriter->writeAttribute('numFmtId', (int) ($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($pStyle->getNumberFormat()->getHashCode()) + 164));
} else {
$objWriter->writeAttribute('numFmtId', (int) $pStyle->getNumberFormat()->getBuiltInFormatCode());
}
$objWriter->writeAttribute('fillId', (int) $this->getParentWriter()->getFillHashTable()->getIndexForHashCode($pStyle->getFill()->getHashCode()));
$objWriter->writeAttribute('borderId', (int) $this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($pStyle->getBorders()->getHashCode()));
// Apply styles?
$objWriter->writeAttribute('applyFont', ($spreadsheet->getDefaultStyle()->getFont()->getHashCode() != $pStyle->getFont()->getHashCode()) ? '1' : '0');
$objWriter->writeAttribute('applyNumberFormat', ($spreadsheet->getDefaultStyle()->getNumberFormat()->getHashCode() != $pStyle->getNumberFormat()->getHashCode()) ? '1' : '0');
$objWriter->writeAttribute('applyFill', ($spreadsheet->getDefaultStyle()->getFill()->getHashCode() != $pStyle->getFill()->getHashCode()) ? '1' : '0');
$objWriter->writeAttribute('applyBorder', ($spreadsheet->getDefaultStyle()->getBorders()->getHashCode() != $pStyle->getBorders()->getHashCode()) ? '1' : '0');
$objWriter->writeAttribute('applyAlignment', ($spreadsheet->getDefaultStyle()->getAlignment()->getHashCode() != $pStyle->getAlignment()->getHashCode()) ? '1' : '0');
if ($pStyle->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) {
$objWriter->writeAttribute('applyProtection', 'true');
}
// alignment
$objWriter->startElement('alignment');
$objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal());
$objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical());
$textRotation = 0;
if ($pStyle->getAlignment()->getTextRotation() >= 0) {
$textRotation = $pStyle->getAlignment()->getTextRotation();
} elseif ($pStyle->getAlignment()->getTextRotation() < 0) {
$textRotation = 90 - $pStyle->getAlignment()->getTextRotation();
}
$objWriter->writeAttribute('textRotation', $textRotation);
$objWriter->writeAttribute('wrapText', ($pStyle->getAlignment()->getWrapText() ? 'true' : 'false'));
$objWriter->writeAttribute('shrinkToFit', ($pStyle->getAlignment()->getShrinkToFit() ? 'true' : 'false'));
if ($pStyle->getAlignment()->getIndent() > 0) {
$objWriter->writeAttribute('indent', $pStyle->getAlignment()->getIndent());
}
if ($pStyle->getAlignment()->getReadOrder() > 0) {
$objWriter->writeAttribute('readingOrder', $pStyle->getAlignment()->getReadOrder());
}
$objWriter->endElement();
// protection
if ($pStyle->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) {
$objWriter->startElement('protection');
if ($pStyle->getProtection()->getLocked() != Protection::PROTECTION_INHERIT) {
$objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
}
if ($pStyle->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) {
$objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
}
$objWriter->endElement();
}
$objWriter->endElement();
}
/**
* Write Cell Style Dxf.
*
* @param XMLWriter $objWriter XML Writer
* @param \PhpOffice\PhpSpreadsheet\Style\Style $pStyle Style
*/
private function writeCellStyleDxf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $pStyle): void
{
// dxf
$objWriter->startElement('dxf');
// font
$this->writeFont($objWriter, $pStyle->getFont());
// numFmt
$this->writeNumFmt($objWriter, $pStyle->getNumberFormat());
// fill
$this->writeFill($objWriter, $pStyle->getFill());
// alignment
$objWriter->startElement('alignment');
if ($pStyle->getAlignment()->getHorizontal() !== null) {
$objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal());
}
if ($pStyle->getAlignment()->getVertical() !== null) {
$objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical());
}
if ($pStyle->getAlignment()->getTextRotation() !== null) {
$textRotation = 0;
if ($pStyle->getAlignment()->getTextRotation() >= 0) {
$textRotation = $pStyle->getAlignment()->getTextRotation();
} elseif ($pStyle->getAlignment()->getTextRotation() < 0) {
$textRotation = 90 - $pStyle->getAlignment()->getTextRotation();
}
$objWriter->writeAttribute('textRotation', $textRotation);
}
$objWriter->endElement();
// border
$this->writeBorder($objWriter, $pStyle->getBorders());
// protection
if (($pStyle->getProtection()->getLocked() !== null) || ($pStyle->getProtection()->getHidden() !== null)) {
if (
$pStyle->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT ||
$pStyle->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT
) {
$objWriter->startElement('protection');
if (
($pStyle->getProtection()->getLocked() !== null) &&
($pStyle->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT)
) {
$objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
}
if (
($pStyle->getProtection()->getHidden() !== null) &&
($pStyle->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT)
) {
$objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
}
$objWriter->endElement();
}
}
$objWriter->endElement();
}
/**
* Write BorderPr.
*
* @param XMLWriter $objWriter XML Writer
* @param string $pName Element name
* @param Border $pBorder Border style
*/
private function writeBorderPr(XMLWriter $objWriter, $pName, Border $pBorder): void
{
// Write BorderPr
if ($pBorder->getBorderStyle() != Border::BORDER_NONE) {
$objWriter->startElement($pName);
$objWriter->writeAttribute('style', $pBorder->getBorderStyle());
// color
$objWriter->startElement('color');
$objWriter->writeAttribute('rgb', $pBorder->getColor()->getARGB());
$objWriter->endElement();
$objWriter->endElement();
}
}
/**
* Write NumberFormat.
*
* @param XMLWriter $objWriter XML Writer
* @param NumberFormat $pNumberFormat Number Format
* @param int $pId Number Format identifier
*/
private function writeNumFmt(XMLWriter $objWriter, NumberFormat $pNumberFormat, $pId = 0): void
{
// Translate formatcode
$formatCode = $pNumberFormat->getFormatCode();
// numFmt
if ($formatCode !== null) {
$objWriter->startElement('numFmt');
$objWriter->writeAttribute('numFmtId', ($pId + 164));
$objWriter->writeAttribute('formatCode', $formatCode);
$objWriter->endElement();
}
}
/**
* Get an array of all styles.
*
* @return \PhpOffice\PhpSpreadsheet\Style\Style[] All styles in PhpSpreadsheet
*/
public function allStyles(Spreadsheet $spreadsheet)
{
return $spreadsheet->getCellXfCollection();
}
/**
* Get an array of all conditional styles.
*
* @return Conditional[] All conditional styles in PhpSpreadsheet
*/
public function allConditionalStyles(Spreadsheet $spreadsheet)
{
// Get an array of all styles
$aStyles = [];
$sheetCount = $spreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
foreach ($spreadsheet->getSheet($i)->getConditionalStylesCollection() as $conditionalStyles) {
foreach ($conditionalStyles as $conditionalStyle) {
$aStyles[] = $conditionalStyle;
}
}
}
return $aStyles;
}
/**
* Get an array of all fills.
*
* @return Fill[] All fills in PhpSpreadsheet
*/
public function allFills(Spreadsheet $spreadsheet)
{
// Get an array of unique fills
$aFills = [];
// Two first fills are predefined
$fill0 = new Fill();
$fill0->setFillType(Fill::FILL_NONE);
$aFills[] = $fill0;
$fill1 = new Fill();
$fill1->setFillType(Fill::FILL_PATTERN_GRAY125);
$aFills[] = $fill1;
// The remaining fills
$aStyles = $this->allStyles($spreadsheet);
/** @var \PhpOffice\PhpSpreadsheet\Style\Style $style */
foreach ($aStyles as $style) {
if (!isset($aFills[$style->getFill()->getHashCode()])) {
$aFills[$style->getFill()->getHashCode()] = $style->getFill();
}
}
return $aFills;
}
/**
* Get an array of all fonts.
*
* @return Font[] All fonts in PhpSpreadsheet
*/
public function allFonts(Spreadsheet $spreadsheet)
{
// Get an array of unique fonts
$aFonts = [];
$aStyles = $this->allStyles($spreadsheet);
/** @var \PhpOffice\PhpSpreadsheet\Style\Style $style */
foreach ($aStyles as $style) {
if (!isset($aFonts[$style->getFont()->getHashCode()])) {
$aFonts[$style->getFont()->getHashCode()] = $style->getFont();
}
}
return $aFonts;
}
/**
* Get an array of all borders.
*
* @return Borders[] All borders in PhpSpreadsheet
*/
public function allBorders(Spreadsheet $spreadsheet)
{
// Get an array of unique borders
$aBorders = [];
$aStyles = $this->allStyles($spreadsheet);
/** @var \PhpOffice\PhpSpreadsheet\Style\Style $style */
foreach ($aStyles as $style) {
if (!isset($aBorders[$style->getBorders()->getHashCode()])) {
$aBorders[$style->getBorders()->getHashCode()] = $style->getBorders();
}
}
return $aBorders;
}
/**
* Get an array of all number formats.
*
* @return NumberFormat[] All number formats in PhpSpreadsheet
*/
public function allNumberFormats(Spreadsheet $spreadsheet)
{
// Get an array of unique number formats
$aNumFmts = [];
$aStyles = $this->allStyles($spreadsheet);
/** @var \PhpOffice\PhpSpreadsheet\Style\Style $style */
foreach ($aStyles as $style) {
if ($style->getNumberFormat()->getBuiltInFormatCode() === false && !isset($aNumFmts[$style->getNumberFormat()->getHashCode()])) {
$aNumFmts[$style->getNumberFormat()->getHashCode()] = $style->getNumberFormat();
}
}
return $aNumFmts;
}
}

View File

@@ -0,0 +1,837 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Theme extends WriterPart
{
/**
* Map of Major fonts to write.
*
* @var array of string
*/
private static $majorFonts = [
'Jpan' => ' Pゴシック',
'Hang' => '맑은 고딕',
'Hans' => '宋体',
'Hant' => '新細明體',
'Arab' => 'Times New Roman',
'Hebr' => 'Times New Roman',
'Thai' => 'Tahoma',
'Ethi' => 'Nyala',
'Beng' => 'Vrinda',
'Gujr' => 'Shruti',
'Khmr' => 'MoolBoran',
'Knda' => 'Tunga',
'Guru' => 'Raavi',
'Cans' => 'Euphemia',
'Cher' => 'Plantagenet Cherokee',
'Yiii' => 'Microsoft Yi Baiti',
'Tibt' => 'Microsoft Himalaya',
'Thaa' => 'MV Boli',
'Deva' => 'Mangal',
'Telu' => 'Gautami',
'Taml' => 'Latha',
'Syrc' => 'Estrangelo Edessa',
'Orya' => 'Kalinga',
'Mlym' => 'Kartika',
'Laoo' => 'DokChampa',
'Sinh' => 'Iskoola Pota',
'Mong' => 'Mongolian Baiti',
'Viet' => 'Times New Roman',
'Uigh' => 'Microsoft Uighur',
'Geor' => 'Sylfaen',
];
/**
* Map of Minor fonts to write.
*
* @var array of string
*/
private static $minorFonts = [
'Jpan' => ' Pゴシック',
'Hang' => '맑은 고딕',
'Hans' => '宋体',
'Hant' => '新細明體',
'Arab' => 'Arial',
'Hebr' => 'Arial',
'Thai' => 'Tahoma',
'Ethi' => 'Nyala',
'Beng' => 'Vrinda',
'Gujr' => 'Shruti',
'Khmr' => 'DaunPenh',
'Knda' => 'Tunga',
'Guru' => 'Raavi',
'Cans' => 'Euphemia',
'Cher' => 'Plantagenet Cherokee',
'Yiii' => 'Microsoft Yi Baiti',
'Tibt' => 'Microsoft Himalaya',
'Thaa' => 'MV Boli',
'Deva' => 'Mangal',
'Telu' => 'Gautami',
'Taml' => 'Latha',
'Syrc' => 'Estrangelo Edessa',
'Orya' => 'Kalinga',
'Mlym' => 'Kartika',
'Laoo' => 'DokChampa',
'Sinh' => 'Iskoola Pota',
'Mong' => 'Mongolian Baiti',
'Viet' => 'Arial',
'Uigh' => 'Microsoft Uighur',
'Geor' => 'Sylfaen',
];
/**
* Map of core colours.
*
* @var array of string
*/
private static $colourScheme = [
'dk2' => '1F497D',
'lt2' => 'EEECE1',
'accent1' => '4F81BD',
'accent2' => 'C0504D',
'accent3' => '9BBB59',
'accent4' => '8064A2',
'accent5' => '4BACC6',
'accent6' => 'F79646',
'hlink' => '0000FF',
'folHlink' => '800080',
];
/**
* Write theme to XML format.
*
* @return string XML Output
*/
public function writeTheme(Spreadsheet $spreadsheet)
{
// Create XML writer
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// a:theme
$objWriter->startElement('a:theme');
$objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
$objWriter->writeAttribute('name', 'Office Theme');
// a:themeElements
$objWriter->startElement('a:themeElements');
// a:clrScheme
$objWriter->startElement('a:clrScheme');
$objWriter->writeAttribute('name', 'Office');
// a:dk1
$objWriter->startElement('a:dk1');
// a:sysClr
$objWriter->startElement('a:sysClr');
$objWriter->writeAttribute('val', 'windowText');
$objWriter->writeAttribute('lastClr', '000000');
$objWriter->endElement();
$objWriter->endElement();
// a:lt1
$objWriter->startElement('a:lt1');
// a:sysClr
$objWriter->startElement('a:sysClr');
$objWriter->writeAttribute('val', 'window');
$objWriter->writeAttribute('lastClr', 'FFFFFF');
$objWriter->endElement();
$objWriter->endElement();
// a:dk2
$this->writeColourScheme($objWriter);
$objWriter->endElement();
// a:fontScheme
$objWriter->startElement('a:fontScheme');
$objWriter->writeAttribute('name', 'Office');
// a:majorFont
$objWriter->startElement('a:majorFont');
$this->writeFonts($objWriter, 'Cambria', self::$majorFonts);
$objWriter->endElement();
// a:minorFont
$objWriter->startElement('a:minorFont');
$this->writeFonts($objWriter, 'Calibri', self::$minorFonts);
$objWriter->endElement();
$objWriter->endElement();
// a:fmtScheme
$objWriter->startElement('a:fmtScheme');
$objWriter->writeAttribute('name', 'Office');
// a:fillStyleLst
$objWriter->startElement('a:fillStyleLst');
// a:solidFill
$objWriter->startElement('a:solidFill');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
$objWriter->endElement();
$objWriter->endElement();
// a:gradFill
$objWriter->startElement('a:gradFill');
$objWriter->writeAttribute('rotWithShape', '1');
// a:gsLst
$objWriter->startElement('a:gsLst');
// a:gs
$objWriter->startElement('a:gs');
$objWriter->writeAttribute('pos', '0');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
// a:tint
$objWriter->startElement('a:tint');
$objWriter->writeAttribute('val', '50000');
$objWriter->endElement();
// a:satMod
$objWriter->startElement('a:satMod');
$objWriter->writeAttribute('val', '300000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:gs
$objWriter->startElement('a:gs');
$objWriter->writeAttribute('pos', '35000');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
// a:tint
$objWriter->startElement('a:tint');
$objWriter->writeAttribute('val', '37000');
$objWriter->endElement();
// a:satMod
$objWriter->startElement('a:satMod');
$objWriter->writeAttribute('val', '300000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:gs
$objWriter->startElement('a:gs');
$objWriter->writeAttribute('pos', '100000');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
// a:tint
$objWriter->startElement('a:tint');
$objWriter->writeAttribute('val', '15000');
$objWriter->endElement();
// a:satMod
$objWriter->startElement('a:satMod');
$objWriter->writeAttribute('val', '350000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:lin
$objWriter->startElement('a:lin');
$objWriter->writeAttribute('ang', '16200000');
$objWriter->writeAttribute('scaled', '1');
$objWriter->endElement();
$objWriter->endElement();
// a:gradFill
$objWriter->startElement('a:gradFill');
$objWriter->writeAttribute('rotWithShape', '1');
// a:gsLst
$objWriter->startElement('a:gsLst');
// a:gs
$objWriter->startElement('a:gs');
$objWriter->writeAttribute('pos', '0');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
// a:shade
$objWriter->startElement('a:shade');
$objWriter->writeAttribute('val', '51000');
$objWriter->endElement();
// a:satMod
$objWriter->startElement('a:satMod');
$objWriter->writeAttribute('val', '130000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:gs
$objWriter->startElement('a:gs');
$objWriter->writeAttribute('pos', '80000');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
// a:shade
$objWriter->startElement('a:shade');
$objWriter->writeAttribute('val', '93000');
$objWriter->endElement();
// a:satMod
$objWriter->startElement('a:satMod');
$objWriter->writeAttribute('val', '130000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:gs
$objWriter->startElement('a:gs');
$objWriter->writeAttribute('pos', '100000');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
// a:shade
$objWriter->startElement('a:shade');
$objWriter->writeAttribute('val', '94000');
$objWriter->endElement();
// a:satMod
$objWriter->startElement('a:satMod');
$objWriter->writeAttribute('val', '135000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:lin
$objWriter->startElement('a:lin');
$objWriter->writeAttribute('ang', '16200000');
$objWriter->writeAttribute('scaled', '0');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:lnStyleLst
$objWriter->startElement('a:lnStyleLst');
// a:ln
$objWriter->startElement('a:ln');
$objWriter->writeAttribute('w', '9525');
$objWriter->writeAttribute('cap', 'flat');
$objWriter->writeAttribute('cmpd', 'sng');
$objWriter->writeAttribute('algn', 'ctr');
// a:solidFill
$objWriter->startElement('a:solidFill');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
// a:shade
$objWriter->startElement('a:shade');
$objWriter->writeAttribute('val', '95000');
$objWriter->endElement();
// a:satMod
$objWriter->startElement('a:satMod');
$objWriter->writeAttribute('val', '105000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:prstDash
$objWriter->startElement('a:prstDash');
$objWriter->writeAttribute('val', 'solid');
$objWriter->endElement();
$objWriter->endElement();
// a:ln
$objWriter->startElement('a:ln');
$objWriter->writeAttribute('w', '25400');
$objWriter->writeAttribute('cap', 'flat');
$objWriter->writeAttribute('cmpd', 'sng');
$objWriter->writeAttribute('algn', 'ctr');
// a:solidFill
$objWriter->startElement('a:solidFill');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
$objWriter->endElement();
$objWriter->endElement();
// a:prstDash
$objWriter->startElement('a:prstDash');
$objWriter->writeAttribute('val', 'solid');
$objWriter->endElement();
$objWriter->endElement();
// a:ln
$objWriter->startElement('a:ln');
$objWriter->writeAttribute('w', '38100');
$objWriter->writeAttribute('cap', 'flat');
$objWriter->writeAttribute('cmpd', 'sng');
$objWriter->writeAttribute('algn', 'ctr');
// a:solidFill
$objWriter->startElement('a:solidFill');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
$objWriter->endElement();
$objWriter->endElement();
// a:prstDash
$objWriter->startElement('a:prstDash');
$objWriter->writeAttribute('val', 'solid');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:effectStyleLst
$objWriter->startElement('a:effectStyleLst');
// a:effectStyle
$objWriter->startElement('a:effectStyle');
// a:effectLst
$objWriter->startElement('a:effectLst');
// a:outerShdw
$objWriter->startElement('a:outerShdw');
$objWriter->writeAttribute('blurRad', '40000');
$objWriter->writeAttribute('dist', '20000');
$objWriter->writeAttribute('dir', '5400000');
$objWriter->writeAttribute('rotWithShape', '0');
// a:srgbClr
$objWriter->startElement('a:srgbClr');
$objWriter->writeAttribute('val', '000000');
// a:alpha
$objWriter->startElement('a:alpha');
$objWriter->writeAttribute('val', '38000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:effectStyle
$objWriter->startElement('a:effectStyle');
// a:effectLst
$objWriter->startElement('a:effectLst');
// a:outerShdw
$objWriter->startElement('a:outerShdw');
$objWriter->writeAttribute('blurRad', '40000');
$objWriter->writeAttribute('dist', '23000');
$objWriter->writeAttribute('dir', '5400000');
$objWriter->writeAttribute('rotWithShape', '0');
// a:srgbClr
$objWriter->startElement('a:srgbClr');
$objWriter->writeAttribute('val', '000000');
// a:alpha
$objWriter->startElement('a:alpha');
$objWriter->writeAttribute('val', '35000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:effectStyle
$objWriter->startElement('a:effectStyle');
// a:effectLst
$objWriter->startElement('a:effectLst');
// a:outerShdw
$objWriter->startElement('a:outerShdw');
$objWriter->writeAttribute('blurRad', '40000');
$objWriter->writeAttribute('dist', '23000');
$objWriter->writeAttribute('dir', '5400000');
$objWriter->writeAttribute('rotWithShape', '0');
// a:srgbClr
$objWriter->startElement('a:srgbClr');
$objWriter->writeAttribute('val', '000000');
// a:alpha
$objWriter->startElement('a:alpha');
$objWriter->writeAttribute('val', '35000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:scene3d
$objWriter->startElement('a:scene3d');
// a:camera
$objWriter->startElement('a:camera');
$objWriter->writeAttribute('prst', 'orthographicFront');
// a:rot
$objWriter->startElement('a:rot');
$objWriter->writeAttribute('lat', '0');
$objWriter->writeAttribute('lon', '0');
$objWriter->writeAttribute('rev', '0');
$objWriter->endElement();
$objWriter->endElement();
// a:lightRig
$objWriter->startElement('a:lightRig');
$objWriter->writeAttribute('rig', 'threePt');
$objWriter->writeAttribute('dir', 't');
// a:rot
$objWriter->startElement('a:rot');
$objWriter->writeAttribute('lat', '0');
$objWriter->writeAttribute('lon', '0');
$objWriter->writeAttribute('rev', '1200000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:sp3d
$objWriter->startElement('a:sp3d');
// a:bevelT
$objWriter->startElement('a:bevelT');
$objWriter->writeAttribute('w', '63500');
$objWriter->writeAttribute('h', '25400');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:bgFillStyleLst
$objWriter->startElement('a:bgFillStyleLst');
// a:solidFill
$objWriter->startElement('a:solidFill');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
$objWriter->endElement();
$objWriter->endElement();
// a:gradFill
$objWriter->startElement('a:gradFill');
$objWriter->writeAttribute('rotWithShape', '1');
// a:gsLst
$objWriter->startElement('a:gsLst');
// a:gs
$objWriter->startElement('a:gs');
$objWriter->writeAttribute('pos', '0');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
// a:tint
$objWriter->startElement('a:tint');
$objWriter->writeAttribute('val', '40000');
$objWriter->endElement();
// a:satMod
$objWriter->startElement('a:satMod');
$objWriter->writeAttribute('val', '350000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:gs
$objWriter->startElement('a:gs');
$objWriter->writeAttribute('pos', '40000');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
// a:tint
$objWriter->startElement('a:tint');
$objWriter->writeAttribute('val', '45000');
$objWriter->endElement();
// a:shade
$objWriter->startElement('a:shade');
$objWriter->writeAttribute('val', '99000');
$objWriter->endElement();
// a:satMod
$objWriter->startElement('a:satMod');
$objWriter->writeAttribute('val', '350000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:gs
$objWriter->startElement('a:gs');
$objWriter->writeAttribute('pos', '100000');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
// a:shade
$objWriter->startElement('a:shade');
$objWriter->writeAttribute('val', '20000');
$objWriter->endElement();
// a:satMod
$objWriter->startElement('a:satMod');
$objWriter->writeAttribute('val', '255000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:path
$objWriter->startElement('a:path');
$objWriter->writeAttribute('path', 'circle');
// a:fillToRect
$objWriter->startElement('a:fillToRect');
$objWriter->writeAttribute('l', '50000');
$objWriter->writeAttribute('t', '-80000');
$objWriter->writeAttribute('r', '50000');
$objWriter->writeAttribute('b', '180000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:gradFill
$objWriter->startElement('a:gradFill');
$objWriter->writeAttribute('rotWithShape', '1');
// a:gsLst
$objWriter->startElement('a:gsLst');
// a:gs
$objWriter->startElement('a:gs');
$objWriter->writeAttribute('pos', '0');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
// a:tint
$objWriter->startElement('a:tint');
$objWriter->writeAttribute('val', '80000');
$objWriter->endElement();
// a:satMod
$objWriter->startElement('a:satMod');
$objWriter->writeAttribute('val', '300000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:gs
$objWriter->startElement('a:gs');
$objWriter->writeAttribute('pos', '100000');
// a:schemeClr
$objWriter->startElement('a:schemeClr');
$objWriter->writeAttribute('val', 'phClr');
// a:shade
$objWriter->startElement('a:shade');
$objWriter->writeAttribute('val', '30000');
$objWriter->endElement();
// a:satMod
$objWriter->startElement('a:satMod');
$objWriter->writeAttribute('val', '200000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:path
$objWriter->startElement('a:path');
$objWriter->writeAttribute('path', 'circle');
// a:fillToRect
$objWriter->startElement('a:fillToRect');
$objWriter->writeAttribute('l', '50000');
$objWriter->writeAttribute('t', '50000');
$objWriter->writeAttribute('r', '50000');
$objWriter->writeAttribute('b', '50000');
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// a:objectDefaults
$objWriter->writeElement('a:objectDefaults', null);
// a:extraClrSchemeLst
$objWriter->writeElement('a:extraClrSchemeLst', null);
$objWriter->endElement();
// Return
return $objWriter->getData();
}
/**
* Write fonts to XML format.
*
* @param XMLWriter $objWriter
* @param string $latinFont
* @param array of string $fontSet
*
* @return string XML Output
*/
private function writeFonts($objWriter, $latinFont, $fontSet)
{
// a:latin
$objWriter->startElement('a:latin');
$objWriter->writeAttribute('typeface', $latinFont);
$objWriter->endElement();
// a:ea
$objWriter->startElement('a:ea');
$objWriter->writeAttribute('typeface', '');
$objWriter->endElement();
// a:cs
$objWriter->startElement('a:cs');
$objWriter->writeAttribute('typeface', '');
$objWriter->endElement();
foreach ($fontSet as $fontScript => $typeface) {
$objWriter->startElement('a:font');
$objWriter->writeAttribute('script', $fontScript);
$objWriter->writeAttribute('typeface', $typeface);
$objWriter->endElement();
}
}
/**
* Write colour scheme to XML format.
*
* @param XMLWriter $objWriter
*
* @return string XML Output
*/
private function writeColourScheme($objWriter)
{
foreach (self::$colourScheme as $colourName => $colourValue) {
$objWriter->startElement('a:' . $colourName);
$objWriter->startElement('a:srgbClr');
$objWriter->writeAttribute('val', $colourValue);
$objWriter->endElement();
$objWriter->endElement();
}
}
}

View File

@@ -0,0 +1,225 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\DefinedNames as DefinedNamesWriter;
class Workbook extends WriterPart
{
/**
* Write workbook to XML format.
*
* @param bool $recalcRequired Indicate whether formulas should be recalculated before writing
*
* @return string XML Output
*/
public function writeWorkbook(Spreadsheet $spreadsheet, $recalcRequired = false)
{
// Create XML writer
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
$objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY);
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// workbook
$objWriter->startElement('workbook');
$objWriter->writeAttribute('xml:space', 'preserve');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
$objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
// fileVersion
$this->writeFileVersion($objWriter);
// workbookPr
$this->writeWorkbookPr($objWriter);
// workbookProtection
$this->writeWorkbookProtection($objWriter, $spreadsheet);
// bookViews
if ($this->getParentWriter()->getOffice2003Compatibility() === false) {
$this->writeBookViews($objWriter, $spreadsheet);
}
// sheets
$this->writeSheets($objWriter, $spreadsheet);
// definedNames
(new DefinedNamesWriter($objWriter, $spreadsheet))->write();
// calcPr
$this->writeCalcPr($objWriter, $recalcRequired);
$objWriter->endElement();
// Return
return $objWriter->getData();
}
/**
* Write file version.
*
* @param XMLWriter $objWriter XML Writer
*/
private function writeFileVersion(XMLWriter $objWriter): void
{
$objWriter->startElement('fileVersion');
$objWriter->writeAttribute('appName', 'xl');
$objWriter->writeAttribute('lastEdited', '4');
$objWriter->writeAttribute('lowestEdited', '4');
$objWriter->writeAttribute('rupBuild', '4505');
$objWriter->endElement();
}
/**
* Write WorkbookPr.
*
* @param XMLWriter $objWriter XML Writer
*/
private function writeWorkbookPr(XMLWriter $objWriter): void
{
$objWriter->startElement('workbookPr');
if (Date::getExcelCalendar() === Date::CALENDAR_MAC_1904) {
$objWriter->writeAttribute('date1904', '1');
}
$objWriter->writeAttribute('codeName', 'ThisWorkbook');
$objWriter->endElement();
}
/**
* Write BookViews.
*
* @param XMLWriter $objWriter XML Writer
*/
private function writeBookViews(XMLWriter $objWriter, Spreadsheet $spreadsheet): void
{
// bookViews
$objWriter->startElement('bookViews');
// workbookView
$objWriter->startElement('workbookView');
$objWriter->writeAttribute('activeTab', $spreadsheet->getActiveSheetIndex());
$objWriter->writeAttribute('autoFilterDateGrouping', ($spreadsheet->getAutoFilterDateGrouping() ? 'true' : 'false'));
$objWriter->writeAttribute('firstSheet', $spreadsheet->getFirstSheetIndex());
$objWriter->writeAttribute('minimized', ($spreadsheet->getMinimized() ? 'true' : 'false'));
$objWriter->writeAttribute('showHorizontalScroll', ($spreadsheet->getShowHorizontalScroll() ? 'true' : 'false'));
$objWriter->writeAttribute('showSheetTabs', ($spreadsheet->getShowSheetTabs() ? 'true' : 'false'));
$objWriter->writeAttribute('showVerticalScroll', ($spreadsheet->getShowVerticalScroll() ? 'true' : 'false'));
$objWriter->writeAttribute('tabRatio', $spreadsheet->getTabRatio());
$objWriter->writeAttribute('visibility', $spreadsheet->getVisibility());
$objWriter->endElement();
$objWriter->endElement();
}
/**
* Write WorkbookProtection.
*
* @param XMLWriter $objWriter XML Writer
*/
private function writeWorkbookProtection(XMLWriter $objWriter, Spreadsheet $spreadsheet): void
{
if ($spreadsheet->getSecurity()->isSecurityEnabled()) {
$objWriter->startElement('workbookProtection');
$objWriter->writeAttribute('lockRevision', ($spreadsheet->getSecurity()->getLockRevision() ? 'true' : 'false'));
$objWriter->writeAttribute('lockStructure', ($spreadsheet->getSecurity()->getLockStructure() ? 'true' : 'false'));
$objWriter->writeAttribute('lockWindows', ($spreadsheet->getSecurity()->getLockWindows() ? 'true' : 'false'));
if ($spreadsheet->getSecurity()->getRevisionsPassword() != '') {
$objWriter->writeAttribute('revisionsPassword', $spreadsheet->getSecurity()->getRevisionsPassword());
}
if ($spreadsheet->getSecurity()->getWorkbookPassword() != '') {
$objWriter->writeAttribute('workbookPassword', $spreadsheet->getSecurity()->getWorkbookPassword());
}
$objWriter->endElement();
}
}
/**
* Write calcPr.
*
* @param XMLWriter $objWriter XML Writer
* @param bool $recalcRequired Indicate whether formulas should be recalculated before writing
*/
private function writeCalcPr(XMLWriter $objWriter, $recalcRequired = true): void
{
$objWriter->startElement('calcPr');
// Set the calcid to a higher value than Excel itself will use, otherwise Excel will always recalc
// If MS Excel does do a recalc, then users opening a file in MS Excel will be prompted to save on exit
// because the file has changed
$objWriter->writeAttribute('calcId', '999999');
$objWriter->writeAttribute('calcMode', 'auto');
// fullCalcOnLoad isn't needed if we've recalculating for the save
$objWriter->writeAttribute('calcCompleted', ($recalcRequired) ? 1 : 0);
$objWriter->writeAttribute('fullCalcOnLoad', ($recalcRequired) ? 0 : 1);
$objWriter->writeAttribute('forceFullCalc', ($recalcRequired) ? 0 : 1);
$objWriter->endElement();
}
/**
* Write sheets.
*
* @param XMLWriter $objWriter XML Writer
*/
private function writeSheets(XMLWriter $objWriter, Spreadsheet $spreadsheet): void
{
// Write sheets
$objWriter->startElement('sheets');
$sheetCount = $spreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
// sheet
$this->writeSheet(
$objWriter,
$spreadsheet->getSheet($i)->getTitle(),
($i + 1),
($i + 1 + 3),
$spreadsheet->getSheet($i)->getSheetState()
);
}
$objWriter->endElement();
}
/**
* Write sheet.
*
* @param XMLWriter $objWriter XML Writer
* @param string $pSheetname Sheet name
* @param int $pSheetId Sheet id
* @param int $pRelId Relationship ID
* @param string $sheetState Sheet state (visible, hidden, veryHidden)
*/
private function writeSheet(XMLWriter $objWriter, $pSheetname, $pSheetId = 1, $pRelId = 1, $sheetState = 'visible'): void
{
if ($pSheetname != '') {
// Write sheet
$objWriter->startElement('sheet');
$objWriter->writeAttribute('name', $pSheetname);
$objWriter->writeAttribute('sheetId', $pSheetId);
if ($sheetState !== 'visible' && $sheetState != '') {
$objWriter->writeAttribute('state', $sheetState);
}
$objWriter->writeAttribute('r:id', 'rId' . $pRelId);
$objWriter->endElement();
} else {
throw new WriterException('Invalid parameters passed.');
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,33 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
abstract class WriterPart
{
/**
* Parent Xlsx object.
*
* @var Xlsx
*/
private $parentWriter;
/**
* Get parent Xlsx object.
*
* @return Xlsx
*/
public function getParentWriter()
{
return $this->parentWriter;
}
/**
* Set parent Xlsx object.
*/
public function __construct(Xlsx $pWriter)
{
$this->parentWriter = $pWriter;
}
}

View File

@@ -0,0 +1,159 @@
<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class Xlfn
{
const XLFNREGEXP = '/(?<!_xlfn[.])\\b('
// functions added with Excel 2010
. 'beta[.]dist'
. '|beta[.]inv'
. '|binom[.]dist'
. '|binom[.]inv'
. '|chisq[.]dist'
. '|chisq[.]dist[.]rt'
. '|chisq[.]inv'
. '|chisq[.]inv[.]rt'
. '|chisq[.]test'
. '|confidence[.]norm'
. '|confidence[.]t'
. '|covariance[.]p'
. '|covariance[.]s'
. '|erf[.]precise'
. '|erfc[.]precise'
. '|expon[.]dist'
. '|f[.]dist'
. '|f[.]dist[.]rt'
. '|f[.]inv'
. '|f[.]inv[.]rt'
. '|f[.]test'
. '|gamma[.]dist'
. '|gamma[.]inv'
. '|gammaln[.]precise'
. '|lognorm[.]dist'
. '|lognorm[.]inv'
. '|mode[.]mult'
. '|mode[.]sngl'
. '|negbinom[.]dist'
. '|networkdays[.]intl'
. '|norm[.]dist'
. '|norm[.]inv'
. '|norm[.]s[.]dist'
. '|norm[.]s[.]inv'
. '|percentile[.]exc'
. '|percentile[.]inc'
. '|percentrank[.]exc'
. '|percentrank[.]inc'
. '|poisson[.]dist'
. '|quartile[.]exc'
. '|quartile[.]inc'
. '|rank[.]avg'
. '|rank[.]eq'
. '|stdev[.]p'
. '|stdev[.]s'
. '|t[.]dist'
. '|t[.]dist[.]2t'
. '|t[.]dist[.]rt'
. '|t[.]inv'
. '|t[.]inv[.]2t'
. '|t[.]test'
. '|var[.]p'
. '|var[.]s'
. '|weibull[.]dist'
. '|z[.]test'
// functions added with Excel 2013
. '|acot'
. '|acoth'
. '|arabic'
. '|averageifs'
. '|binom[.]dist[.]range'
. '|bitand'
. '|bitlshift'
. '|bitor'
. '|bitrshift'
. '|bitxor'
. '|ceiling[.]math'
. '|combina'
. '|cot'
. '|coth'
. '|csc'
. '|csch'
. '|days'
. '|dbcs'
. '|decimal'
. '|encodeurl'
. '|filterxml'
. '|floor[.]math'
. '|formulatext'
. '|gamma'
. '|gauss'
. '|ifna'
. '|imcosh'
. '|imcot'
. '|imcsc'
. '|imcsch'
. '|imsec'
. '|imsech'
. '|imsinh'
. '|imtan'
. '|isformula'
. '|iso[.]ceiling'
. '|isoweeknum'
. '|munit'
. '|numbervalue'
. '|pduration'
. '|permutationa'
. '|phi'
. '|rri'
. '|sec'
. '|sech'
. '|sheet'
. '|sheets'
. '|skew[.]p'
. '|unichar'
. '|unicode'
. '|webservice'
. '|xor'
// functions added with Excel 2016
. '|forecast[.]et2'
. '|forecast[.]ets[.]confint'
. '|forecast[.]ets[.]seasonality'
. '|forecast[.]ets[.]stat'
. '|forecast[.]linear'
. '|switch'
// functions added with Excel 2019
. '|concat'
. '|countifs'
. '|ifs'
. '|maxifs'
. '|minifs'
. '|sumifs'
. '|textjoin'
// functions added with Excel 365
. '|filter'
. '|randarray'
. '|sequence'
. '|sort'
. '|sortby'
. '|unique'
. '|xlookup'
. '|xmatch'
. ')(?=\\s*[(])/i';
/**
* Prefix function name in string with _xlfn. where required.
*/
public static function addXlfn(string $funcstring): string
{
return preg_replace(self::XLFNREGEXP, '_xlfn.$1', $funcstring);
}
/**
* Prefix function name in string with _xlfn. where required.
* Leading character, expected to be equals sign, is stripped.
*/
public static function addXlfnStripEquals(string $funcstring): string
{
return self::addXlfn(substr($funcstring, 1));
}
}