repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls/Worksheet.php | src/PhpSpreadsheet/Writer/Xls/Worksheet.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
use Composer\Pcre\Preg;
use GdImage;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\RichText\Run;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Shared\Xls;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Borders;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\Protection;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Worksheet\SheetView;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
// Original file header of PEAR::Spreadsheet_Excel_Writer_Worksheet (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 Worksheet extends BIFFwriter
{
private static int $always0 = 0;
private static int $always1 = 1;
/**
* Formula parser.
*/
private Parser $parser;
/**
* Array containing format information for columns.
*
* @var array<array{int, int, float, int, int, int}>
*/
private array $columnInfo;
/**
* The active pane for the worksheet.
*/
private int $activePane;
/**
* Whether to use outline.
*/
private bool $outlineOn;
/**
* Auto outline styles.
*/
private bool $outlineStyle;
/**
* Whether to have outline summary below.
* Not currently used.
*/
private bool $outlineBelow; //* @phpstan-ignore-line
/**
* Whether to have outline summary at the right.
* Not currently used.
*/
private bool $outlineRight; //* @phpstan-ignore-line
/**
* Reference to the total number of strings in the workbook.
*/
private int $stringTotal;
/**
* Reference to the number of unique strings in the workbook.
*/
private int $stringUnique;
/**
* Reference to the array containing all the unique strings in the workbook.
*
* @var array<string, int>
*/
private array $stringTable;
/**
* Color cache.
*
* @var mixed[]
*/
private array $colors;
/**
* Index of first used row (at least 0).
*/
private int $firstRowIndex;
/**
* Index of last used row. (no used rows means -1).
*/
private int $lastRowIndex;
/**
* Index of first used column (at least 0).
*/
private int $firstColumnIndex;
/**
* Index of last used column (no used columns means -1).
*/
private int $lastColumnIndex;
/**
* Sheet object.
*/
public \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet;
/**
* Escher object corresponding to MSODRAWING.
*/
private ?\PhpOffice\PhpSpreadsheet\Shared\Escher $escher = null;
/**
* Array of font hashes associated to FONT records index.
*
* @var array<int|string>
*/
public array $fontHashIndex;
private bool $preCalculateFormulas;
private int $printHeaders;
private ?Workbook $writerWorkbook;
/**
* Constructor.
*
* @param int $str_total Total number of strings
* @param int $str_unique Total number of unique strings
* @param array<string, int> $str_table String Table
* @param mixed[] $colors Colour Table
* @param Parser $parser The formula parser created for the Workbook
* @param bool $preCalculateFormulas Flag indicating whether formulas should be calculated or just written
* @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet The worksheet to write
*/
public function __construct(int &$str_total, int &$str_unique, array &$str_table, array &$colors, Parser $parser, bool $preCalculateFormulas, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet, ?Workbook $writerWorkbook = null)
{
// It needs to call its parent's constructor explicitly
parent::__construct();
$this->preCalculateFormulas = $preCalculateFormulas;
$this->stringTotal = &$str_total;
$this->stringUnique = &$str_unique;
$this->stringTable = &$str_table;
$this->colors = &$colors;
$this->parser = $parser;
$this->phpSheet = $phpSheet;
$this->columnInfo = [];
$this->activePane = 3;
$this->printHeaders = 0;
$this->outlineStyle = false;
$this->outlineBelow = true;
$this->outlineRight = true;
$this->outlineOn = true;
$this->fontHashIndex = [];
// calculate values for DIMENSIONS record
$minR = 1;
$minC = 'A';
$maxR = $this->phpSheet->getHighestRow();
$maxC = $this->phpSheet->getHighestColumn();
// Determine lowest and highest column and row
// BIFF8 DIMENSIONS record requires 0-based indices for both rows and columns
// Row methods return 1-based values (Excel UI), so subtract 1 to convert to 0-based
$this->firstRowIndex = $minR - 1;
$this->lastRowIndex = ($maxR > 65536) ? 65535 : ($maxR - 1);
// Column methods return 1-based values (columnIndexFromString('A') = 1), so subtract 1
$this->firstColumnIndex = Coordinate::columnIndexFromString($minC) - 1;
$this->lastColumnIndex = min(255, Coordinate::columnIndexFromString($maxC) - 1);
$this->writerWorkbook = $writerWorkbook;
}
/**
* Add data to the beginning of the workbook (note the reverse order)
* and to the end of the workbook.
*
* @see Workbook::storeWorkbook
*/
public function close(): void
{
$phpSheet = $this->phpSheet;
// Storing selected cells and active sheet because it changes while parsing cells with formulas.
$selectedCells = $this->phpSheet->getSelectedCells();
$activeSheetIndex = $this->phpSheet->getParentOrThrow()->getActiveSheetIndex();
// Write BOF record
$this->storeBof(0x0010);
// Write PRINTHEADERS
$this->writePrintHeaders();
// Write PRINTGRIDLINES
$this->writePrintGridlines();
// Write GRIDSET
$this->writeGridset();
// Calculate column widths
$phpSheet->calculateColumnWidths();
// Column dimensions
if (($defaultWidth = $phpSheet->getDefaultColumnDimension()->getWidth()) < 0) {
$defaultWidth = \PhpOffice\PhpSpreadsheet\Shared\Font::getDefaultColumnWidthByFont($phpSheet->getParentOrThrow()->getDefaultStyle()->getFont());
}
$columnDimensions = $phpSheet->getColumnDimensions();
// lastColumnIndex is now 0-based, so no need to subtract 1
$maxCol = $this->lastColumnIndex;
for ($i = 0; $i <= $maxCol; ++$i) {
$hidden = 0;
$level = 0;
$xfIndex = 15; // there are 15 cell style Xfs
$width = $defaultWidth;
$columnLetter = Coordinate::stringFromColumnIndex($i + 1);
if (isset($columnDimensions[$columnLetter])) {
$columnDimension = $columnDimensions[$columnLetter];
if ($columnDimension->getWidth() >= 0) {
$width = $columnDimension->getWidthForOutput(true);
}
$hidden = $columnDimension->getVisible() ? 0 : 1;
$level = $columnDimension->getOutlineLevel();
$xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs
}
// Components of columnInfo:
// $firstcol first column on the range
// $lastcol last column on the range
// $width width to set
// $xfIndex The optional cell style Xf index to apply to the columns
// $hidden The optional hidden attribute
// $level The optional outline level
$this->columnInfo[] = [$i, $i, $width, $xfIndex, $hidden, $level];
}
// Write GUTS
$this->writeGuts();
// Write DEFAULTROWHEIGHT
$this->writeDefaultRowHeight();
// Write WSBOOL
$this->writeWsbool();
// Write horizontal and vertical page breaks
$this->writeBreaks();
// Write page header
$this->writeHeader();
// Write page footer
$this->writeFooter();
// Write page horizontal centering
$this->writeHcenter();
// Write page vertical centering
$this->writeVcenter();
// Write left margin
$this->writeMarginLeft();
// Write right margin
$this->writeMarginRight();
// Write top margin
$this->writeMarginTop();
// Write bottom margin
$this->writeMarginBottom();
// Write page setup
$this->writeSetup();
// Write sheet protection
$this->writeProtect();
// Write SCENPROTECT
$this->writeScenProtect();
// Write OBJECTPROTECT
$this->writeObjectProtect();
// Write sheet password
$this->writePassword();
// Write DEFCOLWIDTH record
$this->writeDefcol();
// Write the COLINFO records if they exist
if (!empty($this->columnInfo)) {
$colcount = count($this->columnInfo);
for ($i = 0; $i < $colcount; ++$i) {
$this->writeColinfo($this->columnInfo[$i]);
}
}
$autoFilterRange = $phpSheet->getAutoFilter()->getRange();
if (!empty($autoFilterRange)) {
// Write AUTOFILTERINFO
$this->writeAutoFilterInfo();
}
// Write sheet dimensions
$this->writeDimensions();
// Row dimensions
foreach ($phpSheet->getRowDimensions() as $rowDimension) {
$xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs
$this->writeRow(
$rowDimension->getRowIndex() - 1,
(int) $rowDimension->getRowHeight(),
$xfIndex,
!$rowDimension->getVisible(),
$rowDimension->getOutlineLevel()
);
}
// Write Cells
foreach ($phpSheet->getCellCollection()->getSortedCoordinates() as $coordinate) {
/** @var Cell $cell */
$cell = $phpSheet->getCellCollection()->get($coordinate);
$row = $cell->getRow() - 1;
$column = Coordinate::columnIndexFromString($cell->getColumn()) - 1;
// Don't break Excel break the code!
if ($row > 65535 || $column > 255) {
throw new WriterException('Rows or columns overflow! Excel5 has limit to 65535 rows and 255 columns. Use XLSX instead.');
}
// Write cell value
$xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs
$cVal = $cell->getValue();
if ($cVal instanceof RichText && (string) $cVal === '') {
$cVal = '';
}
if ($cVal instanceof RichText) {
$arrcRun = [];
$str_pos = 0;
$elements = $cVal->getRichTextElements();
foreach ($elements as $element) {
// FONT Index
$str_fontidx = 0;
if ($element instanceof Run) {
$getFont = $element->getFont();
if ($getFont !== null) {
$str_fontidx = $this->fontHashIndex[$getFont->getHashCode()];
}
} else {
$styleArray = $this->phpSheet
->getParent()
?->getCellXfCollection();
if ($styleArray !== null) {
$font = $styleArray[$xfIndex - 15] ?? null;
if ($font !== null) {
$font = $font->getFont();
}
if ($font !== null) {
$str_fontidx = $this->fontHashIndex[$font->getHashCode()];
}
}
}
$arrcRun[] = ['strlen' => $str_pos, 'fontidx' => $str_fontidx];
// Position FROM
$str_pos += StringHelper::countCharacters($element->getText(), 'UTF-8');
}
/** @var array<int, array{strlen: int, fontidx: int}> $arrcRun */
$this->writeRichTextString($row, $column, $cVal->getPlainText(), $xfIndex, $arrcRun);
} else {
switch ($cell->getDatatype()) {
case DataType::TYPE_STRING:
case DataType::TYPE_INLINE:
case DataType::TYPE_NULL:
if ($cVal === '' || $cVal === null) {
$this->writeBlank($row, $column, $xfIndex);
} else {
$this->writeString($row, $column, $cell->getValueString(), $xfIndex);
}
break;
case DataType::TYPE_NUMERIC:
$this->writeNumber($row, $column, is_numeric($cVal) ? ($cVal + 0) : 0, $xfIndex);
break;
case DataType::TYPE_FORMULA:
$calculatedValue = $this->preCalculateFormulas ? $cell->getCalculatedValue() : null;
$calculatedValueString = $this->preCalculateFormulas ? $cell->getCalculatedValueString() : '';
if (self::WRITE_FORMULA_EXCEPTION == $this->writeFormula($row, $column, $cell->getValueString(), $xfIndex, $calculatedValue)) {
if ($calculatedValue === null) {
$calculatedValue = $cell->getCalculatedValue();
}
$calctype = gettype($calculatedValue);
match ($calctype) {
'integer', 'double' => $this->writeNumber($row, $column, is_numeric($calculatedValue) ? ((float) $calculatedValue) : 0.0, $xfIndex),
'string' => $this->writeString($row, $column, $calculatedValueString, $xfIndex),
'boolean' => $this->writeBoolErr($row, $column, (int) $calculatedValueString, 0, $xfIndex),
default => $this->writeString($row, $column, $cell->getValueString(), $xfIndex),
};
}
break;
case DataType::TYPE_BOOL:
$this->writeBoolErr($row, $column, (int) $cell->getValueString(), 0, $xfIndex);
break;
case DataType::TYPE_ERROR:
$this->writeBoolErr($row, $column, ErrorCode::error($cell->getValueString()), 1, $xfIndex);
break;
}
}
}
// Append
$this->writeMsoDrawing();
// Restoring active sheet.
$this->phpSheet->getParentOrThrow()->setActiveSheetIndex($activeSheetIndex);
// Write WINDOW2 record
$this->writeWindow2();
// Write PLV record
$this->writePageLayoutView();
// Write ZOOM record
$this->writeZoom();
if ($phpSheet->getFreezePane()) {
$this->writePanes();
}
// Restoring selected cells.
$this->phpSheet->setSelectedCells($selectedCells);
// Write SELECTION record
$this->writeSelection();
// Write MergedCellsTable Record
$this->writeMergedCells();
// Hyperlinks
$phpParent = $phpSheet->getParent();
$hyperlinkbase = ($phpParent === null) ? '' : $phpParent->getProperties()->getHyperlinkBase();
foreach ($phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) {
[$column, $row] = Coordinate::indexesFromString($coordinate);
$url = $hyperlink->getUrl();
if ($url[0] === '#') {
$url = "internal:$url";
} elseif (str_starts_with($url, 'sheet://')) {
// internal to current workbook
$url = str_replace('sheet://', 'internal:', $url);
} elseif (Preg::isMatch('/^(http:|https:|ftp:|mailto:)/', $url)) {
// URL
} elseif (!empty($hyperlinkbase) && !Preg::isMatch('~^([A-Za-z]:)?[/\\\]~', $url)) {
$url = "$hyperlinkbase$url";
if (!Preg::isMatch('/^(http:|https:|ftp:|mailto:)/', $url)) {
$url = 'external:' . $url;
}
} else {
// external (local file)
$url = 'external:' . $url;
}
$this->writeUrl($row - 1, $column - 1, $url);
}
$this->writeDataValidity();
$this->writeSheetLayout();
// Write SHEETPROTECTION record
$this->writeSheetProtection();
$this->writeRangeProtection();
// Write Conditional Formatting Rules and Styles
$this->writeConditionalFormatting();
$this->storeEof();
}
public const MAX_XLS_COLUMN = 256;
public const MAX_XLS_COLUMN_STRING = 'IV';
public const MAX_XLS_ROW = 65536;
private static function limitRange(string $exploded): string
{
$retVal = '';
$ranges = Coordinate::getRangeBoundaries($exploded);
$firstCol = Coordinate::columnIndexFromString($ranges[0][0]);
$firstRow = (int) $ranges[0][1];
if ($firstCol <= self::MAX_XLS_COLUMN && $firstRow <= self::MAX_XLS_ROW) {
$retVal = $exploded;
if (str_contains($exploded, ':')) {
$lastCol = Coordinate::columnIndexFromString($ranges[1][0]);
$ranges[1][1] = min(self::MAX_XLS_ROW, (int) $ranges[1][1]);
if ($lastCol > self::MAX_XLS_COLUMN) {
$ranges[1][0] = self::MAX_XLS_COLUMN_STRING;
}
$retVal = "{$ranges[0][0]}{$ranges[0][1]}:{$ranges[1][0]}{$ranges[1][1]}";
}
}
return $retVal;
}
private function writeConditionalFormatting(): void
{
$conditionalFormulaHelper = new ConditionalHelper($this->parser);
$arrConditionalStyles = [];
foreach ($this->phpSheet->getConditionalStylesCollection() as $key => $value) {
$keyExplode = explode(',', Coordinate::resolveUnionAndIntersection($key));
foreach ($keyExplode as $exploded) {
$range = self::limitRange($exploded);
if ($range !== '') {
$arrConditionalStyles[$range] = $value;
}
}
}
if (!empty($arrConditionalStyles)) {
// Write ConditionalFormattingTable records
foreach ($arrConditionalStyles as $cellCoordinate => $conditionalStyles) {
$cfHeaderWritten = false;
foreach ($conditionalStyles as $conditional) {
/** @var Conditional $conditional */
if (
$conditional->getConditionType() === Conditional::CONDITION_EXPRESSION
|| $conditional->getConditionType() === Conditional::CONDITION_CELLIS
) {
// Write CFHEADER record (only if there are Conditional Styles that we are able to write)
if ($cfHeaderWritten === false) {
$cfHeaderWritten = $this->writeCFHeader($cellCoordinate, $conditionalStyles);
}
if ($cfHeaderWritten === true) {
// Write CFRULE record
$this->writeCFRule($conditionalFormulaHelper, $conditional, $cellCoordinate);
}
}
}
}
}
}
/**
* Write a cell range address in BIFF8
* always fixed range
* See section 2.5.14 in OpenOffice.org's Documentation of the Microsoft Excel File Format.
*
* @param string $range E.g. 'A1' or 'A1:B6'
*
* @return string Binary data
*/
private function writeBIFF8CellRangeAddressFixed(string $range): string
{
$explodes = explode(':', $range);
// extract first cell, e.g. 'A1'
$firstCell = $explodes[0];
if (ctype_alpha($firstCell)) {
$firstCell .= '1';
} elseif (ctype_digit($firstCell)) {
$firstCell = "A$firstCell";
}
// extract last cell, e.g. 'B6'
if (count($explodes) == 1) {
$lastCell = $firstCell;
} else {
$lastCell = $explodes[1];
}
if (ctype_alpha($lastCell)) {
$lastCell .= (string) self::MAX_XLS_ROW;
} elseif (ctype_digit($lastCell)) {
$lastCell = self::MAX_XLS_COLUMN_STRING . $lastCell;
}
$firstCellCoordinates = Coordinate::indexesFromString($firstCell); // e.g. [0, 1]
$lastCellCoordinates = Coordinate::indexesFromString($lastCell); // e.g. [1, 6]
return pack('vvvv', $firstCellCoordinates[1] - 1, $lastCellCoordinates[1] - 1, $firstCellCoordinates[0] - 1, $lastCellCoordinates[0] - 1);
}
/**
* Retrieves data from memory in one chunk, or from disk
* sized chunks.
*
* @return string The data
*/
public function getData(): string
{
// Return data stored in memory
if (isset($this->_data)) {
$tmp = $this->_data;
$this->_data = null;
return $tmp;
}
// No data to return
return '';
}
/**
* Set the option to print the row and column headers on the printed page.
*
* @param int $print Whether to print the headers or not. Defaults to 1 (print).
*/
public function printRowColHeaders(int $print = 1): void
{
$this->printHeaders = $print;
}
/**
* This method sets the properties for outlining and grouping. The defaults
* correspond to Excel's defaults.
*/
public function setOutline(bool $visible = true, bool $symbols_below = true, bool $symbols_right = true, bool $auto_style = false): void
{
$this->outlineOn = $visible;
$this->outlineBelow = $symbols_below;
$this->outlineRight = $symbols_right;
$this->outlineStyle = $auto_style;
}
/**
* Write a double to the specified row and column (zero indexed).
* An integer can be written as a double. Excel will display an
* integer. $format is optional.
*
* Returns 0 : normal termination
* -2 : row or column out of range
*
* @param int $row Zero indexed row
* @param int $col Zero indexed column
* @param float $num The number to write
* @param int $xfIndex The optional XF format
*/
private function writeNumber(int $row, int $col, float $num, int $xfIndex): int
{
$record = 0x0203; // Record identifier
$length = 0x000E; // Number of bytes to follow
$header = pack('vv', $record, $length);
$data = pack('vvv', $row, $col, $xfIndex);
$xl_double = pack('d', $num);
if (self::getByteOrder()) { // if it's Big Endian
$xl_double = strrev($xl_double);
}
$this->append($header . $data . $xl_double);
return 0;
}
/**
* Write a LABELSST record or a LABEL record. Which one depends on BIFF version.
*
* @param int $row Row index (0-based)
* @param int $col Column index (0-based)
* @param string $str The string
* @param int $xfIndex Index to XF record
*/
private function writeString(int $row, int $col, string $str, int $xfIndex): void
{
$this->writeLabelSst($row, $col, $str, $xfIndex);
}
/**
* Write a LABELSST record or a LABEL record. Which one depends on BIFF version
* It differs from writeString by the writing of rich text strings.
*
* @param int $row Row index (0-based)
* @param int $col Column index (0-based)
* @param string $str The string
* @param int $xfIndex The XF format index for the cell
* @param array<int, array{strlen: int, fontidx: int}> $arrcRun Index to Font record and characters beginning
*/
private function writeRichTextString(int $row, int $col, string $str, int $xfIndex, array $arrcRun): void
{
$record = 0x00FD; // Record identifier
$length = 0x000A; // Bytes to follow
$str = StringHelper::UTF8toBIFF8UnicodeShort($str, $arrcRun);
// check if string is already present
if (!isset($this->stringTable[$str])) {
$this->stringTable[$str] = $this->stringUnique++;
}
++$this->stringTotal;
$header = pack('vv', $record, $length);
$data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]);
$this->append($header . $data);
}
/**
* Write a string to the specified row and column (zero indexed).
* This is the BIFF8 version (no 255 chars limit).
* $format is optional.
*
* @param int $row Zero indexed row
* @param int $col Zero indexed column
* @param string $str The string to write
* @param int $xfIndex The XF format index for the cell
*/
private function writeLabelSst(int $row, int $col, string $str, int $xfIndex): void
{
$record = 0x00FD; // Record identifier
$length = 0x000A; // Bytes to follow
$str = StringHelper::UTF8toBIFF8UnicodeLong($str);
// check if string is already present
if (!isset($this->stringTable[$str])) {
$this->stringTable[$str] = $this->stringUnique++;
}
++$this->stringTotal;
$header = pack('vv', $record, $length);
$data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]);
$this->append($header . $data);
}
/**
* Write a blank cell to the specified row and column (zero indexed).
* A blank cell is used to specify formatting without adding a string
* or a number.
*
* A blank cell without a format serves no purpose. Therefore, we don't write
* a BLANK record unless a format is specified.
*
* Returns 0 : normal termination (including no format)
* -1 : insufficient number of arguments
* -2 : row or column out of range
*
* @param int $row Zero indexed row
* @param int $col Zero indexed column
* @param int $xfIndex The XF format index
*/
public function writeBlank(int $row, int $col, int $xfIndex): int
{
$record = 0x0201; // Record identifier
$length = 0x0006; // Number of bytes to follow
$header = pack('vv', $record, $length);
$data = pack('vvv', $row, $col, $xfIndex);
$this->append($header . $data);
return 0;
}
/**
* Write a boolean or an error type to the specified row and column (zero indexed).
*
* @param int $row Row index (0-based)
* @param int $col Column index (0-based)
* @param int $isError Error or Boolean?
*/
private function writeBoolErr(int $row, int $col, int $value, int $isError, int $xfIndex): int
{
$record = 0x0205;
$length = 8;
$header = pack('vv', $record, $length);
$data = pack('vvvCC', $row, $col, $xfIndex, $value, $isError);
$this->append($header . $data);
return 0;
}
const WRITE_FORMULA_NORMAL = 0;
const WRITE_FORMULA_ERRORS = -1;
const WRITE_FORMULA_RANGE = -2;
const WRITE_FORMULA_EXCEPTION = -3;
private static bool $allowThrow = false;
public static function setAllowThrow(bool $allowThrow): void
{
self::$allowThrow = $allowThrow;
}
public static function getAllowThrow(): bool
{
return self::$allowThrow;
}
/**
* Write a formula to the specified row and column (zero indexed).
* The textual representation of the formula is passed to the parser in
* Parser.php which returns a packed binary string.
*
* Returns 0 : WRITE_FORMULA_NORMAL normal termination
* -1 : WRITE_FORMULA_ERRORS formula errors (bad formula)
* -2 : WRITE_FORMULA_RANGE row or column out of range
* -3 : WRITE_FORMULA_EXCEPTION parse raised exception, probably due to definedname
*
* @param int $row Zero indexed row
* @param int $col Zero indexed column
* @param string $formula The formula text string
* @param int $xfIndex The XF format index
* @param mixed $calculatedValue Calculated value
*/
private function writeFormula(int $row, int $col, string $formula, int $xfIndex, mixed $calculatedValue): int
{
$record = 0x0006; // Record identifier
// Initialize possible additional value for STRING record that should be written after the FORMULA record?
$stringValue = null;
// calculated value
if (isset($calculatedValue)) {
// Since we can't yet get the data type of the calculated value,
// we use best effort to determine data type
if (is_bool($calculatedValue)) {
// Boolean value
$num = pack('CCCvCv', 0x01, 0x00, (int) $calculatedValue, 0x00, 0x00, 0xFFFF);
} elseif (is_int($calculatedValue) || is_float($calculatedValue)) {
// Numeric value
$num = pack('d', $calculatedValue);
} elseif (is_string($calculatedValue)) {
$errorCodes = DataType::getErrorCodes();
if (isset($errorCodes[$calculatedValue])) {
// Error value
$num = pack('CCCvCv', 0x02, 0x00, ErrorCode::error($calculatedValue), 0x00, 0x00, 0xFFFF);
} elseif ($calculatedValue === '') {
// Empty string (and BIFF8)
$num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
} else {
// Non-empty string value (or empty string BIFF5)
$stringValue = $calculatedValue;
$num = pack('CCCvCv', 0x00, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
}
} else {
// We are really not supposed to reach here
$num = pack('d', 0x00);
}
} else {
$num = pack('d', 0x00);
}
$grbit = 0x03; // Option flags
$unknown = 0x0000; // Must be zero
// Strip the '=' or '@' sign at the beginning of the formula string
if ($formula[0] == '=') {
$formula = substr($formula, 1);
} else {
// Error handling
$this->writeString($row, $col, 'Unrecognised character for formula', 0);
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | true |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls/CellDataValidation.php | src/PhpSpreadsheet/Writer/Xls/CellDataValidation.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
class CellDataValidation
{
/**
* @var array<string, int>
*/
protected static array $validationTypeMap = [
DataValidation::TYPE_NONE => 0x00,
DataValidation::TYPE_WHOLE => 0x01,
DataValidation::TYPE_DECIMAL => 0x02,
DataValidation::TYPE_LIST => 0x03,
DataValidation::TYPE_DATE => 0x04,
DataValidation::TYPE_TIME => 0x05,
DataValidation::TYPE_TEXTLENGTH => 0x06,
DataValidation::TYPE_CUSTOM => 0x07,
];
/**
* @var array<string, int>
*/
protected static array $errorStyleMap = [
DataValidation::STYLE_STOP => 0x00,
DataValidation::STYLE_WARNING => 0x01,
DataValidation::STYLE_INFORMATION => 0x02,
];
/**
* @var array<string, int>
*/
protected static array $operatorMap = [
DataValidation::OPERATOR_BETWEEN => 0x00,
DataValidation::OPERATOR_NOTBETWEEN => 0x01,
DataValidation::OPERATOR_EQUAL => 0x02,
DataValidation::OPERATOR_NOTEQUAL => 0x03,
DataValidation::OPERATOR_GREATERTHAN => 0x04,
DataValidation::OPERATOR_LESSTHAN => 0x05,
DataValidation::OPERATOR_GREATERTHANOREQUAL => 0x06,
DataValidation::OPERATOR_LESSTHANOREQUAL => 0x07,
];
public static function type(DataValidation $dataValidation): int
{
$validationType = $dataValidation->getType();
return self::$validationTypeMap[$validationType] ?? self::$validationTypeMap[DataValidation::TYPE_NONE];
}
public static function errorStyle(DataValidation $dataValidation): int
{
$errorStyle = $dataValidation->getErrorStyle();
return self::$errorStyleMap[$errorStyle] ?? self::$errorStyleMap[DataValidation::STYLE_STOP];
}
public static function operator(DataValidation $dataValidation): int
{
$operator = $dataValidation->getOperator();
return self::$operatorMap[$operator] ?? self::$operatorMap[DataValidation::OPERATOR_BETWEEN];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls/Parser.php | src/PhpSpreadsheet/Writer/Xls/Parser.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
use Composer\Pcre\Preg;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as PhpspreadsheetWorksheet;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
// Original file header of PEAR::Spreadsheet_Excel_Writer_Parser (used as the base for this class):
// -----------------------------------------------------------------------------------------
// * Class for parsing Excel formulas
// *
// * 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 Parser
{
/** Constants */
// Sheet title in unquoted form
// Invalid sheet title characters cannot occur in the sheet title:
// *:/\?[]
// Moreover, there are valid sheet title characters that cannot occur in unquoted form (there may be more?)
// +-% '^&<>=,;#()"{}
const REGEX_SHEET_TITLE_UNQUOTED = '[^\*\:\/\\\\\?\[\]\+\-\% \\\'\^\&\<\>\=\,\;\#\(\)\"\{\}]+';
// Sheet title in quoted form (without surrounding quotes)
// Invalid sheet title characters cannot occur in the sheet title:
// *:/\?[] (usual invalid sheet title characters)
// Single quote is represented as a pair ''
// Former value for this constant led to "catastrophic backtracking",
// unable to handle double apostrophes.
// (*COMMIT) should prevent this.
const REGEX_SHEET_TITLE_QUOTED = "([^*:/\\\\?\\[\\]']|'')+";
const REGEX_CELL_TITLE_QUOTED = "~^'"
. self::REGEX_SHEET_TITLE_QUOTED
. '(:' . self::REGEX_SHEET_TITLE_QUOTED . ')?'
. "'!(*COMMIT)"
. '[$]?[A-Ia-i]?[A-Za-z][$]?(\d+)'
. '$~u';
const REGEX_RANGE_TITLE_QUOTED = "~^'"
. self::REGEX_SHEET_TITLE_QUOTED
. '(:' . self::REGEX_SHEET_TITLE_QUOTED . ')?'
. "'!(*COMMIT)"
. '[$]?[A-Ia-i]?[A-Za-z][$]?(\d+)'
. ':'
. '[$]?[A-Ia-i]?[A-Za-z][$]?(\d+)'
. '$~u';
private const UTF8 = 'UTF-8';
/**
* The index of the character we are currently looking at.
*/
public int $currentCharacter;
/**
* The token we are working on.
*/
public string $currentToken;
/**
* The formula to parse.
*/
private string $formula;
/**
* The character ahead of the current char.
*/
public string $lookAhead;
/**
* The parse tree to be generated.
*
* @var mixed[]|string
*/
public array|string $parseTree;
/**
* Array of external sheets.
*
* @var array<string, int>
*/
private array $externalSheets;
/**
* Array of sheet references in the form of REF structures.
*
* @var array<int|string, int|string>
*/
public array $references;
/**
* The Excel ptg indices.
*
* @var array<string, int>
*/
private array $ptg = [
'ptgExp' => 0x01,
'ptgTbl' => 0x02,
'ptgAdd' => 0x03,
'ptgSub' => 0x04,
'ptgMul' => 0x05,
'ptgDiv' => 0x06,
'ptgPower' => 0x07,
'ptgConcat' => 0x08,
'ptgLT' => 0x09,
'ptgLE' => 0x0A,
'ptgEQ' => 0x0B,
'ptgGE' => 0x0C,
'ptgGT' => 0x0D,
'ptgNE' => 0x0E,
'ptgIsect' => 0x0F,
'ptgUnion' => 0x10,
'ptgRange' => 0x11,
'ptgUplus' => 0x12,
'ptgUminus' => 0x13,
'ptgPercent' => 0x14,
'ptgParen' => 0x15,
'ptgMissArg' => 0x16,
'ptgStr' => 0x17,
'ptgAttr' => 0x19,
'ptgSheet' => 0x1A,
'ptgEndSheet' => 0x1B,
'ptgErr' => 0x1C,
'ptgBool' => 0x1D,
'ptgInt' => 0x1E,
'ptgNum' => 0x1F,
'ptgArray' => 0x20,
'ptgFunc' => 0x21,
'ptgFuncVar' => 0x22,
'ptgName' => 0x23,
'ptgRef' => 0x24,
'ptgArea' => 0x25,
'ptgMemArea' => 0x26,
'ptgMemErr' => 0x27,
'ptgMemNoMem' => 0x28,
'ptgMemFunc' => 0x29,
'ptgRefErr' => 0x2A,
'ptgAreaErr' => 0x2B,
'ptgRefN' => 0x2C,
'ptgAreaN' => 0x2D,
'ptgMemAreaN' => 0x2E,
'ptgMemNoMemN' => 0x2F,
'ptgNameX' => 0x39,
'ptgRef3d' => 0x3A,
'ptgArea3d' => 0x3B,
'ptgRefErr3d' => 0x3C,
'ptgAreaErr3d' => 0x3D,
'ptgArrayV' => 0x40,
'ptgFuncV' => 0x41,
'ptgFuncVarV' => 0x42,
'ptgNameV' => 0x43,
'ptgRefV' => 0x44,
'ptgAreaV' => 0x45,
'ptgMemAreaV' => 0x46,
'ptgMemErrV' => 0x47,
'ptgMemNoMemV' => 0x48,
'ptgMemFuncV' => 0x49,
'ptgRefErrV' => 0x4A,
'ptgAreaErrV' => 0x4B,
'ptgRefNV' => 0x4C,
'ptgAreaNV' => 0x4D,
'ptgMemAreaNV' => 0x4E,
'ptgMemNoMemNV' => 0x4F,
'ptgFuncCEV' => 0x58,
'ptgNameXV' => 0x59,
'ptgRef3dV' => 0x5A,
'ptgArea3dV' => 0x5B,
'ptgRefErr3dV' => 0x5C,
'ptgAreaErr3dV' => 0x5D,
'ptgArrayA' => 0x60,
'ptgFuncA' => 0x61,
'ptgFuncVarA' => 0x62,
'ptgNameA' => 0x63,
'ptgRefA' => 0x64,
'ptgAreaA' => 0x65,
'ptgMemAreaA' => 0x66,
'ptgMemErrA' => 0x67,
'ptgMemNoMemA' => 0x68,
'ptgMemFuncA' => 0x69,
'ptgRefErrA' => 0x6A,
'ptgAreaErrA' => 0x6B,
'ptgRefNA' => 0x6C,
'ptgAreaNA' => 0x6D,
'ptgMemAreaNA' => 0x6E,
'ptgMemNoMemNA' => 0x6F,
'ptgFuncCEA' => 0x78,
'ptgNameXA' => 0x79,
'ptgRef3dA' => 0x7A,
'ptgArea3dA' => 0x7B,
'ptgRefErr3dA' => 0x7C,
'ptgAreaErr3dA' => 0x7D,
];
/**
* Thanks to Michael Meeks and Gnumeric for the initial arg values.
*
* The following hash was generated by "function_locale.pl" in the distro.
* Refer to function_locale.pl for non-English function names.
*
* The array elements are as follows:
* ptg: The Excel function ptg code.
* args: The number of arguments that the function takes:
* >=0 is a fixed number of arguments.
* -1 is a variable number of arguments.
* class: The reference, value or array class of the function args.
* vol: The function is volatile.
*
* @var array<string, array{int, int, int, int}>
*/
private array $functions = [
// function ptg args class vol
'COUNT' => [0, -1, 0, 0],
'IF' => [1, -1, 1, 0],
'ISNA' => [2, 1, 1, 0],
'ISERROR' => [3, 1, 1, 0],
'SUM' => [4, -1, 0, 0],
'AVERAGE' => [5, -1, 0, 0],
'MIN' => [6, -1, 0, 0],
'MAX' => [7, -1, 0, 0],
'ROW' => [8, -1, 0, 0],
'COLUMN' => [9, -1, 0, 0],
'NA' => [10, 0, 0, 0],
'NPV' => [11, -1, 1, 0],
'STDEV' => [12, -1, 0, 0],
'DOLLAR' => [13, -1, 1, 0],
'FIXED' => [14, -1, 1, 0],
'SIN' => [15, 1, 1, 0],
'COS' => [16, 1, 1, 0],
'TAN' => [17, 1, 1, 0],
'ATAN' => [18, 1, 1, 0],
'PI' => [19, 0, 1, 0],
'SQRT' => [20, 1, 1, 0],
'EXP' => [21, 1, 1, 0],
'LN' => [22, 1, 1, 0],
'LOG10' => [23, 1, 1, 0],
'ABS' => [24, 1, 1, 0],
'INT' => [25, 1, 1, 0],
'SIGN' => [26, 1, 1, 0],
'ROUND' => [27, 2, 1, 0],
'LOOKUP' => [28, -1, 0, 0],
'INDEX' => [29, -1, 0, 1],
'REPT' => [30, 2, 1, 0],
'MID' => [31, 3, 1, 0],
'LEN' => [32, 1, 1, 0],
'VALUE' => [33, 1, 1, 0],
'TRUE' => [34, 0, 1, 0],
'FALSE' => [35, 0, 1, 0],
'AND' => [36, -1, 0, 0],
'OR' => [37, -1, 0, 0],
'NOT' => [38, 1, 1, 0],
'MOD' => [39, 2, 1, 0],
'DCOUNT' => [40, 3, 0, 0],
'DSUM' => [41, 3, 0, 0],
'DAVERAGE' => [42, 3, 0, 0],
'DMIN' => [43, 3, 0, 0],
'DMAX' => [44, 3, 0, 0],
'DSTDEV' => [45, 3, 0, 0],
'VAR' => [46, -1, 0, 0],
'DVAR' => [47, 3, 0, 0],
'TEXT' => [48, 2, 1, 0],
'LINEST' => [49, -1, 0, 0],
'TREND' => [50, -1, 0, 0],
'LOGEST' => [51, -1, 0, 0],
'GROWTH' => [52, -1, 0, 0],
'PV' => [56, -1, 1, 0],
'FV' => [57, -1, 1, 0],
'NPER' => [58, -1, 1, 0],
'PMT' => [59, -1, 1, 0],
'RATE' => [60, -1, 1, 0],
'MIRR' => [61, 3, 0, 0],
'IRR' => [62, -1, 0, 0],
'RAND' => [63, 0, 1, 1],
'MATCH' => [64, -1, 0, 0],
'DATE' => [65, 3, 1, 0],
'TIME' => [66, 3, 1, 0],
'DAY' => [67, 1, 1, 0],
'MONTH' => [68, 1, 1, 0],
'YEAR' => [69, 1, 1, 0],
'WEEKDAY' => [70, -1, 1, 0],
'HOUR' => [71, 1, 1, 0],
'MINUTE' => [72, 1, 1, 0],
'SECOND' => [73, 1, 1, 0],
'NOW' => [74, 0, 1, 1],
'AREAS' => [75, 1, 0, 1],
'ROWS' => [76, 1, 0, 1],
'COLUMNS' => [77, 1, 0, 1],
'OFFSET' => [78, -1, 0, 1],
'SEARCH' => [82, -1, 1, 0],
'TRANSPOSE' => [83, 1, 1, 0],
'TYPE' => [86, 1, 1, 0],
'ATAN2' => [97, 2, 1, 0],
'ASIN' => [98, 1, 1, 0],
'ACOS' => [99, 1, 1, 0],
'CHOOSE' => [100, -1, 1, 0],
'HLOOKUP' => [101, -1, 0, 0],
'VLOOKUP' => [102, -1, 0, 0],
'ISREF' => [105, 1, 0, 0],
'LOG' => [109, -1, 1, 0],
'CHAR' => [111, 1, 1, 0],
'LOWER' => [112, 1, 1, 0],
'UPPER' => [113, 1, 1, 0],
'PROPER' => [114, 1, 1, 0],
'LEFT' => [115, -1, 1, 0],
'RIGHT' => [116, -1, 1, 0],
'EXACT' => [117, 2, 1, 0],
'TRIM' => [118, 1, 1, 0],
'REPLACE' => [119, 4, 1, 0],
'SUBSTITUTE' => [120, -1, 1, 0],
'CODE' => [121, 1, 1, 0],
'FIND' => [124, -1, 1, 0],
'CELL' => [125, -1, 0, 1],
'ISERR' => [126, 1, 1, 0],
'ISTEXT' => [127, 1, 1, 0],
'ISNUMBER' => [128, 1, 1, 0],
'ISBLANK' => [129, 1, 1, 0],
'T' => [130, 1, 0, 0],
'N' => [131, 1, 0, 0],
'DATEVALUE' => [140, 1, 1, 0],
'TIMEVALUE' => [141, 1, 1, 0],
'SLN' => [142, 3, 1, 0],
'SYD' => [143, 4, 1, 0],
'DDB' => [144, -1, 1, 0],
'INDIRECT' => [148, -1, 1, 1],
'CALL' => [150, -1, 1, 0],
'CLEAN' => [162, 1, 1, 0],
'MDETERM' => [163, 1, 2, 0],
'MINVERSE' => [164, 1, 2, 0],
'MMULT' => [165, 2, 2, 0],
'IPMT' => [167, -1, 1, 0],
'PPMT' => [168, -1, 1, 0],
'COUNTA' => [169, -1, 0, 0],
'PRODUCT' => [183, -1, 0, 0],
'FACT' => [184, 1, 1, 0],
'DPRODUCT' => [189, 3, 0, 0],
'ISNONTEXT' => [190, 1, 1, 0],
'STDEVP' => [193, -1, 0, 0],
'VARP' => [194, -1, 0, 0],
'DSTDEVP' => [195, 3, 0, 0],
'DVARP' => [196, 3, 0, 0],
'TRUNC' => [197, -1, 1, 0],
'ISLOGICAL' => [198, 1, 1, 0],
'DCOUNTA' => [199, 3, 0, 0],
'USDOLLAR' => [204, -1, 1, 0],
'FINDB' => [205, -1, 1, 0],
'SEARCHB' => [206, -1, 1, 0],
'REPLACEB' => [207, 4, 1, 0],
'LEFTB' => [208, -1, 1, 0],
'RIGHTB' => [209, -1, 1, 0],
'MIDB' => [210, 3, 1, 0],
'LENB' => [211, 1, 1, 0],
'ROUNDUP' => [212, 2, 1, 0],
'ROUNDDOWN' => [213, 2, 1, 0],
'ASC' => [214, 1, 1, 0],
'DBCS' => [215, 1, 1, 0],
'RANK' => [216, -1, 0, 0],
'ADDRESS' => [219, -1, 1, 0],
'DAYS360' => [220, -1, 1, 0],
'TODAY' => [221, 0, 1, 1],
'VDB' => [222, -1, 1, 0],
'MEDIAN' => [227, -1, 0, 0],
'SUMPRODUCT' => [228, -1, 2, 0],
'SINH' => [229, 1, 1, 0],
'COSH' => [230, 1, 1, 0],
'TANH' => [231, 1, 1, 0],
'ASINH' => [232, 1, 1, 0],
'ACOSH' => [233, 1, 1, 0],
'ATANH' => [234, 1, 1, 0],
'DGET' => [235, 3, 0, 0],
'INFO' => [244, 1, 1, 1],
'DB' => [247, -1, 1, 0],
'FREQUENCY' => [252, 2, 0, 0],
'ERROR.TYPE' => [261, 1, 1, 0],
'REGISTER.ID' => [267, -1, 1, 0],
'AVEDEV' => [269, -1, 0, 0],
'BETADIST' => [270, -1, 1, 0],
'GAMMALN' => [271, 1, 1, 0],
'BETAINV' => [272, -1, 1, 0],
'BINOMDIST' => [273, 4, 1, 0],
'CHIDIST' => [274, 2, 1, 0],
'CHIINV' => [275, 2, 1, 0],
'COMBIN' => [276, 2, 1, 0],
'CONFIDENCE' => [277, 3, 1, 0],
'CRITBINOM' => [278, 3, 1, 0],
'EVEN' => [279, 1, 1, 0],
'EXPONDIST' => [280, 3, 1, 0],
'FDIST' => [281, 3, 1, 0],
'FINV' => [282, 3, 1, 0],
'FISHER' => [283, 1, 1, 0],
'FISHERINV' => [284, 1, 1, 0],
'FLOOR' => [285, 2, 1, 0],
'FLOOR.XCL' => [285, 2, 1, 0],
'GAMMADIST' => [286, 4, 1, 0],
'GAMMAINV' => [287, 3, 1, 0],
'CEILING' => [288, 2, 1, 0],
'CEILING.XCL' => [288, 2, 1, 0],
'HYPGEOMDIST' => [289, 4, 1, 0],
'LOGNORMDIST' => [290, 3, 1, 0],
'LOGINV' => [291, 3, 1, 0],
'NEGBINOMDIST' => [292, 3, 1, 0],
'NORMDIST' => [293, 4, 1, 0],
'NORMSDIST' => [294, 1, 1, 0],
'NORMINV' => [295, 3, 1, 0],
'NORMSINV' => [296, 1, 1, 0],
'STANDARDIZE' => [297, 3, 1, 0],
'ODD' => [298, 1, 1, 0],
'PERMUT' => [299, 2, 1, 0],
'POISSON' => [300, 3, 1, 0],
'TDIST' => [301, 3, 1, 0],
'WEIBULL' => [302, 4, 1, 0],
'SUMXMY2' => [303, 2, 2, 0],
'SUMX2MY2' => [304, 2, 2, 0],
'SUMX2PY2' => [305, 2, 2, 0],
'CHITEST' => [306, 2, 2, 0],
'CORREL' => [307, 2, 2, 0],
'COVAR' => [308, 2, 2, 0],
'FORECAST' => [309, 3, 2, 0],
'FTEST' => [310, 2, 2, 0],
'INTERCEPT' => [311, 2, 2, 0],
'PEARSON' => [312, 2, 2, 0],
'RSQ' => [313, 2, 2, 0],
'STEYX' => [314, 2, 2, 0],
'SLOPE' => [315, 2, 2, 0],
'TTEST' => [316, 4, 2, 0],
'PROB' => [317, -1, 2, 0],
'DEVSQ' => [318, -1, 0, 0],
'GEOMEAN' => [319, -1, 0, 0],
'HARMEAN' => [320, -1, 0, 0],
'SUMSQ' => [321, -1, 0, 0],
'KURT' => [322, -1, 0, 0],
'SKEW' => [323, -1, 0, 0],
'ZTEST' => [324, -1, 0, 0],
'LARGE' => [325, 2, 0, 0],
'SMALL' => [326, 2, 0, 0],
'QUARTILE' => [327, 2, 0, 0],
'PERCENTILE' => [328, 2, 0, 0],
'PERCENTRANK' => [329, -1, 0, 0],
'MODE' => [330, -1, 2, 0],
'TRIMMEAN' => [331, 2, 0, 0],
'TINV' => [332, 2, 1, 0],
'CONCATENATE' => [336, -1, 1, 0],
'POWER' => [337, 2, 1, 0],
'RADIANS' => [342, 1, 1, 0],
'DEGREES' => [343, 1, 1, 0],
'SUBTOTAL' => [344, -1, 0, 0],
'SUMIF' => [345, -1, 0, 0],
'COUNTIF' => [346, 2, 0, 0],
'COUNTBLANK' => [347, 1, 0, 0],
'ISPMT' => [350, 4, 1, 0],
'DATEDIF' => [351, 3, 1, 0],
'DATESTRING' => [352, 1, 1, 0],
'NUMBERSTRING' => [353, 2, 1, 0],
'ROMAN' => [354, -1, 1, 0],
'GETPIVOTDATA' => [358, -1, 0, 0],
'HYPERLINK' => [359, -1, 1, 0],
'PHONETIC' => [360, 1, 0, 0],
'AVERAGEA' => [361, -1, 0, 0],
'MAXA' => [362, -1, 0, 0],
'MINA' => [363, -1, 0, 0],
'STDEVPA' => [364, -1, 0, 0],
'VARPA' => [365, -1, 0, 0],
'STDEVA' => [366, -1, 0, 0],
'VARA' => [367, -1, 0, 0],
'BAHTTEXT' => [368, 1, 0, 0],
];
private Spreadsheet $spreadsheet;
/**
* The class constructor.
*/
public function __construct(Spreadsheet $spreadsheet)
{
$this->spreadsheet = $spreadsheet;
$this->currentCharacter = 0;
$this->currentToken = ''; // The token we are working on.
$this->formula = ''; // The formula to parse.
$this->lookAhead = ''; // The character ahead of the current char.
$this->parseTree = ''; // The parse tree to be generated.
$this->externalSheets = [];
$this->references = [];
}
/**
* Convert a token to the proper ptg value.
*
* @param string $token the token to convert
*
* @return string the converted token on success
*/
private function convert(string $token): string
{
if (Preg::isMatch('/"([^"]|""){0,255}"/', $token)) {
return $this->convertString($token);
}
if (is_numeric($token)) {
return $this->convertNumber($token);
}
// match references like A1 or $A$1
if (Preg::isMatch('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/', $token)) {
return $this->convertRef2d($token);
}
// match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1
if (Preg::isMatch('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\!\$?[A-Ia-i]?[A-Za-z]\$?(\d+)$/u', $token)) {
return $this->convertRef3d($token);
}
// match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1
if (self::matchCellSheetnameQuoted($token)) {
return $this->convertRef3d($token);
}
// match ranges like A1:B2 or $A$1:$B$2
if (Preg::isMatch('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) {
return $this->convertRange2d($token);
}
// match external ranges like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
if (Preg::isMatch('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\!\$?([A-Ia-i]?[A-Za-z])?\$?(\d+)\:\$?([A-Ia-i]?[A-Za-z])?\$?(\d+)$/u', $token)) {
return $this->convertRange3d($token);
}
// match external ranges like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
if (self::matchRangeSheetnameQuoted($token)) {
return $this->convertRange3d($token);
}
// operators (including parentheses)
if (isset($this->ptg[$token])) {
return pack('C', $this->ptg[$token]);
}
// match error codes
if (Preg::isMatch('/^#[A-Z0\/]{3,5}[!?]{1}$/', $token) || $token == '#N/A') {
return $this->convertError($token);
}
if (Preg::isMatch('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $token) && $this->spreadsheet->getDefinedName($token) !== null) {
return $this->convertDefinedName($token);
}
// commented so argument number can be processed correctly. See toReversePolish().
/*if (Preg::isMatch("/[A-Z0-9\xc0-\xdc\.]+/", $token))
{
return($this->convertFunction($token, $this->_func_args));
}*/
// if it's an argument, ignore the token (the argument remains)
if ($token == 'arg') {
return '';
}
if (Preg::isMatch('/^true$/i', $token)) {
return $this->convertBool(1);
}
if (Preg::isMatch('/^false$/i', $token)) {
return $this->convertBool(0);
}
// TODO: use real error codes
throw new WriterException("Unknown token $token");
}
/**
* Convert a number token to ptgInt or ptgNum.
*
* @param float|int|string $num an integer or double for conversion to its ptg value
*/
private function convertNumber(mixed $num): string
{
// Integer in the range 0..2**16-1
if ((Preg::isMatch('/^\d+$/', (string) $num)) && ($num <= 65535)) {
return pack('Cv', $this->ptg['ptgInt'], $num);
}
// A float
if (BIFFwriter::getByteOrder()) { // if it's Big Endian
$num = strrev((string) $num);
}
return pack('Cd', $this->ptg['ptgNum'], $num);
}
private function convertBool(int $num): string
{
return pack('CC', $this->ptg['ptgBool'], $num);
}
/**
* Convert a string token to ptgStr.
*
* @param string $string a string for conversion to its ptg value
*
* @return string the converted token
*/
private function convertString(string $string): string
{
// chop away beggining and ending quotes
$string = substr($string, 1, -1);
if (strlen($string) > 255) {
throw new WriterException('String is too long');
}
return pack('C', $this->ptg['ptgStr']) . StringHelper::UTF8toBIFF8UnicodeShort($string);
}
/**
* Convert a function to a ptgFunc or ptgFuncVarV depending on the number of
* args that it takes.
*
* @param string $token the name of the function for convertion to ptg value
* @param int $num_args the number of arguments the function receives
*
* @return string The packed ptg for the function
*/
private function convertFunction(string $token, int $num_args): string
{
$args = $this->functions[$token][1];
// Fixed number of args eg. TIME($i, $j, $k).
if ($args >= 0) {
return pack('Cv', $this->ptg['ptgFuncV'], $this->functions[$token][0]);
}
// Variable number of args eg. SUM($i, $j, $k, ..).
return pack('CCv', $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]);
}
/**
* Convert an Excel range such as A1:D4 to a ptgRefV.
*
* @param string $range An Excel range in the A1:A2
*/
private function convertRange2d(string $range, int $class = 0): string
{
// TODO: possible class value 0,1,2 check Formula.pm
// Split the range into 2 cell refs
if (Preg::isMatch('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) {
[$cell1, $cell2] = explode(':', $range);
} else {
// TODO: use real error codes
throw new WriterException('Unknown range separator');
}
// Convert the cell references
[$row1, $col1] = $this->cellToPackedRowcol($cell1);
[$row2, $col2] = $this->cellToPackedRowcol($cell2);
// The ptg value depends on the class of the ptg.
if ($class == 0) {
$ptgArea = pack('C', $this->ptg['ptgArea']);
} elseif ($class == 1) {
$ptgArea = pack('C', $this->ptg['ptgAreaV']);
} elseif ($class == 2) {
$ptgArea = pack('C', $this->ptg['ptgAreaA']);
} else {
// TODO: use real error codes
throw new WriterException("Unknown class $class");
}
return $ptgArea . $row1 . $row2 . $col1 . $col2;
}
/**
* Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to
* a ptgArea3d.
*
* @param string $token an Excel range in the Sheet1!A1:A2 format
*
* @return string the packed ptgArea3d token on success
*/
private function convertRange3d(string $token): string
{
// Split the ref at the ! symbol
[$ext_ref, $range] = PhpspreadsheetWorksheet::extractSheetTitle($token, true, true);
// Convert the external reference part (different for BIFF8)
$ext_ref = $this->getRefIndex($ext_ref ?? '');
// Split the range into 2 cell refs
[$cell1, $cell2] = explode(':', $range ?? '');
// Convert the cell references
if (Preg::isMatch('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $cell1)) {
[$row1, $col1] = $this->cellToPackedRowcol($cell1);
[$row2, $col2] = $this->cellToPackedRowcol($cell2);
} else { // It's a rows range (like 26:27)
[$row1, $col1, $row2, $col2] = $this->rangeToPackedRange($cell1 . ':' . $cell2);
}
// The ptg value depends on the class of the ptg.
$ptgArea = pack('C', $this->ptg['ptgArea3d']);
return $ptgArea . $ext_ref . $row1 . $row2 . $col1 . $col2;
}
/**
* Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV.
*
* @param string $cell An Excel cell reference
*
* @return string The cell in packed() format with the corresponding ptg
*/
private function convertRef2d(string $cell): string
{
// Convert the cell reference
$cell_array = $this->cellToPackedRowcol($cell);
[$row, $col] = $cell_array;
// The ptg value depends on the class of the ptg.
$ptgRef = pack('C', $this->ptg['ptgRefA']);
return $ptgRef . $row . $col;
}
/**
* Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a
* ptgRef3d.
*
* @param string $cell An Excel cell reference
*
* @return string the packed ptgRef3d token on success
*/
private function convertRef3d(string $cell): string
{
// Split the ref at the ! symbol
[$ext_ref, $cell] = PhpspreadsheetWorksheet::extractSheetTitle($cell, true, true);
// Convert the external reference part (different for BIFF8)
$ext_ref = $this->getRefIndex($ext_ref ?? '');
// Convert the cell reference part
[$row, $col] = $this->cellToPackedRowcol($cell ?? '');
// The ptg value depends on the class of the ptg.
$ptgRef = pack('C', $this->ptg['ptgRef3dA']);
return $ptgRef . $ext_ref . $row . $col;
}
/**
* Convert an error code to a ptgErr.
*
* @param string $errorCode The error code for conversion to its ptg value
*
* @return string The error code ptgErr
*/
private function convertError(string $errorCode): string
{
return match ($errorCode) {
'#NULL!' => pack('C', 0x00),
'#DIV/0!' => pack('C', 0x07),
'#VALUE!' => pack('C', 0x0F),
'#REF!' => pack('C', 0x17),
'#NAME?' => pack('C', 0x1D),
'#NUM!' => pack('C', 0x24),
'#N/A' => pack('C', 0x2A),
default => pack('C', 0xFF),
};
}
private bool $tryDefinedName = false;
private function convertDefinedName(string $name): string
{
if (strlen($name) > 255) {
throw new WriterException('Defined Name is too long');
}
if ($this->tryDefinedName) {
// @codeCoverageIgnoreStart
$nameReference = 1;
foreach ($this->spreadsheet->getDefinedNames() as $definedName) {
if ($name === $definedName->getName()) {
break;
}
++$nameReference;
}
$ptgRef = pack('Cvxx', $this->ptg['ptgName'], $nameReference);
return $ptgRef;
// @codeCoverageIgnoreEnd
}
throw new WriterException('Cannot yet write formulae with defined names to Xls');
}
/**
* Look up the REF index that corresponds to an external sheet name
* (or range). If it doesn't exist yet add it to the workbook's references
* array. It assumes all sheet names given must exist.
*
* @param string $ext_ref The name of the external reference
*
* @return string The reference index in packed() format on success
*/
private function getRefIndex(string $ext_ref): string
{
$ext_ref = Preg::replace(["/^'/", "/'$/"], ['', ''], $ext_ref); // Remove leading and trailing ' if any.
$ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with '
// Check if there is a sheet range eg., Sheet1:Sheet2.
if (Preg::isMatch('/:/', $ext_ref)) {
[$sheet_name1, $sheet_name2] = explode(':', $ext_ref);
$sheet1 = $this->getSheetIndex($sheet_name1);
if ($sheet1 == -1) {
throw new WriterException("Unknown sheet name $sheet_name1 in formula");
}
$sheet2 = $this->getSheetIndex($sheet_name2);
if ($sheet2 == -1) {
throw new WriterException("Unknown sheet name $sheet_name2 in formula");
}
// Reverse max and min sheet numbers if necessary
if ($sheet1 > $sheet2) {
[$sheet1, $sheet2] = [$sheet2, $sheet1];
}
} else { // Single sheet name only.
$sheet1 = $this->getSheetIndex($ext_ref);
if ($sheet1 == -1) {
throw new WriterException("Unknown sheet name $ext_ref in formula");
}
$sheet2 = $sheet1;
}
// assume all references belong to this document
$supbook_index = 0x00;
$ref = pack('vvv', $supbook_index, $sheet1, $sheet2);
$totalreferences = count($this->references);
$index = -1;
for ($i = 0; $i < $totalreferences; ++$i) {
if ($ref == $this->references[$i]) {
$index = $i;
break;
}
}
// if REF was not found add it to references array
if ($index == -1) {
$this->references[$totalreferences] = $ref;
$index = $totalreferences;
}
return pack('v', $index);
}
/**
* Look up the index that corresponds to an external sheet name. The hash of
* sheet names is updated by the addworksheet() method of the
* \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class.
*
* @param string $sheet_name Sheet name
*
* @return int The sheet index, -1 if the sheet was not found
*/
private function getSheetIndex(string $sheet_name): int
{
if (!isset($this->externalSheets[$sheet_name])) {
return -1;
}
return $this->externalSheets[$sheet_name];
}
/**
* This method is used to update the array of sheet names. It is
* called by the addWorksheet() method of the
* \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class.
*
* @param string $name The name of the worksheet being added
* @param int $index The index of the worksheet being added
*
* @see Workbook::addWorksheet
*/
public function setExtSheet(string $name, int $index): void
{
$this->externalSheets[$name] = $index;
}
/**
* pack() row and column into the required 3 or 4 byte format.
*
* @param string $cell The Excel cell reference to be packed
*
* @return array{string, string} Array containing the row and column in packed() format
*/
private function cellToPackedRowcol(string $cell): array
{
$cell = strtoupper($cell);
[$row, $col, $row_rel, $col_rel] = $this->cellToRowcol($cell);
if ($col >= 256) {
throw new WriterException("Column in: $cell greater than 255");
}
if ($row >= 65536) {
throw new WriterException("Row in: $cell greater than 65536 ");
}
// Set the high bits to indicate if row or col are relative.
$col |= $col_rel << 14;
$col |= $row_rel << 15;
$col = pack('v', $col);
$row = pack('v', $row);
return [$row, $col];
}
/**
* pack() row range into the required 3 or 4 byte format.
* Just using maximum col/rows, which is probably not the correct solution.
*
* @param string $range The Excel range to be packed
*
* @return array{string, string, string, string} Array containing (row1,col1,row2,col2) in packed() format
*/
private function rangeToPackedRange(string $range): array
{
if (!Preg::isMatch('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match)) {
// @codeCoverageIgnoreStart
throw new WriterException('Regexp failure in rangeToPackedRange');
// @codeCoverageIgnoreEnd
}
// return absolute rows if there is a $ in the ref
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | true |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls/ErrorCode.php | src/PhpSpreadsheet/Writer/Xls/ErrorCode.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
class ErrorCode
{
/**
* @var array<string, int>
*/
protected static array $errorCodeMap = [
'#NULL!' => 0x00,
'#DIV/0!' => 0x07,
'#VALUE!' => 0x0F,
'#REF!' => 0x17,
'#NAME?' => 0x1D,
'#NUM!' => 0x24,
'#N/A' => 0x2A,
];
public static function error(string $errorCode): int
{
return self::$errorCodeMap[$errorCode] ?? 0;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php | src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php | <?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.
*/
private static ?int $byteOrder = null;
/**
* The string containing the data of the BIFF stream.
*/
public ?string $_data;
/**
* The size of the data in bytes. Should be the same as strlen($this->_data).
*/
public int $_datasize;
/**
* The maximum length for a BIFF record (excluding record header and length field). See addContinue().
*
* @see addContinue()
*/
private int $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().
*/
public static function getByteOrder(): int
{
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(string $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
*/
public function writeData(string $data): string
{
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(int $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(): string
{
$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(string $data): string
{
$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;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls/Style/CellFill.php | src/PhpSpreadsheet/Writer/Xls/Style/CellFill.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls\Style;
use PhpOffice\PhpSpreadsheet\Style\Fill;
class CellFill
{
/**
* @var array<string, int>
*/
protected static array $fillStyleMap = [
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
];
public static function style(Fill $fill): int
{
$fillStyle = $fill->getFillType();
if (is_string($fillStyle) && array_key_exists($fillStyle, self::$fillStyleMap)) {
return self::$fillStyleMap[$fillStyle];
}
return self::$fillStyleMap[Fill::FILL_NONE];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls/Style/CellBorder.php | src/PhpSpreadsheet/Writer/Xls/Style/CellBorder.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls\Style;
use PhpOffice\PhpSpreadsheet\Style\Border;
class CellBorder
{
/**
* @var array<string, int>
*/
protected static array $styleMap = [
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,
Border::BORDER_OMIT => 0x00,
];
public static function style(Border $border): int
{
$borderStyle = $border->getBorderStyle();
if (array_key_exists($borderStyle, self::$styleMap)) {
return self::$styleMap[$borderStyle];
}
return self::$styleMap[Border::BORDER_NONE];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls/Style/CellAlignment.php | src/PhpSpreadsheet/Writer/Xls/Style/CellAlignment.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls\Style;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
class CellAlignment
{
/**
* @var array<string, int>
*/
private static array $horizontalMap = [
Alignment::HORIZONTAL_GENERAL => 0,
Alignment::HORIZONTAL_LEFT => 1,
Alignment::HORIZONTAL_RIGHT => 3,
Alignment::HORIZONTAL_CENTER => 2,
Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6,
Alignment::HORIZONTAL_JUSTIFY => 5,
];
/**
* @var array<string, int>
*/
private static array $verticalMap = [
Alignment::VERTICAL_BOTTOM => 2,
Alignment::VERTICAL_TOP => 0,
Alignment::VERTICAL_CENTER => 1,
Alignment::VERTICAL_JUSTIFY => 3,
];
public static function horizontal(Alignment $alignment): int
{
$horizontalAlignment = $alignment->getHorizontal();
if (is_string($horizontalAlignment) && array_key_exists($horizontalAlignment, self::$horizontalMap)) {
return self::$horizontalMap[$horizontalAlignment];
}
return self::$horizontalMap[Alignment::HORIZONTAL_GENERAL];
}
public static function wrap(Alignment $alignment): int
{
$wrap = $alignment->getWrapText();
return ($wrap === true) ? 1 : 0;
}
public static function vertical(Alignment $alignment): int
{
$verticalAlignment = $alignment->getVertical();
if (is_string($verticalAlignment) && array_key_exists($verticalAlignment, self::$verticalMap)) {
return self::$verticalMap[$verticalAlignment];
}
return self::$verticalMap[Alignment::VERTICAL_BOTTOM];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods/Styles.php | src/PhpSpreadsheet/Writer/Ods/Styles.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
class Styles extends WriterPart
{
/**
* Write styles.xml to XML format.
*
* @return string XML Output
*/
public function write(): string
{
$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->startElement('office:automatic-styles');
$objWriter->startElement('style:page-layout');
$objWriter->writeAttribute('style:name', 'Mpm1');
$objWriter->endElement(); // style:page-layout
$objWriter->endElement(); // office:automatic-styles
$objWriter->startElement('office:master-styles');
$objWriter->startElement('style:master-page');
$objWriter->writeAttribute('style:name', 'Default');
$objWriter->writeAttribute('style:page-layout-name', 'Mpm1');
$objWriter->endElement(); //style:master-page
$objWriter->endElement(); //office:master-styles
$objWriter->endElement();
return $objWriter->getData();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods/AutoFilters.php | src/PhpSpreadsheet/Writer/Ods/AutoFilters.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class AutoFilters
{
private XMLWriter $objWriter;
private Spreadsheet $spreadsheet;
public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet)
{
$this->objWriter = $objWriter;
$this->spreadsheet = $spreadsheet;
}
public function write(): void
{
$wrapperWritten = false;
$sheetCount = $this->spreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
$worksheet = $this->spreadsheet->getSheet($i);
$autofilter = $worksheet->getAutoFilter();
if (!empty($autofilter->getRange())) {
if ($wrapperWritten === false) {
$this->objWriter->startElement('table:database-ranges');
$wrapperWritten = true;
}
$this->objWriter->startElement('table:database-range');
$this->objWriter->writeAttribute('table:orientation', 'column');
$this->objWriter->writeAttribute('table:display-filter-buttons', 'true');
$this->objWriter->writeAttribute(
'table:target-range-address',
$this->formatRange($worksheet, $autofilter)
);
$this->objWriter->endElement();
}
}
if ($wrapperWritten === true) {
$this->objWriter->endElement();
}
}
protected function formatRange(Worksheet $worksheet, AutoFilter $autofilter): string
{
$title = $worksheet->getTitle();
$range = $autofilter->getRange();
return "'{$title}'.{$range}";
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods/Settings.php | src/PhpSpreadsheet/Writer/Ods/Settings.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use Composer\Pcre\Preg;
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class Settings extends WriterPart
{
/**
* Write settings.xml to XML format.
*
* @return string XML Output
*/
public function write(): string
{
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->startElement('config:config-item-map-entry');
$spreadsheet = $this->getParentWriter()->getSpreadsheet();
$objWriter->startElement('config:config-item');
$objWriter->writeAttribute('config:name', 'ViewId');
$objWriter->writeAttribute('config:type', 'string');
$objWriter->text('view1');
$objWriter->endElement(); // ViewId
$objWriter->startElement('config:config-item-map-named');
$this->writeAllWorksheetSettings($objWriter, $spreadsheet);
$wstitle = $spreadsheet->getActiveSheet()->getTitle();
$objWriter->startElement('config:config-item');
$objWriter->writeAttribute('config:name', 'ActiveTable');
$objWriter->writeAttribute('config:type', 'string');
$objWriter->text($wstitle);
$objWriter->endElement(); // config:config-item ActiveTable
$objWriter->endElement(); // config:config-item-map-entry
$objWriter->endElement(); // config:config-item-map-indexed Views
$objWriter->endElement(); // config:config-item-set ooo:view-settings
$objWriter->startElement('config:config-item-set');
$objWriter->writeAttribute('config:name', 'ooo:configuration-settings');
$objWriter->endElement(); // config:config-item-set ooo:configuration-settings
$objWriter->endElement(); // office:settings
$objWriter->endElement(); // office:document-settings
return $objWriter->getData();
}
private function writeAllWorksheetSettings(XMLWriter $objWriter, Spreadsheet $spreadsheet): void
{
$objWriter->writeAttribute('config:name', 'Tables');
foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
$this->writeWorksheetSettings($objWriter, $worksheet);
}
$objWriter->endElement(); // config:config-item-map-entry Tables
}
private function writeWorksheetSettings(XMLWriter $objWriter, Worksheet $worksheet): void
{
$objWriter->startElement('config:config-item-map-entry');
$objWriter->writeAttribute('config:name', $worksheet->getTitle());
$this->writeSelectedCells($objWriter, $worksheet);
$this->writeFreezePane($objWriter, $worksheet);
$objWriter->endElement(); // config:config-item-map-entry Worksheet
}
private function writeSelectedCells(XMLWriter $objWriter, Worksheet $worksheet): void
{
$selected = $worksheet->getSelectedCells();
if (Preg::isMatch('/^([a-z]+)([0-9]+)/i', $selected, $matches)) {
$colSel = Coordinate::columnIndexFromString($matches[1]) - 1;
$rowSel = (int) $matches[2] - 1;
$objWriter->startElement('config:config-item');
$objWriter->writeAttribute('config:name', 'CursorPositionX');
$objWriter->writeAttribute('config:type', 'int');
$objWriter->text((string) $colSel);
$objWriter->endElement();
$objWriter->startElement('config:config-item');
$objWriter->writeAttribute('config:name', 'CursorPositionY');
$objWriter->writeAttribute('config:type', 'int');
$objWriter->text((string) $rowSel);
$objWriter->endElement();
}
}
private function writeSplitValue(XMLWriter $objWriter, string $splitMode, string $type, string $value): void
{
$objWriter->startElement('config:config-item');
$objWriter->writeAttribute('config:name', $splitMode);
$objWriter->writeAttribute('config:type', $type);
$objWriter->text($value);
$objWriter->endElement();
}
private function writeFreezePane(XMLWriter $objWriter, Worksheet $worksheet): void
{
$freezePane = CellAddress::fromCellAddress($worksheet->getFreezePane() ?? 'A1');
if ($freezePane->cellAddress() === 'A1') {
return;
}
$columnId = $freezePane->columnId();
$columnName = $freezePane->columnName();
$row = $freezePane->rowId();
$this->writeSplitValue($objWriter, 'HorizontalSplitMode', 'short', '2');
$this->writeSplitValue($objWriter, 'HorizontalSplitPosition', 'int', (string) ($columnId - 1));
$this->writeSplitValue($objWriter, 'PositionLeft', 'short', '0');
$this->writeSplitValue($objWriter, 'PositionRight', 'short', (string) ($columnId - 1));
for ($column = 'A'; $column !== $columnName; StringHelper::stringIncrement($column)) {
$worksheet->getColumnDimension($column)->setAutoSize(true);
}
$this->writeSplitValue($objWriter, 'VerticalSplitMode', 'short', '2');
$this->writeSplitValue($objWriter, 'VerticalSplitPosition', 'int', (string) ($row - 1));
$this->writeSplitValue($objWriter, 'PositionTop', 'short', '0');
$this->writeSplitValue($objWriter, 'PositionBottom', 'short', (string) ($row - 1));
$this->writeSplitValue($objWriter, 'ActiveSplitRange', 'short', '3');
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods/Formula.php | src/PhpSpreadsheet/Writer/Ods/Formula.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use Composer\Pcre\Preg;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
class Formula
{
/** @var string[] */
private array $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);
$formula = $this->convertFunctionNames($formula);
if (!str_starts_with($formula, '=')) {
$formula = '=' . $formula;
}
return 'of:' . $formula;
}
private function convertDefinedNames(string $formula): string
{
$splitCount = Preg::matchAllWithOffsets(
'/' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '/mui',
$formula,
$splitRanges
);
$lengths = array_map([StringHelper::class, 'strlenAllowNull'], 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::matchAllWithOffsets(
'/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
$formula,
$splitRanges
);
$lengths = array_map([StringHelper::class, 'strlenAllowNull'], 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 semicolons 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::matchAllWithOffsets()
$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)) { // phpstan says always true
$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;
}
private function convertFunctionNames(string $formula): string
{
return Preg::replace(
[
'/\b((CEILING|FLOOR)'
. '([.](MATH|PRECISE))?)\s*[(]/ui',
'/\b(CEILING|FLOOR)[.]XCL\s*[(]/ui',
'/\b(CEILING|FLOOR)[.]ODS\s*[(]/ui',
],
[
'COM.MICROSOFT.$1(',
'COM.MICROSOFT.$1(',
'$1(',
],
$formula
);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods/MetaInf.php | src/PhpSpreadsheet/Writer/Ods/MetaInf.php | <?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 write(): string
{
$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();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php | src/PhpSpreadsheet/Writer/Ods/Thumbnails.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
class Thumbnails extends WriterPart
{
/**
* Write Thumbnails/thumbnail.png to PNG format.
*
* @return string XML Output
*/
public function write(): string
{
return '';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods/Meta.php | src/PhpSpreadsheet/Writer/Ods/Meta.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Document\Properties;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Meta extends WriterPart
{
/**
* Write meta.xml to XML format.
*
* @return string XML Output
*/
public function write(): string
{
$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());
$created = $spreadsheet->getProperties()->getCreated();
$date = Date::dateTimeFromTimestamp("$created");
$date->setTimeZone(Date::getDefaultOrLocalTimeZone());
$objWriter->writeElement('meta:creation-date', $date->format(DATE_W3C));
$created = $spreadsheet->getProperties()->getModified();
$date = Date::dateTimeFromTimestamp("$created");
$date->setTimeZone(Date::getDefaultOrLocalTimeZone());
$objWriter->writeElement('dc:date', $date->format(DATE_W3C));
$objWriter->writeElement('dc:title', $spreadsheet->getProperties()->getTitle());
$objWriter->writeElement('dc:description', $spreadsheet->getProperties()->getDescription());
$objWriter->writeElement('dc:subject', $spreadsheet->getProperties()->getSubject());
$objWriter->writeElement('meta:keyword', $spreadsheet->getProperties()->getKeywords());
// Don't know if this changed over time, but the keywords are all
// in a single declaration now.
//$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->writeRawData($spreadsheet->getProperties()->getCompany());
$objWriter->endElement();
$objWriter->startElement('meta:user-defined');
$objWriter->writeAttribute('meta:name', 'category');
$objWriter->writeRawData($spreadsheet->getProperties()->getCategory());
$objWriter->endElement();
self::writeDocPropsCustom($objWriter, $spreadsheet);
$objWriter->endElement();
$objWriter->endElement();
return $objWriter->getData();
}
private static function writeDocPropsCustom(XMLWriter $objWriter, Spreadsheet $spreadsheet): void
{
$customPropertyList = $spreadsheet->getProperties()->getCustomProperties();
foreach ($customPropertyList as $customProperty) {
$propertyValue = $spreadsheet->getProperties()->getCustomPropertyValue($customProperty);
$propertyType = $spreadsheet->getProperties()->getCustomPropertyType($customProperty);
$objWriter->startElement('meta:user-defined');
$objWriter->writeAttribute('meta:name', $customProperty);
switch ($propertyType) {
case Properties::PROPERTY_TYPE_INTEGER:
case Properties::PROPERTY_TYPE_FLOAT:
$objWriter->writeAttribute('meta:value-type', 'float');
$objWriter->writeRawData((string) $propertyValue);
break;
case Properties::PROPERTY_TYPE_BOOLEAN:
$objWriter->writeAttribute('meta:value-type', 'boolean');
$objWriter->writeRawData($propertyValue ? 'true' : 'false');
break;
case Properties::PROPERTY_TYPE_DATE:
$objWriter->writeAttribute('meta:value-type', 'date');
$dtobj = Date::dateTimeFromTimestamp((string) ($propertyValue ?? 0));
$objWriter->writeRawData($dtobj->format(DATE_W3C));
break;
default:
$objWriter->writeRawData((string) $propertyValue);
break;
}
$objWriter->endElement();
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods/Mimetype.php | src/PhpSpreadsheet/Writer/Ods/Mimetype.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
class Mimetype extends WriterPart
{
/**
* Write mimetype to plain text format.
*
* @return string XML Output
*/
public function write(): string
{
return 'application/vnd.oasis.opendocument.spreadsheet';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods/WriterPart.php | src/PhpSpreadsheet/Writer/Ods/WriterPart.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Writer\Ods;
abstract class WriterPart
{
/**
* Parent Ods object.
*/
private Ods $parentWriter;
/**
* Get Ods writer.
*/
public function getParentWriter(): Ods
{
return $this->parentWriter;
}
/**
* Set parent Ods writer.
*/
public function __construct(Ods $writer)
{
$this->parentWriter = $writer;
}
abstract public function write(): string;
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods/Content.php | src/PhpSpreadsheet/Writer/Ods/Content.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use Composer\Pcre\Preg;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalculationException;
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\Worksheet\RowCellIterator;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Comment;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Style;
/**
* @author Alexander Pervakov <frost-nzcr4@jagmort.com>
*/
class Content extends WriterPart
{
private Formula $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(): string
{
$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);
(new AutoFilters($objWriter, $this->getParentWriter()->getSpreadsheet()))->write();
// 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();
$sheetCount = $spreadsheet->getSheetCount();
for ($sheetIndex = 0; $sheetIndex < $sheetCount; ++$sheetIndex) {
$spreadsheet->getSheet($sheetIndex)->calculateArrays($this->getParentWriter()->getPreCalculateFormulas());
$objWriter->startElement('table:table');
$objWriter->writeAttribute('table:name', $spreadsheet->getSheet($sheetIndex)->getTitle());
$objWriter->writeAttribute('table:style-name', Style::TABLE_STYLE_PREFIX . (string) ($sheetIndex + 1));
$objWriter->writeElement('office:forms');
$lastColumn = 0;
foreach ($spreadsheet->getSheet($sheetIndex)->getColumnDimensions() as $columnDimension) {
$thisColumn = $columnDimension->getColumnNumeric();
$emptyColumns = $thisColumn - $lastColumn - 1;
if ($emptyColumns > 0) {
$objWriter->startElement('table:table-column');
$objWriter->writeAttribute('table:number-columns-repeated', (string) $emptyColumns);
$objWriter->endElement();
}
$lastColumn = $thisColumn;
$objWriter->startElement('table:table-column');
$objWriter->writeAttribute(
'table:style-name',
sprintf('%s_%d_%d', Style::COLUMN_STYLE_PREFIX, $sheetIndex, $columnDimension->getColumnNumeric())
);
$objWriter->writeAttribute('table:default-cell-style-name', 'ce0');
$objWriter->endElement();
}
$this->writeRows($objWriter, $spreadsheet->getSheet($sheetIndex), $sheetIndex);
$objWriter->endElement();
}
}
/**
* Write rows of the specified sheet.
*/
private function writeRows(XMLWriter $objWriter, Worksheet $sheet, int $sheetIndex): void
{
$spanRow = 0;
$rows = $sheet->getRowIterator();
foreach ($rows as $row) {
$cellIterator = $row->getCellIterator(iterateOnlyExistingCells: true);
$cellIterator->rewind();
$rowStyleExists = $sheet->rowDimensionExists($row->getRowIndex()) && $sheet->getRowDimension($row->getRowIndex())->getRowHeight() > 0;
if ($cellIterator->valid() || $rowStyleExists) {
if ($spanRow) {
$objWriter->startElement('table:table-row');
$objWriter->writeAttribute(
'table:number-rows-repeated',
(string) $spanRow
);
$objWriter->endElement();
$spanRow = 0;
}
$objWriter->startElement('table:table-row');
if ($rowStyleExists) {
$objWriter->writeAttribute(
'table:style-name',
sprintf('%s_%d_%d', Style::ROW_STYLE_PREFIX, $sheetIndex, $row->getRowIndex())
);
} elseif ($sheet->getDefaultRowDimension()->getRowHeight() > 0.0 && !$sheet->getRowDimension($row->getRowIndex())->getCustomFormat()) {
$objWriter->writeAttribute(
'table:style-name',
sprintf('%s%d', Style::ROW_STYLE_PREFIX, $sheetIndex)
);
}
$this->writeCells($objWriter, $cellIterator);
$objWriter->endElement();
} else {
++$spanRow;
}
}
}
/**
* Write cells of the specified row.
*/
private function writeCells(XMLWriter $objWriter, RowCellIterator $cells): void
{
$prevColumn = -1;
foreach ($cells as $cell) {
/** @var Cell $cell */
$column = Coordinate::columnIndexFromString($cell->getColumn()) - 1;
$attributes = $cell->getFormulaAttributes() ?? [];
$this->writeCellSpan($objWriter, $column, $prevColumn);
$objWriter->startElement('table:table-cell');
$this->writeCellMerge($objWriter, $cell);
// Style XF
$style = $cell->getXfIndex();
$objWriter->writeAttribute('table:style-name', Style::CELL_STYLE_PREFIX . $style);
switch ($cell->getDataType()) {
case DataType::TYPE_BOOL:
$objWriter->writeAttribute('office:value-type', 'boolean');
$objWriter->writeAttribute('office:boolean-value', $cell->getValue() ? 'true' : 'false');
$objWriter->writeElement('text:p', Calculation::getInstance()->getLocaleBoolean($cell->getValue() ? 'TRUE' : 'FALSE'));
break;
case DataType::TYPE_ERROR:
$objWriter->writeAttribute('table:formula', 'of:=#NULL!');
$objWriter->writeAttribute('office:value-type', 'string');
$objWriter->writeAttribute('office:string-value', '');
$objWriter->writeElement('text:p', '#NULL!');
break;
case DataType::TYPE_FORMULA:
$formulaValue = $cell->getValueString();
if ($this->getParentWriter()->getPreCalculateFormulas()) {
try {
$formulaValue = $cell->getCalculatedValueString();
} catch (CalculationException $e) {
// don't do anything
}
}
if (isset($attributes['ref'])) {
if (Preg::isMatch('/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/', (string) $attributes['ref'], $matches)) {
$matrixRowSpan = 1;
$matrixColSpan = 1;
if (isset($matches[3])) {
$minRow = (int) $matches[2];
$maxRow = (int) $matches[5];
$matrixRowSpan = $maxRow - $minRow + 1;
$minCol = Coordinate::columnIndexFromString($matches[1]);
$maxCol = Coordinate::columnIndexFromString($matches[4]);
$matrixColSpan = $maxCol - $minCol + 1;
}
$objWriter->writeAttribute('table:number-matrix-columns-spanned', "$matrixColSpan");
$objWriter->writeAttribute('table:number-matrix-rows-spanned', "$matrixRowSpan");
}
}
$objWriter->writeAttribute('table:formula', $this->formulaConvertor->convertFormula($cell->getValueString()));
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_NUMERIC:
$objWriter->writeAttribute('office:value-type', 'float');
$objWriter->writeAttribute('office:value', $cell->getValueString());
$objWriter->writeElement('text:p', $cell->getValueString());
break;
case DataType::TYPE_INLINE:
// break intentionally omitted
case DataType::TYPE_STRING:
$objWriter->writeAttribute('office:value-type', 'string');
$url = $cell->getHyperlink()->getUrl();
if (empty($url)) {
$objWriter->writeElement('text:p', $cell->getValueString());
} else {
$objWriter->startElement('text:p');
$objWriter->startElement('text:a');
$sheets = 'sheet://';
$lensheets = strlen($sheets);
if (substr($url, 0, $lensheets) === $sheets) {
$url = '#' . substr($url, $lensheets);
}
$objWriter->writeAttribute('xlink:href', $url);
$objWriter->writeAttribute('xlink:type', 'simple');
$objWriter->text($cell->getValueString());
$objWriter->endElement(); // text:a
$objWriter->endElement(); // text:p
}
break;
}
Comment::write($objWriter, $cell);
$objWriter->endElement();
$prevColumn = $column;
}
}
/**
* Write span.
*/
private function writeCellSpan(XMLWriter $objWriter, int $curColumn, int $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', (string) $diff);
$objWriter->endElement();
}
}
/**
* Write XF cell styles.
*/
private function writeXfStyles(XMLWriter $writer, Spreadsheet $spreadsheet): void
{
$styleWriter = new Style($writer);
$sheetCount = $spreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
$worksheet = $spreadsheet->getSheet($i);
$styleWriter->writeTableStyle($worksheet, $i + 1);
$worksheet->calculateColumnWidths();
foreach ($worksheet->getColumnDimensions() as $columnDimension) {
if ($columnDimension->getWidth() !== -1.0) {
$styleWriter->writeColumnStyles($columnDimension, $i);
}
}
}
for ($i = 0; $i < $sheetCount; ++$i) {
$worksheet = $spreadsheet->getSheet($i);
$default = $worksheet->getDefaultRowDimension();
if ($default->getRowHeight() > 0.0) {
$styleWriter->writeDefaultRowStyle($default, $i);
}
foreach ($worksheet->getRowDimensions() as $rowDimension) {
if ($rowDimension->getRowHeight() > 0.0) {
$styleWriter->writeRowStyles($rowDimension, $i);
}
}
}
foreach ($spreadsheet->getCellXfCollection() as $style) {
$styleWriter->write($style);
}
}
/**
* Write attributes for merged cell.
*/
private function writeCellMerge(XMLWriter $objWriter, Cell $cell): void
{
if (!$cell->isMergeRangeValueCell()) {
return;
}
$mergeRange = Coordinate::splitRange((string) $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 = ((int) $end[1]) - ((int) $start[1]) + 1;
$objWriter->writeAttribute('table:number-columns-spanned', (string) $columnSpan);
$objWriter->writeAttribute('table:number-rows-spanned', (string) $rowSpan);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php | src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use Composer\Pcre\Preg;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class NamedExpressions
{
private XMLWriter $objWriter;
private Spreadsheet $spreadsheet;
private Formula $formulaConvertor;
public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet, Formula $formulaConvertor)
{
$this->objWriter = $objWriter;
$this->spreadsheet = $spreadsheet;
$this->formulaConvertor = $formulaConvertor;
}
public function write(): string
{
$this->objWriter->startElement('table:named-expressions');
$this->writeExpressions();
$this->objWriter->endElement();
return '';
}
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
{
$title = ($definedName->getWorksheet() !== null) ? $definedName->getWorksheet()->getTitle() : $defaultWorksheet->getTitle();
$this->objWriter->writeAttribute('table:name', $definedName->getName());
$this->objWriter->writeAttribute(
'table:expression',
$this->formulaConvertor->convertFormula($definedName->getValue(), $title)
);
$this->objWriter->writeAttribute('table:base-cell-address', $this->convertAddress(
$definedName,
"'" . $title . "'!\$A\$1"
));
}
private function writeNamedRange(DefinedName $definedName): void
{
$baseCell = '$A$1';
$ws = $definedName->getWorksheet();
if ($ws !== null) {
$baseCell = "'" . $ws->getTitle() . "'!$baseCell";
}
$this->objWriter->writeAttribute('table:name', $definedName->getName());
$this->objWriter->writeAttribute('table:base-cell-address', $this->convertAddress(
$definedName,
$baseCell
));
$this->objWriter->writeAttribute('table:cell-range-address', $this->convertAddress($definedName, $definedName->getValue()));
}
private function convertAddress(DefinedName $definedName, string $address): string
{
$splitCount = Preg::matchAllWithOffsets(
'/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
$address,
$splitRanges
);
$lengths = array_map([StringHelper::class, 'strlenAllowNull'], 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
$ws = $definedName->getWorksheet();
if ($ws !== null) {
$worksheet = $ws->getTitle();
}
}
} else {
$worksheet = str_replace("''", "'", trim($worksheet, "'"));
}
if (!empty($worksheet)) {
$newRange = "'" . str_replace("'", "''", $worksheet) . "'.";
}
//if (!empty($column)) { // phpstan says always true
$newRange .= $column;
//}
if (!empty($row)) {
$newRange .= $row;
}
$address = substr($address, 0, $offset) . $newRange . substr($address, $offset + $length);
}
if (str_starts_with($address, '=')) {
$address = substr($address, 1);
}
return $address;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods/Cell/Comment.php | src/PhpSpreadsheet/Writer/Ods/Cell/Comment.php | <?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->startElement('text:p');
$text = $comment->getText()->getPlainText();
$textElements = explode("\n", $text);
$newLineOwed = false;
foreach ($textElements as $textSegment) {
if ($newLineOwed) {
$objWriter->writeElement('text:line-break');
}
$newLineOwed = true;
if ($textSegment !== '') {
$objWriter->writeElement('text:span', $textSegment);
}
}
$objWriter->endElement(); // text:p
$objWriter->endElement();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods/Cell/Style.php | src/PhpSpreadsheet/Writer/Ods/Cell/Style.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Ods\Cell;
use PhpOffice\PhpSpreadsheet\Helper\Dimension;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Borders;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Font;
use PhpOffice\PhpSpreadsheet\Style\Style as CellStyle;
use PhpOffice\PhpSpreadsheet\Worksheet\ColumnDimension;
use PhpOffice\PhpSpreadsheet\Worksheet\RowDimension;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class Style
{
public const CELL_STYLE_PREFIX = 'ce';
public const COLUMN_STYLE_PREFIX = 'co';
public const ROW_STYLE_PREFIX = 'ro';
public const TABLE_STYLE_PREFIX = 'ta';
public const INDENT_TO_INCHES = 0.1043; // undocumented, used trial and error
private XMLWriter $writer;
public function __construct(XMLWriter $writer)
{
$this->writer = $writer;
}
private function mapHorizontalAlignment(?string $horizontalAlignment): string
{
return match ($horizontalAlignment) {
Alignment::HORIZONTAL_CENTER, Alignment::HORIZONTAL_CENTER_CONTINUOUS, Alignment::HORIZONTAL_DISTRIBUTED => 'center',
Alignment::HORIZONTAL_RIGHT => 'end',
Alignment::HORIZONTAL_FILL, Alignment::HORIZONTAL_JUSTIFY => 'justify',
Alignment::HORIZONTAL_GENERAL, '', null => '',
default => 'start',
};
}
private function mapVerticalAlignment(string $verticalAlignment): string
{
return match ($verticalAlignment) {
Alignment::VERTICAL_TOP => 'top',
Alignment::VERTICAL_CENTER => 'middle',
Alignment::VERTICAL_DISTRIBUTED, Alignment::VERTICAL_JUSTIFY => 'automatic',
default => 'bottom',
};
}
private function writeFillStyle(Fill $fill): void
{
switch ($fill->getFillType()) {
case Fill::FILL_SOLID:
$this->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:
}
}
private function writeBordersStyle(Borders $borders): void
{
$this->writeBorderStyle('bottom', $borders->getBottom());
$this->writeBorderStyle('left', $borders->getLeft());
$this->writeBorderStyle('right', $borders->getRight());
$this->writeBorderStyle('top', $borders->getTop());
}
private function writeBorderStyle(string $direction, Border $border): void
{
if ($border->getBorderStyle() === Border::BORDER_NONE) {
return;
}
$this->writer->writeAttribute('fo:border-' . $direction, sprintf(
'%s %s #%s',
$this->mapBorderWidth($border),
$this->mapBorderStyle($border),
$border->getColor()->getRGB(),
));
}
private function mapBorderWidth(Border $border): string
{
switch ($border->getBorderStyle()) {
case Border::BORDER_THIN:
case Border::BORDER_DASHED:
case Border::BORDER_DASHDOT:
case Border::BORDER_DASHDOTDOT:
case Border::BORDER_DOTTED:
case Border::BORDER_HAIR:
return '0.75pt';
case Border::BORDER_MEDIUM:
case Border::BORDER_MEDIUMDASHED:
case Border::BORDER_MEDIUMDASHDOT:
case Border::BORDER_MEDIUMDASHDOTDOT:
case Border::BORDER_SLANTDASHDOT:
return '1.75pt';
case Border::BORDER_DOUBLE:
case Border::BORDER_THICK:
return '2.5pt';
}
return '1pt';
}
private function mapBorderStyle(Border $border): string
{
switch ($border->getBorderStyle()) {
case Border::BORDER_DOTTED:
case Border::BORDER_MEDIUMDASHDOTDOT:
return Border::BORDER_DOTTED;
case Border::BORDER_DASHED:
case Border::BORDER_DASHDOT:
case Border::BORDER_DASHDOTDOT:
case Border::BORDER_MEDIUMDASHDOT:
case Border::BORDER_MEDIUMDASHED:
case Border::BORDER_SLANTDASHDOT:
return Border::BORDER_DASHED;
case Border::BORDER_DOUBLE:
return Border::BORDER_DOUBLE;
case Border::BORDER_HAIR:
case Border::BORDER_MEDIUM:
case Border::BORDER_THICK:
case Border::BORDER_THIN:
return 'solid';
}
return 'solid';
}
private function writeCellProperties(CellStyle $style): void
{
// Align
$hAlign = $style->getAlignment()->getHorizontal();
$hAlign = $this->mapHorizontalAlignment($hAlign);
$vAlign = $style->getAlignment()->getVertical();
$wrap = $style->getAlignment()->getWrapText();
$indent = $style->getAlignment()->getIndent();
$readOrder = $style->getAlignment()->getReadOrder();
$this->writer->startElement('style:table-cell-properties');
if (!empty($vAlign) || $wrap) {
if (!empty($vAlign)) {
$vAlign = $this->mapVerticalAlignment($vAlign);
$this->writer->writeAttribute('style:vertical-align', $vAlign);
}
if ($wrap) {
$this->writer->writeAttribute('fo:wrap-option', 'wrap');
}
}
$this->writer->writeAttribute('style:rotation-align', 'none');
// Fill
$this->writeFillStyle($style->getFill());
// Border
$this->writeBordersStyle($style->getBorders());
$this->writer->endElement();
if ($hAlign !== '' || !empty($indent) || $readOrder === Alignment::READORDER_RTL || $readOrder === Alignment::READORDER_LTR) {
$this->writer
->startElement('style:paragraph-properties');
if ($hAlign !== '') {
$this->writer->writeAttribute('fo:text-align', $hAlign);
}
if (!empty($indent)) {
$indentString = sprintf('%.4f', $indent * self::INDENT_TO_INCHES) . 'in';
$this->writer->writeAttribute('fo:margin-left', $indentString);
}
if ($readOrder === Alignment::READORDER_RTL) {
$this->writer->writeAttribute('style:writing-mode', 'rl-tb');
} elseif ($readOrder === Alignment::READORDER_LTR) {
$this->writer->writeAttribute('style:writing-mode', 'lr-tb');
}
$this->writer->endElement();
}
}
protected function mapUnderlineStyle(Font $font): string
{
return match ($font->getUnderline()) {
Font::UNDERLINE_DOUBLE, Font::UNDERLINE_DOUBLEACCOUNTING => 'double',
Font::UNDERLINE_SINGLE, Font::UNDERLINE_SINGLEACCOUNTING => 'single',
default => 'none',
};
}
protected function writeTextProperties(CellStyle $style): void
{
// Font
$this->writer->startElement('style:text-properties');
$font = $style->getFont();
if ($font->getBold()) {
$this->writer->writeAttribute('fo:font-weight', 'bold');
$this->writer->writeAttribute(
'style:font-weight-complex',
'bold'
);
$this->writer->writeAttribute(
'style:font-weight-asian',
'bold'
);
}
if ($font->getItalic()) {
$this->writer->writeAttribute('fo:font-style', 'italic');
}
if ($font->getAutoColor()) {
$this->writer
->writeAttribute('style:use-window-font-color', 'true');
} else {
$this->writer->writeAttribute('fo:color', sprintf('#%s', $font->getColor()->getRGB()));
}
if ($family = $font->getName()) {
$this->writer->writeAttribute('fo:font-family', $family);
}
if ($size = $font->getSize()) {
$this->writer->writeAttribute('fo:font-size', sprintf('%.1Fpt', $size));
}
if ($font->getUnderline() && $font->getUnderline() !== Font::UNDERLINE_NONE) {
$this->writer->writeAttribute('style:text-underline-style', 'solid');
$this->writer->writeAttribute('style:text-underline-width', 'auto');
$this->writer->writeAttribute('style:text-underline-color', 'font-color');
$underline = $this->mapUnderlineStyle($font);
$this->writer->writeAttribute('style:text-underline-type', $underline);
}
$this->writer->endElement(); // Close style:text-properties
}
protected function writeColumnProperties(ColumnDimension $columnDimension): void
{
$this->writer->startElement('style:table-column-properties');
$this->writer->writeAttribute(
'style:column-width',
round($columnDimension->getWidth(Dimension::UOM_CENTIMETERS), 3) . 'cm'
);
$this->writer->writeAttribute('fo:break-before', 'auto');
// End
$this->writer->endElement(); // Close style:table-column-properties
}
public function writeColumnStyles(ColumnDimension $columnDimension, int $sheetId): void
{
$this->writer->startElement('style:style');
$this->writer->writeAttribute('style:family', 'table-column');
$this->writer->writeAttribute(
'style:name',
sprintf('%s_%d_%d', self::COLUMN_STYLE_PREFIX, $sheetId, $columnDimension->getColumnNumeric())
);
$this->writeColumnProperties($columnDimension);
// End
$this->writer->endElement(); // Close style:style
}
protected function writeRowProperties(RowDimension $rowDimension): void
{
$this->writer->startElement('style:table-row-properties');
$this->writer->writeAttribute(
'style:row-height',
round($rowDimension->getRowHeight(Dimension::UOM_CENTIMETERS), 3) . 'cm'
);
$this->writer->writeAttribute('style:use-optimal-row-height', 'false');
$this->writer->writeAttribute('fo:break-before', 'auto');
// End
$this->writer->endElement(); // Close style:table-row-properties
}
public function writeRowStyles(RowDimension $rowDimension, int $sheetId): void
{
$this->writer->startElement('style:style');
$this->writer->writeAttribute('style:family', 'table-row');
$this->writer->writeAttribute(
'style:name',
sprintf('%s_%d_%d', self::ROW_STYLE_PREFIX, $sheetId, $rowDimension->getRowIndex())
);
$this->writeRowProperties($rowDimension);
// End
$this->writer->endElement(); // Close style:style
}
public function writeDefaultRowStyle(RowDimension $rowDimension, int $sheetId): void
{
$this->writer->startElement('style:style');
$this->writer->writeAttribute('style:family', 'table-row');
$this->writer->writeAttribute(
'style:name',
sprintf('%s%d', self::ROW_STYLE_PREFIX, $sheetId)
);
$this->writeRowProperties($rowDimension);
// End
$this->writer->endElement(); // Close style:style
}
public function writeTableStyle(Worksheet $worksheet, int $sheetId): void
{
$this->writer->startElement('style:style');
$this->writer->writeAttribute('style:family', 'table');
$this->writer->writeAttribute(
'style:name',
sprintf('%s%d', self::TABLE_STYLE_PREFIX, $sheetId)
);
$this->writer->writeAttribute('style:master-page-name', 'Default');
$this->writer->startElement('style:table-properties');
$this->writer->writeAttribute(
'table:display',
$worksheet->getSheetState() === Worksheet::SHEETSTATE_VISIBLE ? 'true' : 'false'
);
$this->writer->endElement(); // Close style:table-properties
$this->writer->endElement(); // Close style:style
}
public function write(CellStyle $style): void
{
$this->writer->startElement('style:style');
$this->writer->writeAttribute('style:name', self::CELL_STYLE_PREFIX . $style->getIndex());
$this->writer->writeAttribute('style:family', 'table-cell');
$this->writer->writeAttribute('style:parent-style-name', 'Default');
// Alignment, fill colour, etc
$this->writeCellProperties($style);
// style:text-properties
$this->writeTextProperties($style);
// End
$this->writer->endElement(); // Close style:style
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php | src/PhpSpreadsheet/Writer/Pdf/Dompdf.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Pdf;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Writer\Pdf;
class Dompdf extends Pdf
{
/**
* embed images, or link to images.
*/
protected bool $embedImages = true;
/**
* Gets the implementation of external PDF library that should be used.
*
* @return \Dompdf\Dompdf implementation
*/
protected function createExternalWriterInstance(): \Dompdf\Dompdf
{
return new \Dompdf\Dompdf();
}
/**
* Save Spreadsheet to file.
*
* @param string $filename Name of the file to save as
*/
public function save($filename, int $flags = 0): void
{
$fileHandle = parent::prepareForSave($filename);
// Check for paper size and page orientation
$setup = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageSetup();
$orientation = $this->getOrientation() ?? $setup->getOrientation();
$orientation = ($orientation === PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
$printPaperSize = $this->getPaperSize() ?? $setup->getPaperSize();
$paperSize = self::$paperSizes[$printPaperSize] ?? self::$paperSizes[PageSetup::getPaperSizeDefault()] ?? 'LETTER';
if (is_array($paperSize) && count($paperSize) === 2) {
$paperSize = [0.0, 0.0, $paperSize[0], $paperSize[1]];
}
$orientation = ($orientation == 'L') ? 'landscape' : 'portrait';
// Create PDF
$pdf = $this->createExternalWriterInstance();
$pdf->setPaper($paperSize, $orientation);
$pdf->loadHtml($this->generateHTMLAll());
$pdf->render();
// Write to file
fwrite($fileHandle, $pdf->output());
parent::restoreStateAfterSave();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Pdf/TcpdfNoDie.php | src/PhpSpreadsheet/Writer/Pdf/TcpdfNoDie.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Pdf;
class TcpdfNoDie extends Tcpdf
{
/**
* By default, Tcpdf will die sometimes rather than throwing exception.
* And this is controlled by a defined constant in the global namespace,
* not by an instance property. Ugh!
* Using this class instead of the class which it extends will probably
* be suitable for most users. But not for those who have customized
* their config file. Which is why this isn't the default, so that
* there is no breaking change for those users.
* Note that if both Tcpdf and TcpdfNoDie are used in the same process,
* the first one used "wins" the battle of the defines.
*/
protected function defines(): void
{
if (!defined('K_TCPDF_EXTERNAL_CONFIG')) {
define('K_TCPDF_EXTERNAL_CONFIG', true);
}
if (!defined('K_TCPDF_THROW_EXCEPTION_ERROR')) {
define('K_TCPDF_THROW_EXCEPTION_ERROR', true);
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php | src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php | <?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 float[]|string $paperSize Paper size
*
* @return \TCPDF implementation
*/
protected function createExternalWriterInstance(string $orientation, string $unit, $paperSize): \TCPDF
{
$this->defines();
return new \TCPDF($orientation, $unit, $paperSize);
}
protected function defines(): void
{
}
/**
* Save Spreadsheet to file.
*
* @param string $filename Name of the file to save as
*/
public function save($filename, int $flags = 0): void
{
$fileHandle = parent::prepareForSave($filename);
// Default PDF paper size
$paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.)
// Check for paper size and page orientation
$setup = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageSetup();
$orientation = $this->getOrientation() ?? $setup->getOrientation();
$orientation = ($orientation === PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
$printPaperSize = $this->getPaperSize() ?? $setup->getPaperSize();
$paperSize = self::$paperSizes[$printPaperSize] ?? self::$paperSizes[PageSetup::getPaperSizeDefault()] ?? 'LETTER';
$printMargins = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageMargins();
// 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());
$this->checkRtlAndLtr();
if ($this->rtlSheets && !$this->ltrSheets) {
$pdf->setRTL(true);
}
$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('', 'S'));
parent::restoreStateAfterSave();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php | src/PhpSpreadsheet/Writer/Pdf/Mpdf.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Pdf;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Writer\Pdf;
class Mpdf extends Pdf
{
public const SIMULATED_BODY_START = '<!-- simulated body start -->';
private const BODY_TAG = '<body>';
/**
* Gets the implementation of external PDF library that should be used.
*
* @param mixed[] $config Configuration array
*
* @return \Mpdf\Mpdf implementation
*/
protected function createExternalWriterInstance(array $config): \Mpdf\Mpdf
{
return new \Mpdf\Mpdf($config);
}
/**
* Save Spreadsheet to file.
*
* @param string $filename Name of the file to save as
*/
public function save($filename, int $flags = 0): void
{
$fileHandle = parent::prepareForSave($filename);
// Check for paper size and page orientation
$setup = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageSetup();
$orientation = $this->getOrientation() ?? $setup->getOrientation();
$orientation = ($orientation === PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
$printPaperSize = $this->getPaperSize() ?? $setup->getPaperSize();
$paperSize = self::$paperSizes[$printPaperSize] ?? PageSetup::getPaperSizeDefault();
// Create PDF
$config = ['tempDir' => $this->tempDir . '/mpdf'];
$pdf = $this->createExternalWriterInstance($config);
$ortmp = $orientation;
$pdf->_setPageSize($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();
$bodyLocation = strpos($html, self::SIMULATED_BODY_START);
if ($bodyLocation === false) {
$bodyLocation = strpos($html, self::BODY_TAG);
if ($bodyLocation !== false) {
$bodyLocation += strlen(self::BODY_TAG);
}
}
// Make sure first data presented to Mpdf includes body tag
// (and any htmlpageheader/htmlpagefooter tags)
// so that Mpdf doesn't parse it as content. Issue 2432.
if ($bodyLocation !== false) {
$pdf->WriteHTML(substr($html, 0, $bodyLocation));
$html = substr($html, $bodyLocation);
}
foreach (explode("\n", $html) as $line) {
$pdf->WriteHTML("$line\n");
}
// Write to file
/** @var string */
$str = $pdf->Output('', 'S');
fwrite($fileHandle, $str);
parent::restoreStateAfterSave();
}
/**
* Convert inches to mm.
*/
private function inchesToMm(float $inches): float
{
return $inches * 25.4;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php | src/PhpSpreadsheet/Writer/Xlsx/Workbook.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
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 $preCalculateFormulas If true, formulas will be calculated before writing
* @param ?bool $forceFullCalc If null, !$preCalculateFormulas
*
* @return string XML Output
*/
public function writeWorkbook(Spreadsheet $spreadsheet, bool $preCalculateFormulas = false, ?bool $forceFullCalc = null): string
{
// 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('xmlns', Namespaces::MAIN);
$objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT);
// fileVersion
$this->writeFileVersion($objWriter);
// workbookPr
$this->writeWorkbookPr($objWriter, $spreadsheet);
// 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, $preCalculateFormulas, $forceFullCalc);
$objWriter->endElement();
// Return
return $objWriter->getData();
}
/**
* Write file version.
*/
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.
*/
private function writeWorkbookPr(XMLWriter $objWriter, Spreadsheet $spreadsheet): void
{
$objWriter->startElement('workbookPr');
if ($spreadsheet->getExcelCalendar() === Date::CALENDAR_MAC_1904) {
$objWriter->writeAttribute('date1904', '1');
}
$objWriter->writeAttribute('codeName', 'ThisWorkbook');
$objWriter->endElement();
}
/**
* Write BookViews.
*/
private function writeBookViews(XMLWriter $objWriter, Spreadsheet $spreadsheet): void
{
// bookViews
$objWriter->startElement('bookViews');
// workbookView
$objWriter->startElement('workbookView');
$objWriter->writeAttribute('activeTab', (string) $spreadsheet->getActiveSheetIndex());
$objWriter->writeAttribute('autoFilterDateGrouping', ($spreadsheet->getAutoFilterDateGrouping() ? 'true' : 'false'));
$objWriter->writeAttribute('firstSheet', (string) $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', (string) $spreadsheet->getTabRatio());
$objWriter->writeAttribute('visibility', $spreadsheet->getVisibility());
$objWriter->endElement();
$objWriter->endElement();
}
/**
* Write WorkbookProtection.
*/
private function writeWorkbookProtection(XMLWriter $objWriter, Spreadsheet $spreadsheet): void
{
$security = $spreadsheet->getSecurity();
if ($security->isSecurityEnabled()) {
$objWriter->startElement('workbookProtection');
$objWriter->writeAttribute('lockRevision', ($security->getLockRevision() ? 'true' : 'false'));
$objWriter->writeAttribute('lockStructure', ($security->getLockStructure() ? 'true' : 'false'));
$objWriter->writeAttribute('lockWindows', ($security->getLockWindows() ? 'true' : 'false'));
if ($security->getRevisionsPassword() !== '') {
$objWriter->writeAttribute('revisionsPassword', $security->getRevisionsPassword());
} else {
$hashValue = $security->getRevisionsHashValue();
if ($hashValue !== '') {
$objWriter->writeAttribute('revisionsAlgorithmName', $security->getRevisionsAlgorithmName());
$objWriter->writeAttribute('revisionsHashValue', $hashValue);
$objWriter->writeAttribute('revisionsSaltValue', $security->getRevisionsSaltValue());
$objWriter->writeAttribute('revisionsSpinCount', (string) $security->getRevisionsSpinCount());
}
}
if ($security->getWorkbookPassword() !== '') {
$objWriter->writeAttribute('workbookPassword', $security->getWorkbookPassword());
} else {
$hashValue = $security->getWorkbookHashValue();
if ($hashValue !== '') {
$objWriter->writeAttribute('workbookAlgorithmName', $security->getWorkbookAlgorithmName());
$objWriter->writeAttribute('workbookHashValue', $hashValue);
$objWriter->writeAttribute('workbookSaltValue', $security->getWorkbookSaltValue());
$objWriter->writeAttribute('workbookSpinCount', (string) $security->getWorkbookSpinCount());
}
}
$objWriter->endElement();
}
}
/**
* Write calcPr.
*
* @param bool $preCalculateFormulas If true, formulas will be calculated before writing
*/
private function writeCalcPr(XMLWriter $objWriter, bool $preCalculateFormulas, ?bool $forceFullCalc): 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 will calculate before writing
$objWriter->writeAttribute('calcCompleted', ($preCalculateFormulas) ? '1' : '0');
$objWriter->writeAttribute('fullCalcOnLoad', ($preCalculateFormulas) ? '0' : '1');
if ($forceFullCalc === null) {
$objWriter->writeAttribute('forceFullCalc', $preCalculateFormulas ? '0' : '1');
} else {
$objWriter->writeAttribute('forceFullCalc', $forceFullCalc ? '1' : '0');
}
$objWriter->endElement();
}
/**
* Write sheets.
*/
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 string $worksheetName Sheet name
* @param int $worksheetId Sheet id
* @param int $relId Relationship ID
* @param string $sheetState Sheet state (visible, hidden, veryHidden)
*/
private function writeSheet(XMLWriter $objWriter, string $worksheetName, int $worksheetId = 1, int $relId = 1, string $sheetState = 'visible'): void
{
if ($worksheetName != '') {
// Write sheet
$objWriter->startElement('sheet');
$objWriter->writeAttribute('name', $worksheetName);
$objWriter->writeAttribute('sheetId', (string) $worksheetId);
if ($sheetState !== 'visible' && $sheetState != '') {
$objWriter->writeAttribute('state', $sheetState);
}
$objWriter->writeAttribute('r:id', 'rId' . $relId);
$objWriter->endElement();
} else {
throw new WriterException('Invalid parameters passed.');
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/Rels.php | src/PhpSpreadsheet/Writer/Xlsx/Rels.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Composer\Pcre\Preg;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing;
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): string
{
// 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', Namespaces::RELATIONSHIPS);
$customPropertyList = $spreadsheet->getProperties()->getCustomProperties();
if (!empty($customPropertyList)) {
// Relationship docProps/app.xml
$this->writeRelationship(
$objWriter,
4,
Namespaces::RELATIONSHIPS_CUSTOM_PROPERTIES,
'docProps/custom.xml'
);
}
// Relationship docProps/app.xml
$this->writeRelationship(
$objWriter,
3,
Namespaces::RELATIONSHIPS_EXTENDED_PROPERTIES,
'docProps/app.xml'
);
// Relationship docProps/core.xml
$this->writeRelationship(
$objWriter,
2,
Namespaces::CORE_PROPERTIES,
'docProps/core.xml'
);
// Relationship xl/workbook.xml
$this->writeRelationship(
$objWriter,
1,
Namespaces::OFFICE_DOCUMENT,
'xl/workbook.xml'
);
// a custom UI in workbook ?
$target = $spreadsheet->getRibbonXMLData('target');
if ($spreadsheet->hasRibbon()) {
$this->writeRelationShip(
$objWriter,
5,
Namespaces::EXTENSIBILITY,
is_string($target) ? $target : ''
);
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write workbook relationships to XML format.
*
* @return string XML Output
*/
public function writeWorkbookRelationships(Spreadsheet $spreadsheet): string
{
// 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', Namespaces::RELATIONSHIPS);
// Relationship styles.xml
$this->writeRelationship(
$objWriter,
1,
Namespaces::STYLES,
'styles.xml'
);
// Relationship theme/theme1.xml
$this->writeRelationship(
$objWriter,
2,
Namespaces::THEME2,
'theme/theme1.xml'
);
// Relationship sharedStrings.xml
$this->writeRelationship(
$objWriter,
3,
Namespaces::SHARED_STRINGS,
'sharedStrings.xml'
);
// Relationships with sheets
$sheetCount = $spreadsheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$i) {
$this->writeRelationship(
$objWriter,
($i + 1 + 3),
Namespaces::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),
Namespaces::VBA,
'vbaProject.bin'
);
++$i; //increment i if needed for another relation
}
// Metadata needed for Dynamic Arrays
if ($this->getParentWriter()->useDynamicArrays()) {
$this->writeRelationShip(
$objWriter,
($i + 1 + 3),
Namespaces::RELATIONSHIPS_METADATA,
'metadata.xml'
);
++$i; //increment i if needed for another relation
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write worksheet relationships to XML format.
*
* Numbering is as follows:
* rId1 - Drawings
* rId_hyperlink_x - Hyperlinks
*
* @param bool $includeCharts Flag indicating if we should write charts
* @param int $tableRef Table ID
* @param string[] $zipContent
*
* @return string XML Output
*/
public function writeWorksheetRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, int $worksheetId = 1, bool $includeCharts = false, int $tableRef = 1, array &$zipContent = []): string
{
// 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', Namespaces::RELATIONSHIPS);
// Write drawing relationships?
$drawingOriginalIds = [];
/** @var string[][][][] */
$unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData();
if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) {
$drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'];
}
if ($includeCharts) {
$charts = $worksheet->getChartCollection();
} else {
$charts = [];
}
if (($worksheet->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($relPath, $drawingOriginalIds[$relPath])) {
$rId = (int) (substr($drawingOriginalIds[$relPath], 3));
}
// Generate new $relPath to write drawing relationship
$relPath = '../drawings/drawing' . $worksheetId . '.xml';
$this->writeRelationship(
$objWriter,
$rId,
Namespaces::RELATIONSHIPS_DRAWING,
$relPath
);
}
$backgroundImage = $worksheet->getBackgroundImage();
if ($backgroundImage !== '') {
$rId = 'Bg';
$uniqueName = md5(mt_rand(0, 9999) . time() . mt_rand(0, 9999));
$relPath = "../media/$uniqueName." . $worksheet->getBackgroundExtension();
$this->writeRelationship(
$objWriter,
$rId,
Namespaces::IMAGE,
$relPath
);
$zipContent["xl/media/$uniqueName." . $worksheet->getBackgroundExtension()] = $backgroundImage;
}
// Write hyperlink relationships?
$i = 1;
foreach ($worksheet->getHyperlinkCollection() as $hyperlink) {
if (!$hyperlink->isInternal()) {
$this->writeRelationship(
$objWriter,
'_hyperlink_' . $i,
Namespaces::HYPERLINK,
$hyperlink->getUrl(),
'External'
);
++$i;
}
}
// Write comments relationship?
$i = 1;
if (count($worksheet->getComments()) > 0 || isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing'])) {
$this->writeRelationship(
$objWriter,
'_comments_vml' . $i,
Namespaces::VML,
'../drawings/vmlDrawing' . $worksheetId . '.vml'
);
}
if (count($worksheet->getComments()) > 0) {
$this->writeRelationship(
$objWriter,
'_comments' . $i,
Namespaces::COMMENTS,
'../comments' . $worksheetId . '.xml'
);
}
// Write Table
$tableCount = $worksheet->getTableCollection()->count();
for ($i = 1; $i <= $tableCount; ++$i) {
$this->writeRelationship(
$objWriter,
'_table_' . $i,
Namespaces::RELATIONSHIPS_TABLE,
'../tables/table' . $tableRef++ . '.xml'
);
}
// Write header/footer relationship?
$i = 1;
if (count($worksheet->getHeaderFooter()->getImages()) > 0) {
$this->writeRelationship(
$objWriter,
'_headerfooter_vml' . $i,
Namespaces::VML,
'../drawings/vmlDrawingHF' . $worksheetId . '.vml'
);
}
$this->writeUnparsedRelationship($worksheet, $objWriter, 'ctrlProps', Namespaces::RELATIONSHIPS_CTRLPROP);
$this->writeUnparsedRelationship($worksheet, $objWriter, 'vmlDrawings', Namespaces::VML);
$this->writeUnparsedRelationship($worksheet, $objWriter, 'printerSettings', Namespaces::RELATIONSHIPS_PRINTER_SETTINGS);
$objWriter->endElement();
return $objWriter->getData();
}
private function writeUnparsedRelationship(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, XMLWriter $objWriter, string $relationship, string $type): void
{
/** @var mixed[][][][] */
$unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData();
if (!isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()][$relationship])) {
return;
}
foreach ($unparsedLoadedData['sheets'][$worksheet->getCodeName()][$relationship] as $rId => $value) {
if (!str_starts_with($rId, '_headerfooter_vml')) {
/** @var string[] $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 $worksheet, int &$chartRef, bool $includeCharts = false): string
{
// Check if we should use pass-through relationships
$passThroughRels = $this->getPassThroughDrawingRelationships($worksheet);
if ($passThroughRels !== null) {
return $passThroughRels;
}
// 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', Namespaces::RELATIONSHIPS);
// Loop through images and write relationships
$i = 1;
$iterator = $worksheet->getDrawingCollection()->getIterator();
while ($iterator->valid()) {
$drawing = $iterator->current();
if (
$drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\Drawing
|| $drawing instanceof MemoryDrawing
) {
// Write relationship for image drawing
$this->writeRelationship(
$objWriter,
$i,
Namespaces::IMAGE,
'../media/' . $drawing->getIndexedFilename()
);
$i = $this->writeDrawingHyperLink($objWriter, $drawing, $i);
}
$iterator->next();
++$i;
}
if ($includeCharts) {
// Loop through charts and write relationships
$chartCount = $worksheet->getChartCount();
if ($chartCount > 0) {
for ($c = 0; $c < $chartCount; ++$c) {
$this->writeRelationship(
$objWriter,
$i++,
Namespaces::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 $worksheet): string
{
// 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', Namespaces::RELATIONSHIPS);
// Loop through images and write relationships
foreach ($worksheet->getHeaderFooter()->getImages() as $key => $value) {
// Write relationship for image drawing
$this->writeRelationship(
$objWriter,
$key,
Namespaces::IMAGE,
'../media/' . $value->getIndexedFilename()
);
}
$objWriter->endElement();
return $objWriter->getData();
}
public function writeVMLDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet): string
{
// 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', Namespaces::RELATIONSHIPS);
// Loop through images and write relationships
foreach ($worksheet->getComments() as $comment) {
if (!$comment->hasBackgroundImage()) {
continue;
}
$bgImage = $comment->getBackgroundImage();
$this->writeRelationship(
$objWriter,
$bgImage->getImageIndex(),
Namespaces::IMAGE,
'../media/' . $bgImage->getMediaFilename()
);
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write Override content type.
*
* @param int|string $id Relationship ID. rId will be prepended!
* @param string $type Relationship type
* @param string $target Relationship target
* @param string $targetMode Relationship target mode
*/
private function writeRelationship(XMLWriter $objWriter, $id, string $type, string $target, string $targetMode = ''): void
{
if ($type != '' && $target != '') {
// Write relationship
$objWriter->startElement('Relationship');
$objWriter->writeAttribute('Id', 'rId' . $id);
$objWriter->writeAttribute('Type', $type);
$objWriter->writeAttribute('Target', $target);
if ($targetMode != '') {
$objWriter->writeAttribute('TargetMode', $targetMode);
}
$objWriter->endElement();
} else {
throw new WriterException('Invalid parameters passed.');
}
}
private function writeDrawingHyperLink(XMLWriter $objWriter, BaseDrawing $drawing, int $i): int
{
if ($drawing->getHyperlink() === null) {
return $i;
}
++$i;
$this->writeRelationship(
$objWriter,
$i,
Namespaces::HYPERLINK,
Preg::replace('~^sheet://~', '#', $drawing->getHyperlink()->getUrl()),
$drawing->getHyperlink()->getTypeHyperlink()
);
return $i;
}
/**
* Get pass-through drawing relationships XML if available.
*
* Note: When pass-through is used, the original relationships are returned as-is.
* This means any drawings (images, charts, shapes) added programmatically after
* loading will not be included in the relationships. This is a known limitation
* when combining pass-through with drawing modifications.
*/
private function getPassThroughDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet): ?string
{
/** @var array<string, array<string, mixed>> $sheets */
$sheets = $worksheet->getParentOrThrow()->getUnparsedLoadedData()['sheets'] ?? [];
$sheetData = $sheets[$worksheet->getCodeName()] ?? [];
if (($sheetData['drawingPassThroughEnabled'] ?? false) !== true || !is_string($sheetData['drawingRelationships'] ?? null)) {
return null;
}
return $sheetData['drawingRelationships'];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php | src/PhpSpreadsheet/Writer/Xlsx/Drawing.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Composer\Pcre\Preg;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing;
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 $worksheet, bool $includeCharts = false): string
{
// Try to use pass-through drawing XML if available
if ($passThroughXml = $this->getPassThroughDrawingXml($worksheet)) {
return $passThroughXml;
}
// 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', Namespaces::SPREADSHEET_DRAWING);
$objWriter->writeAttribute('xmlns:a', Namespaces::DRAWINGML);
// Loop through images and write drawings
$i = 1;
$iterator = $worksheet->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 = $worksheet->getChartCount();
// Loop through charts and write the chart position
if ($chartCount > 0) {
for ($c = 0; $c < $chartCount; ++$c) {
$chart = $worksheet->getChartByIndex((string) $c);
if ($chart !== false) {
$this->writeChart($objWriter, $chart, $c + $i);
}
}
}
}
// unparsed AlternateContent
/** @var string[][][][] */
$unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData();
if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingAlternateContents'])) {
foreach ($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingAlternateContents'] as $drawingAlternateContent) {
$objWriter->writeRaw($drawingAlternateContent);
}
}
$objWriter->endElement();
// Return
return $objWriter->getData();
}
/**
* Write drawings to XML format.
*/
public function writeChart(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Chart\Chart $chart, int $relationId = -1): void
{
$tl = $chart->getTopLeftPosition();
$tlColRow = Coordinate::indexesFromString($tl['cell']);
$br = $chart->getBottomRightPosition();
$isTwoCellAnchor = $br['cell'] !== '';
if ($isTwoCellAnchor) {
$brColRow = Coordinate::indexesFromString($br['cell']);
$objWriter->startElement('xdr:twoCellAnchor');
$objWriter->startElement('xdr:from');
$objWriter->writeElement('xdr:col', (string) ($tlColRow[0] - 1));
$objWriter->writeElement('xdr:colOff', self::stringEmu($tl['xOffset']));
$objWriter->writeElement('xdr:row', (string) ($tlColRow[1] - 1));
$objWriter->writeElement('xdr:rowOff', self::stringEmu($tl['yOffset']));
$objWriter->endElement();
$objWriter->startElement('xdr:to');
$objWriter->writeElement('xdr:col', (string) ($brColRow[0] - 1));
$objWriter->writeElement('xdr:colOff', self::stringEmu($br['xOffset']));
$objWriter->writeElement('xdr:row', (string) ($brColRow[1] - 1));
$objWriter->writeElement('xdr:rowOff', self::stringEmu($br['yOffset']));
$objWriter->endElement();
} elseif ($chart->getOneCellAnchor()) {
$objWriter->startElement('xdr:oneCellAnchor');
$objWriter->startElement('xdr:from');
$objWriter->writeElement('xdr:col', (string) ($tlColRow[0] - 1));
$objWriter->writeElement('xdr:colOff', self::stringEmu($tl['xOffset']));
$objWriter->writeElement('xdr:row', (string) ($tlColRow[1] - 1));
$objWriter->writeElement('xdr:rowOff', self::stringEmu($tl['yOffset']));
$objWriter->endElement();
$objWriter->startElement('xdr:ext');
$objWriter->writeAttribute('cx', self::stringEmu($br['xOffset']));
$objWriter->writeAttribute('cy', self::stringEmu($br['yOffset']));
$objWriter->endElement();
} else {
$objWriter->startElement('xdr:absoluteAnchor');
$objWriter->startElement('xdr:pos');
$objWriter->writeAttribute('x', '0');
$objWriter->writeAttribute('y', '0');
$objWriter->endElement();
$objWriter->startElement('xdr:ext');
$objWriter->writeAttribute('cx', self::stringEmu($br['xOffset']));
$objWriter->writeAttribute('cy', self::stringEmu($br['yOffset']));
$objWriter->endElement();
}
$objWriter->startElement('xdr:graphicFrame');
$objWriter->writeAttribute('macro', '');
$objWriter->startElement('xdr:nvGraphicFramePr');
$objWriter->startElement('xdr:cNvPr');
$objWriter->writeAttribute('name', 'Chart ' . $relationId);
$objWriter->writeAttribute('id', (string) (1025 * $relationId));
$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', Namespaces::CHART);
$objWriter->startElement('c:chart');
$objWriter->writeAttribute('xmlns:c', Namespaces::CHART);
$objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT);
$objWriter->writeAttribute('r:id', 'rId' . $relationId);
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
$objWriter->startElement('xdr:clientData');
$objWriter->endElement();
$objWriter->endElement();
}
/**
* Write drawings to XML format.
*/
public function writeDrawing(XMLWriter $objWriter, BaseDrawing $drawing, int $relationId = -1, ?int $hlinkClickId = null): void
{
if ($relationId >= 0) {
$isTwoCellAnchor = $drawing->getCoordinates2() !== '';
if ($isTwoCellAnchor) {
// xdr:twoCellAnchor
$objWriter->startElement('xdr:twoCellAnchor');
if ($drawing->validEditAs()) {
$objWriter->writeAttribute('editAs', $drawing->getEditAs());
}
// Image location
$aCoordinates = Coordinate::indexesFromString($drawing->getCoordinates());
$aCoordinates2 = Coordinate::indexesFromString($drawing->getCoordinates2());
// xdr:from
$objWriter->startElement('xdr:from');
$objWriter->writeElement('xdr:col', (string) ($aCoordinates[0] - 1));
$objWriter->writeElement('xdr:colOff', self::stringEmu($drawing->getOffsetX()));
$objWriter->writeElement('xdr:row', (string) ($aCoordinates[1] - 1));
$objWriter->writeElement('xdr:rowOff', self::stringEmu($drawing->getOffsetY()));
$objWriter->endElement();
// xdr:to
$objWriter->startElement('xdr:to');
$objWriter->writeElement('xdr:col', (string) ($aCoordinates2[0] - 1));
$objWriter->writeElement('xdr:colOff', self::stringEmu($drawing->getOffsetX2()));
$objWriter->writeElement('xdr:row', (string) ($aCoordinates2[1] - 1));
$objWriter->writeElement('xdr:rowOff', self::stringEmu($drawing->getOffsetY2()));
$objWriter->endElement();
} else {
// xdr:oneCellAnchor
$objWriter->startElement('xdr:oneCellAnchor');
// Image location
$aCoordinates = Coordinate::indexesFromString($drawing->getCoordinates());
// xdr:from
$objWriter->startElement('xdr:from');
$objWriter->writeElement('xdr:col', (string) ($aCoordinates[0] - 1));
$objWriter->writeElement('xdr:colOff', self::stringEmu($drawing->getOffsetX()));
$objWriter->writeElement('xdr:row', (string) ($aCoordinates[1] - 1));
$objWriter->writeElement('xdr:rowOff', self::stringEmu($drawing->getOffsetY()));
$objWriter->endElement();
// xdr:ext
$objWriter->startElement('xdr:ext');
$objWriter->writeAttribute('cx', self::stringEmu($drawing->getWidth()));
$objWriter->writeAttribute('cy', self::stringEmu($drawing->getHeight()));
$objWriter->endElement();
}
// xdr:pic
$objWriter->startElement('xdr:pic');
// xdr:nvPicPr
$objWriter->startElement('xdr:nvPicPr');
// xdr:cNvPr
$objWriter->startElement('xdr:cNvPr');
$objWriter->writeAttribute('id', (string) $relationId);
$objWriter->writeAttribute('name', $drawing->getName());
$objWriter->writeAttribute('descr', $drawing->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', Namespaces::SCHEMA_OFFICE_DOCUMENT);
$objWriter->writeAttribute('r:embed', 'rId' . $relationId);
$temp = $drawing->getOpacity();
if (is_int($temp) && $temp >= 0 && $temp <= 100000) {
$objWriter->startElement('a:alphaModFix');
$objWriter->writeAttribute('amt', "$temp");
$objWriter->endElement(); // a:alphaModFix
}
$objWriter->endElement(); // a:blip
$srcRect = $drawing->getSrcRect();
if (!empty($srcRect)) {
$objWriter->startElement('a:srcRect');
foreach ($srcRect as $key => $value) {
$objWriter->writeAttribute($key, (string) $value);
}
$objWriter->endElement(); // a:srcRect
$objWriter->startElement('a:stretch');
$objWriter->endElement(); // a:stretch
} else {
// 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', (string) SharedDrawing::degreesToAngle($drawing->getRotation()));
self::writeAttributeIf($objWriter, $drawing->getFlipVertical(), 'flipV', '1');
self::writeAttributeIf($objWriter, $drawing->getFlipHorizontal(), 'flipH', '1');
if ($isTwoCellAnchor) {
$objWriter->startElement('a:ext');
$objWriter->writeAttribute('cx', self::stringEmu($drawing->getWidth()));
$objWriter->writeAttribute('cy', self::stringEmu($drawing->getHeight()));
$objWriter->endElement();
}
$objWriter->endElement();
// a:prstGeom
$objWriter->startElement('a:prstGeom');
$objWriter->writeAttribute('prst', 'rect');
// a:avLst
$objWriter->writeElement('a:avLst', null);
$objWriter->endElement();
if ($drawing->getShadow()->getVisible()) {
// a:effectLst
$objWriter->startElement('a:effectLst');
// a:outerShdw
$objWriter->startElement('a:outerShdw');
$objWriter->writeAttribute('blurRad', self::stringEmu($drawing->getShadow()->getBlurRadius()));
$objWriter->writeAttribute('dist', self::stringEmu($drawing->getShadow()->getDistance()));
$objWriter->writeAttribute('dir', (string) SharedDrawing::degreesToAngle($drawing->getShadow()->getDirection()));
$objWriter->writeAttribute('algn', $drawing->getShadow()->getAlignment());
$objWriter->writeAttribute('rotWithShape', '0');
// a:srgbClr
$objWriter->startElement('a:srgbClr');
$objWriter->writeAttribute('val', $drawing->getShadow()->getColor()->getRGB());
// a:alpha
$objWriter->startElement('a:alpha');
$objWriter->writeAttribute('val', (string) ($drawing->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 $worksheet): string
{
// 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 = $worksheet->getHeaderFooter()->getImages();
// xml
$objWriter->startElement('xml');
$objWriter->writeAttribute('xmlns:v', Namespaces::URN_VML);
$objWriter->writeAttribute('xmlns:o', Namespaces::URN_MSOFFICE);
$objWriter->writeAttribute('xmlns:x', Namespaces::URN_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 string $reference Reference
*/
private function writeVMLHeaderFooterImage(XMLWriter $objWriter, string $reference, HeaderFooterDrawing $image): void
{
// Calculate object id
if (!Preg::isMatch('{(\d+)}', md5($reference), $m)) {
// @codeCoverageIgnoreStart
throw new WriterException('Regexp failure in writeVMLHeaderFooterImage');
// @codeCoverageIgnoreEnd
}
$id = 1500 + ((int) substr($m[1], 0, 2) * 1);
// Calculate offset
$width = $image->getWidth();
$height = $image->getHeight();
$marginLeft = $image->getOffsetX();
$marginTop = $image->getOffsetY();
// v:shape
$objWriter->startElement('v:shape');
$objWriter->writeAttribute('id', $reference);
$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' . $reference);
$objWriter->writeAttribute('o:title', $image->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 BaseDrawing[] All drawings in PhpSpreadsheet
*/
public function allDrawings(Spreadsheet $spreadsheet): array
{
// 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;
}
private function writeHyperLinkDrawing(XMLWriter $objWriter, ?int $hlinkClickId): void
{
if ($hlinkClickId === null) {
return;
}
$objWriter->startElement('a:hlinkClick');
$objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT);
$objWriter->writeAttribute('r:id', 'rId' . $hlinkClickId);
$objWriter->endElement();
}
private static function stringEmu(int $pixelValue): string
{
return (string) SharedDrawing::pixelsToEMU($pixelValue);
}
private static function writeAttributeIf(XMLWriter $objWriter, ?bool $condition, string $attr, string $val): void
{
if ($condition) {
$objWriter->writeAttribute($attr, $val);
}
}
/**
* Get pass-through drawing XML if available.
*
* Returns the original drawing XML stored during load (when Reader pass-through was enabled).
* This preserves unsupported drawing elements (shapes, textboxes) that PhpSpreadsheet cannot parse.
*
* @return ?string The pass-through XML, or null if not available or should not be used
*/
private function getPassThroughDrawingXml(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet): ?string
{
/** @var array<string, array<string, mixed>> $sheets */
$sheets = $worksheet->getParentOrThrow()->getUnparsedLoadedData()['sheets'] ?? [];
$sheetData = $sheets[$worksheet->getCodeName()] ?? [];
// Only use pass-through XML if the Reader flag was explicitly enabled
/** @var string[] $drawings */
$drawings = $sheetData['Drawings'] ?? [];
if (($sheetData['drawingPassThroughEnabled'] ?? false) !== true || $drawings === []) {
return null;
}
return reset($drawings) ?: null;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php | src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing as WorksheetDrawing;
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, bool $includeCharts = false): string
{
// 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', Namespaces::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');
// Table
$table = 1;
for ($i = 0; $i < $sheetCount; ++$i) {
$tableCount = $spreadsheet->getSheet($i)->getTableCollection()->count();
for ($t = 1; $t <= $tableCount; ++$t) {
$this->writeOverrideContentType($objWriter, '/xl/tables/table' . $table++ . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml');
}
}
// Add worksheet relationship content types
/** @var mixed[][][][] */
$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 = '';
$drawing = $this->getParentWriter()->getDrawingHashTable()->getByIndex($i);
if ($drawing instanceof WorksheetDrawing && $drawing->getPath() !== '') {
$extension = strtolower($drawing->getExtension());
if ($drawing->getIsUrl()) {
$mimeType = image_type_to_mime_type($drawing->getType());
} else {
$mimeType = $this->getImageMimeType($drawing->getPath());
}
} elseif ($drawing instanceof MemoryDrawing) {
$extension = strtolower($drawing->getMimeType());
$extension = explode('/', $extension);
$extension = $extension[1];
$mimeType = $drawing->getMimeType();
}
if ($mimeType !== '' && !isset($aMediaContentTypes[$extension])) {
$aMediaContentTypes[$extension] = $mimeType;
$this->writeDefaultContentType($objWriter, $extension, $mimeType);
}
}
// Add pass-through media content types
/** @var array<string, array<string, mixed>> $sheets */
$sheets = $unparsedLoadedData['sheets'] ?? [];
foreach ($sheets as $sheetData) {
if (($sheetData['drawingPassThroughEnabled'] ?? false) !== true) {
continue;
}
/** @var string[] $mediaFiles */
$mediaFiles = $sheetData['drawingMediaFiles'] ?? [];
foreach ($mediaFiles as $mediaPath) {
$extension = strtolower(pathinfo($mediaPath, PATHINFO_EXTENSION));
if ($extension !== '' && !isset($aMediaContentTypes[$extension])) {
$mimeType = match ($extension) { // @phpstan-ignore match.unhandled
'png' => 'image/png',
'jpg', 'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'tif', 'tiff' => 'image/tiff',
'svg' => 'image/svg+xml',
};
$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
/** @var string[] */
$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 ($image->getPath() !== '' && !isset($aMediaContentTypes[strtolower($image->getExtension())])) {
$aMediaContentTypes[strtolower($image->getExtension())] = $this->getImageMimeType($image->getPath());
$this->writeDefaultContentType($objWriter, strtolower($image->getExtension()), $aMediaContentTypes[strtolower($image->getExtension())]);
}
}
}
if (count($spreadsheet->getSheet($i)->getComments()) > 0) {
foreach ($spreadsheet->getSheet($i)->getComments() as $comment) {
if (!$comment->hasBackgroundImage()) {
continue;
}
$bgImage = $comment->getBackgroundImage();
$bgImageExtensionKey = strtolower($bgImage->getImageFileExtensionForSave(false));
if (!isset($aMediaContentTypes[$bgImageExtensionKey])) {
$aMediaContentTypes[$bgImageExtensionKey] = $bgImage->getImageMimeType();
$this->writeDefaultContentType($objWriter, $bgImageExtensionKey, $aMediaContentTypes[$bgImageExtensionKey]);
}
}
}
$bgImage = $spreadsheet->getSheet($i)->getBackgroundImage();
$mimeType = $spreadsheet->getSheet($i)->getBackgroundMime();
$extension = $spreadsheet->getSheet($i)->getBackgroundExtension();
if ($bgImage !== '' && !isset($aMediaContentTypes[$extension])) {
$this->writeDefaultContentType($objWriter, $extension, $mimeType);
}
}
// unparsed defaults
if (isset($unparsedLoadedData['default_content_types'])) {
/** @var array<string, string> */
$unparsedDefault = $unparsedLoadedData['default_content_types'];
foreach ($unparsedDefault as $extName => $contentType) {
$this->writeDefaultContentType($objWriter, $extName, $contentType);
}
}
// unparsed overrides
if (isset($unparsedLoadedData['override_content_types'])) {
/** @var array<string, string> */
$unparsedOverride = $unparsedLoadedData['override_content_types'];
foreach ($unparsedOverride as $partName => $overrideType) {
$this->writeOverrideContentType($objWriter, $partName, $overrideType);
}
}
// Metadata needed for Dynamic Arrays
if ($this->getParentWriter()->useDynamicArrays()) {
$this->writeOverrideContentType($objWriter, '/xl/metadata.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml');
}
$objWriter->endElement();
// Return
return $objWriter->getData();
}
private static int $three = 3; // phpstan silliness
/**
* Get image mime type.
*
* @param string $filename Filename
*
* @return string Mime Type
*/
private function getImageMimeType(string $filename): string
{
if (File::fileExists($filename)) {
$image = getimagesize($filename);
return image_type_to_mime_type((is_array($image) && count($image) >= self::$three) ? $image[2] : 0);
}
throw new WriterException("File $filename does not exist");
}
/**
* Write Default content type.
*
* @param string $partName Part name
* @param string $contentType Content type
*/
private function writeDefaultContentType(XMLWriter $objWriter, string $partName, string $contentType): void
{
if ($partName != '' && $contentType != '') {
// Write content type
$objWriter->startElement('Default');
$objWriter->writeAttribute('Extension', $partName);
$objWriter->writeAttribute('ContentType', $contentType);
$objWriter->endElement();
} else {
throw new WriterException('Invalid parameters passed.');
}
}
/**
* Write Override content type.
*
* @param string $partName Part name
* @param string $contentType Content type
*/
private function writeOverrideContentType(XMLWriter $objWriter, string $partName, string $contentType): void
{
if ($partName != '' && $contentType != '') {
// Write content type
$objWriter->startElement('Override');
$objWriter->writeAttribute('PartName', $partName);
$objWriter->writeAttribute('ContentType', $contentType);
$objWriter->endElement();
} else {
throw new WriterException('Invalid parameters passed.');
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/Metadata.php | src/PhpSpreadsheet/Writer/Xlsx/Metadata.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
class Metadata extends WriterPart
{
/**
* Write content types to XML format.
*
* @return string XML Output
*/
public function writeMetadata(): string
{
if (!$this->getParentWriter()->useDynamicArrays()) {
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');
// Types
$objWriter->startElement('metadata');
$objWriter->writeAttribute('xmlns', Namespaces::MAIN);
$objWriter->writeAttribute('xmlns:xlrd', Namespaces::DYNAMIC_ARRAY_RICHDATA);
$objWriter->writeAttribute('xmlns:xda', Namespaces::DYNAMIC_ARRAY);
$objWriter->startElement('metadataTypes');
$objWriter->writeAttribute('count', '2');
$objWriter->startElement('metadataType');
$objWriter->writeAttribute('name', 'XLDAPR');
$objWriter->writeAttribute('minSupportedVersion', '120000');
$objWriter->writeAttribute('copy', '1');
$objWriter->writeAttribute('pasteAll', '1');
$objWriter->writeAttribute('pasteValues', '1');
$objWriter->writeAttribute('merge', '1');
$objWriter->writeAttribute('splitFirst', '1');
$objWriter->writeAttribute('rowColShift', '1');
$objWriter->writeAttribute('clearFormats', '1');
$objWriter->writeAttribute('clearComments', '1');
$objWriter->writeAttribute('assign', '1');
$objWriter->writeAttribute('coerce', '1');
$objWriter->writeAttribute('cellMeta', '1');
$objWriter->endElement(); // metadataType XLDAPR
$objWriter->startElement('metadataType');
$objWriter->writeAttribute('name', 'XLRICHVALUE');
$objWriter->writeAttribute('minSupportedVersion', '120000');
$objWriter->writeAttribute('copy', '1');
$objWriter->writeAttribute('pasteAll', '1');
$objWriter->writeAttribute('pasteValues', '1');
$objWriter->writeAttribute('merge', '1');
$objWriter->writeAttribute('splitFirst', '1');
$objWriter->writeAttribute('rowColShift', '1');
$objWriter->writeAttribute('clearFormats', '1');
$objWriter->writeAttribute('clearComments', '1');
$objWriter->writeAttribute('assign', '1');
$objWriter->writeAttribute('coerce', '1');
$objWriter->endElement(); // metadataType XLRICHVALUE
$objWriter->endElement(); // metadataTypes
$objWriter->startElement('futureMetadata');
$objWriter->writeAttribute('name', 'XLDAPR');
$objWriter->writeAttribute('count', '1');
$objWriter->startElement('bk');
$objWriter->startElement('extLst');
$objWriter->startElement('ext');
$objWriter->writeAttribute('uri', '{bdbb8cdc-fa1e-496e-a857-3c3f30c029c3}');
$objWriter->startElement('xda:dynamicArrayProperties');
$objWriter->writeAttribute('fDynamic', '1');
$objWriter->writeAttribute('fCollapsed', '0');
$objWriter->endElement(); // xda:dynamicArrayProperties
$objWriter->endElement(); // ext
$objWriter->endElement(); // extLst
$objWriter->endElement(); // bk
$objWriter->endElement(); // futureMetadata XLDAPR
$objWriter->startElement('futureMetadata');
$objWriter->writeAttribute('name', 'XLRICHVALUE');
$objWriter->writeAttribute('count', '1');
$objWriter->startElement('bk');
$objWriter->startElement('extLst');
$objWriter->startElement('ext');
$objWriter->writeAttribute('uri', '{3e2802c4-a4d2-4d8b-9148-e3be6c30e623}');
$objWriter->startElement('xlrd:rvb');
$objWriter->writeAttribute('i', '0');
$objWriter->endElement(); // xlrd:rvb
$objWriter->endElement(); // ext
$objWriter->endElement(); // extLst
$objWriter->endElement(); // bk
$objWriter->endElement(); // futureMetadata XLRICHVALUE
$objWriter->startElement('cellMetadata');
$objWriter->writeAttribute('count', '1');
$objWriter->startElement('bk');
$objWriter->startElement('rc');
$objWriter->writeAttribute('t', '1');
$objWriter->writeAttribute('v', '0');
$objWriter->endElement(); // rc
$objWriter->endElement(); // bk
$objWriter->endElement(); // cellMetadata
$objWriter->startElement('valueMetadata');
$objWriter->writeAttribute('count', '1');
$objWriter->startElement('bk');
$objWriter->startElement('rc');
$objWriter->writeAttribute('t', '2');
$objWriter->writeAttribute('v', '0');
$objWriter->endElement(); // rc
$objWriter->endElement(); // bk
$objWriter->endElement(); // valueMetadata
$objWriter->endElement(); // metadata
// Return
return $objWriter->getData();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/RelsRibbon.php | src/PhpSpreadsheet/Writer/Xlsx/RelsRibbon.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
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): string
{
// 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', Namespaces::RELATIONSHIPS);
$localRels = $spreadsheet->getRibbonBinObjects('names');
if (is_array($localRels)) {
foreach ($localRels as $aId => $aTarget) {
$objWriter->startElement('Relationship');
$objWriter->writeAttribute('Id', $aId);
$objWriter->writeAttribute('Type', Namespaces::IMAGE);
/** @var string $aTarget */
$objWriter->writeAttribute('Target', $aTarget);
$objWriter->endElement();
}
}
$objWriter->endElement();
return $objWriter->getData();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/Table.php | src/PhpSpreadsheet/Writer/Xlsx/Table.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Worksheet\Table as WorksheetTable;
class Table extends WriterPart
{
/**
* Write Table to XML format.
*
* @param int $tableRef Table ID
*
* @return string XML Output
*/
public function writeTable(WorksheetTable $table, int $tableRef): string
{
// 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');
// Table
$name = 'Table' . $tableRef;
$range = $table->getRange();
$objWriter->startElement('table');
$objWriter->writeAttribute('xmlns', Namespaces::MAIN);
$objWriter->writeAttribute('id', (string) $tableRef);
$objWriter->writeAttribute('name', $name);
$objWriter->writeAttribute('displayName', $table->getName() ?: $name);
$objWriter->writeAttribute('ref', $range);
$objWriter->writeAttribute('headerRowCount', $table->getShowHeaderRow() ? '1' : '0');
$objWriter->writeAttribute('totalsRowCount', $table->getShowTotalsRow() ? '1' : '0');
// Table Boundaries
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($table->getRange());
// Table Auto Filter
if ($table->getShowHeaderRow() && $table->getAllowFilter() === true) {
$objWriter->startElement('autoFilter');
$objWriter->writeAttribute('ref', $range);
foreach (range($rangeStart[0], $rangeEnd[0]) as $offset => $columnIndex) {
$column = $table->getColumnByOffset($offset);
if (!$column->getShowFilterButton()) {
$objWriter->startElement('filterColumn');
$objWriter->writeAttribute('colId', (string) $offset);
$objWriter->writeAttribute('hiddenButton', '1');
$objWriter->endElement();
} else {
$column = $table->getAutoFilter()->getColumnByOffset($offset);
AutoFilter::writeAutoFilterColumn($objWriter, $column, $offset);
}
}
$objWriter->endElement(); // autoFilter
}
// Table Columns
$objWriter->startElement('tableColumns');
$objWriter->writeAttribute('count', (string) ($rangeEnd[0] - $rangeStart[0] + 1));
foreach (range($rangeStart[0], $rangeEnd[0]) as $offset => $columnIndex) {
$worksheet = $table->getWorksheet();
if (!$worksheet) {
continue;
}
$column = $table->getColumnByOffset($offset);
$cell = $worksheet->getCell([$columnIndex, $rangeStart[1]]);
$objWriter->startElement('tableColumn');
$objWriter->writeAttribute('id', (string) ($offset + 1));
$objWriter->writeAttribute('name', $table->getShowHeaderRow() ? $cell->getValueString() : ('Column' . ($offset + 1)));
if ($table->getShowTotalsRow()) {
if ($column->getTotalsRowLabel()) {
$objWriter->writeAttribute('totalsRowLabel', $column->getTotalsRowLabel());
}
if ($column->getTotalsRowFunction()) {
$objWriter->writeAttribute('totalsRowFunction', $column->getTotalsRowFunction());
}
}
if ($column->getColumnFormula()) {
$objWriter->writeElement('calculatedColumnFormula', $column->getColumnFormula());
}
$objWriter->endElement();
}
$objWriter->endElement();
// Table Styles
$objWriter->startElement('tableStyleInfo');
$objWriter->writeAttribute('name', $table->getStyle()->getTheme());
$objWriter->writeAttribute('showFirstColumn', $table->getStyle()->getShowFirstColumn() ? '1' : '0');
$objWriter->writeAttribute('showLastColumn', $table->getStyle()->getShowLastColumn() ? '1' : '0');
$objWriter->writeAttribute('showRowStripes', $table->getStyle()->getShowRowStripes() ? '1' : '0');
$objWriter->writeAttribute('showColumnStripes', $table->getStyle()->getShowColumnStripes() ? '1' : '0');
$objWriter->endElement();
$objWriter->endElement();
// Return
return $objWriter->getData();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/Theme.php | src/PhpSpreadsheet/Writer/Xlsx/Theme.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Theme as SpreadsheetTheme;
class Theme extends WriterPart
{
/**
* Write theme to XML format.
*
* @return string XML Output
*/
public function writeTheme(Spreadsheet $spreadsheet): string
{
// 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);
}
$theme = $spreadsheet->getTheme();
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// a:theme
$objWriter->startElement('a:theme');
$objWriter->writeAttribute('xmlns:a', Namespaces::DRAWINGML);
$objWriter->writeAttribute('name', 'Office Theme');
// a:themeElements
$objWriter->startElement('a:themeElements');
// a:clrScheme
$objWriter->startElement('a:clrScheme');
$objWriter->writeAttribute('name', $theme->getThemeColorName());
$this->writeColourScheme($objWriter, $theme);
$objWriter->endElement();
// a:fontScheme
$objWriter->startElement('a:fontScheme');
$objWriter->writeAttribute('name', $theme->getThemeFontName());
// a:majorFont
$objWriter->startElement('a:majorFont');
$this->writeFonts(
$objWriter,
$theme->getMajorFontLatin(),
$theme->getMajorFontEastAsian(),
$theme->getMajorFontComplexScript(),
$theme->getMajorFontSubstitutions()
);
$objWriter->endElement(); // a:majorFont
// a:minorFont
$objWriter->startElement('a:minorFont');
$this->writeFonts(
$objWriter,
$theme->getMinorFontLatin(),
$theme->getMinorFontEastAsian(),
$theme->getMinorFontComplexScript(),
$theme->getMinorFontSubstitutions()
);
$objWriter->endElement(); // a:minorFont
$objWriter->endElement(); // a:fontScheme
// 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 string[] $fontSet
*/
private function writeFonts(XMLWriter $objWriter, string $latinFont, string $eastAsianFont, string $complexScriptFont, array $fontSet): void
{
// a:latin
$objWriter->startElement('a:latin');
$objWriter->writeAttribute('typeface', $latinFont);
$objWriter->endElement();
// a:ea
$objWriter->startElement('a:ea');
$objWriter->writeAttribute('typeface', $eastAsianFont);
$objWriter->endElement();
// a:cs
$objWriter->startElement('a:cs');
$objWriter->writeAttribute('typeface', $complexScriptFont);
$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.
*/
private function writeColourScheme(XMLWriter $objWriter, SpreadsheetTheme $theme): void
{
$themeArray = $theme->getThemeColors();
// a:dk1
$objWriter->startElement('a:dk1');
$objWriter->startElement('a:sysClr');
$objWriter->writeAttribute('val', 'windowText');
$objWriter->writeAttribute('lastClr', $themeArray['dk1'] ?? '000000');
$objWriter->endElement(); // a:sysClr
$objWriter->endElement(); // a:dk1
// a:lt1
$objWriter->startElement('a:lt1');
$objWriter->startElement('a:sysClr');
$objWriter->writeAttribute('val', 'window');
$objWriter->writeAttribute('lastClr', $themeArray['lt1'] ?? 'FFFFFF');
$objWriter->endElement(); // a:sysClr
$objWriter->endElement(); // a:lt1
foreach ($themeArray as $colourName => $colourValue) {
if ($colourName !== 'dk1' && $colourName !== 'lt1') {
$objWriter->startElement('a:' . $colourName);
$objWriter->startElement('a:srgbClr');
$objWriter->writeAttribute('val', $colourValue);
$objWriter->endElement(); // a:srgbClr
$objWriter->endElement(); // a:$colourName
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php | src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Composer\Pcre\Preg;
use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue;
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalColorScale;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormattingRuleExtension;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalIconSet;
use PhpOffice\PhpSpreadsheet\Style\Font;
use PhpOffice\PhpSpreadsheet\Worksheet\RowDimension;
use PhpOffice\PhpSpreadsheet\Worksheet\SheetView;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as PhpspreadsheetWorksheet;
class Worksheet extends WriterPart
{
private string $numberStoredAsText = '';
private string $formula = '';
private string $formulaRange = '';
private string $twoDigitTextYear = '';
private string $evalError = '';
private bool $explicitStyle0;
private bool $useDynamicArrays = false;
private bool $restrictMaxColumnWidth = false;
/**
* Write worksheet to XML format.
*
* @param string[] $stringTable
* @param bool $includeCharts Flag indicating if we should write charts
*
* @return string XML Output
*/
public function writeWorksheet(PhpspreadsheetWorksheet $worksheet, array $stringTable = [], bool $includeCharts = false): string
{
$this->useDynamicArrays = $this->getParentWriter()->useDynamicArrays();
$this->explicitStyle0 = $this->getParentWriter()->getExplicitStyle0();
$worksheet->calculateArrays($this->getParentWriter()->getPreCalculateFormulas());
$this->numberStoredAsText = '';
$this->formula = '';
$this->formulaRange = '';
$this->twoDigitTextYear = '';
$this->evalError = '';
// 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);
}
$this->restrictMaxColumnWidth = $this->getParentWriter()->getRestrictMaxColumnWidth();
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Worksheet
$objWriter->startElement('worksheet');
$objWriter->writeAttribute('xmlns', Namespaces::MAIN);
$objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT);
$objWriter->writeAttribute('xmlns:xdr', Namespaces::SPREADSHEET_DRAWING);
$objWriter->writeAttribute('xmlns:x14', Namespaces::DATA_VALIDATIONS1);
$objWriter->writeAttribute('xmlns:xm', Namespaces::DATA_VALIDATIONS2);
$objWriter->writeAttribute('xmlns:mc', Namespaces::COMPATIBILITY);
$objWriter->writeAttribute('mc:Ignorable', 'x14ac');
$objWriter->writeAttribute('xmlns:x14ac', Namespaces::SPREADSHEETML_AC);
// sheetPr
$this->writeSheetPr($objWriter, $worksheet);
// Dimension
$this->writeDimension($objWriter, $worksheet);
// sheetViews
$this->writeSheetViews($objWriter, $worksheet);
// sheetFormatPr
$this->writeSheetFormatPr($objWriter, $worksheet);
// cols
$this->writeCols($objWriter, $worksheet);
// sheetData
$this->writeSheetData($objWriter, $worksheet, $stringTable);
// sheetProtection
$this->writeSheetProtection($objWriter, $worksheet);
// protectedRanges
$this->writeProtectedRanges($objWriter, $worksheet);
// autoFilter
$this->writeAutoFilter($objWriter, $worksheet);
// mergeCells
$this->writeMergeCells($objWriter, $worksheet);
// conditionalFormatting
$this->writeConditionalFormatting($objWriter, $worksheet);
// dataValidations
$this->writeDataValidations($objWriter, $worksheet);
// hyperlinks
$this->writeHyperlinks($objWriter, $worksheet);
// Print options
$this->writePrintOptions($objWriter, $worksheet);
// Page margins
$this->writePageMargins($objWriter, $worksheet);
// Page setup
$this->writePageSetup($objWriter, $worksheet);
// Header / footer
$this->writeHeaderFooter($objWriter, $worksheet);
// Breaks
$this->writeBreaks($objWriter, $worksheet);
// IgnoredErrors
$this->writeIgnoredErrors($objWriter);
// Drawings and/or Charts
$this->writeDrawings($objWriter, $worksheet, $includeCharts);
// LegacyDrawing
$this->writeLegacyDrawing($objWriter, $worksheet);
// LegacyDrawingHF
$this->writeLegacyDrawingHF($objWriter, $worksheet);
// AlternateContent
$this->writeAlternateContent($objWriter, $worksheet);
// BackgroundImage must come after ignored, before table
$this->writeBackgroundImage($objWriter, $worksheet);
// Table
$this->writeTable($objWriter, $worksheet);
// ConditionalFormattingRuleExtensionList
// (Must be inserted last. Not insert last, an Excel parse error will occur)
$this->writeExtLst($objWriter, $worksheet);
$objWriter->endElement();
// Return
return $objWriter->getData();
}
private function writeIgnoredError(XMLWriter $objWriter, bool &$started, string $attr, string $cells): void
{
if ($cells !== '') {
if (!$started) {
$objWriter->startElement('ignoredErrors');
$started = true;
}
$objWriter->startElement('ignoredError');
$objWriter->writeAttribute('sqref', substr($cells, 1));
$objWriter->writeAttribute($attr, '1');
$objWriter->endElement();
}
}
private function writeIgnoredErrors(XMLWriter $objWriter): void
{
$started = false;
$this->writeIgnoredError($objWriter, $started, 'numberStoredAsText', $this->numberStoredAsText);
$this->writeIgnoredError($objWriter, $started, 'formula', $this->formula);
$this->writeIgnoredError($objWriter, $started, 'formulaRange', $this->formulaRange);
$this->writeIgnoredError($objWriter, $started, 'twoDigitTextYear', $this->twoDigitTextYear);
$this->writeIgnoredError($objWriter, $started, 'evalError', $this->evalError);
if ($started) {
$objWriter->endElement();
}
}
/**
* Write SheetPr.
*/
private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// sheetPr
$objWriter->startElement('sheetPr');
if ($worksheet->getParentOrThrow()->hasMacros()) {
//if the workbook have macros, we need to have codeName for the sheet
if (!$worksheet->hasCodeName()) {
$worksheet->setCodeName($worksheet->getTitle());
}
self::writeAttributeNotNull($objWriter, 'codeName', $worksheet->getCodeName());
}
$autoFilterRange = $worksheet->getAutoFilter()->getRange();
if (!empty($autoFilterRange)) {
$objWriter->writeAttribute('filterMode', '1');
if (!$worksheet->getAutoFilter()->getEvaluated()) {
$worksheet->getAutoFilter()->showHideRows();
}
}
$tables = $worksheet->getTableCollection();
if (count($tables)) {
foreach ($tables as $table) {
if (!$table->getAutoFilter()->getEvaluated()) {
$table->getAutoFilter()->showHideRows();
}
}
}
// tabColor
if ($worksheet->isTabColorSet()) {
$objWriter->startElement('tabColor');
$objWriter->writeAttribute('rgb', $worksheet->getTabColor()->getARGB() ?? '');
$objWriter->endElement();
}
// outlinePr
$objWriter->startElement('outlinePr');
$objWriter->writeAttribute('summaryBelow', ($worksheet->getShowSummaryBelow() ? '1' : '0'));
$objWriter->writeAttribute('summaryRight', ($worksheet->getShowSummaryRight() ? '1' : '0'));
$objWriter->endElement();
// pageSetUpPr
if ($worksheet->getPageSetup()->getFitToPage()) {
$objWriter->startElement('pageSetUpPr');
$objWriter->writeAttribute('fitToPage', '1');
$objWriter->endElement();
}
$objWriter->endElement();
}
/**
* Write Dimension.
*/
private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// dimension
$objWriter->startElement('dimension');
$objWriter->writeAttribute('ref', $worksheet->calculateWorksheetDimension());
$objWriter->endElement();
}
/**
* Write SheetViews.
*/
private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// sheetViews
$objWriter->startElement('sheetViews');
// Sheet selected?
$sheetSelected = false;
if ($this->getParentWriter()->getSpreadsheet()->getIndex($worksheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) {
$sheetSelected = true;
}
// sheetView
$objWriter->startElement('sheetView');
$objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0');
$objWriter->writeAttribute('workbookViewId', '0');
// Zoom scales
$zoomScale = $worksheet->getSheetView()->getZoomScale();
if ($zoomScale !== 100 && $zoomScale !== null) {
$objWriter->writeAttribute('zoomScale', (string) $zoomScale);
}
$zoomScale = $worksheet->getSheetView()->getZoomScaleNormal();
if ($zoomScale !== 100 && $zoomScale !== null) {
$objWriter->writeAttribute('zoomScaleNormal', (string) $zoomScale);
}
$zoomScale = $worksheet->getSheetView()->getZoomScalePageLayoutView();
if ($zoomScale !== 100) {
$objWriter->writeAttribute('zoomScalePageLayoutView', (string) $zoomScale);
}
$zoomScale = $worksheet->getSheetView()->getZoomScaleSheetLayoutView();
if ($zoomScale !== 100) {
$objWriter->writeAttribute('zoomScaleSheetLayoutView', (string) $zoomScale);
}
// Show zeros (Excel also writes this attribute only if set to false)
if ($worksheet->getSheetView()->getShowZeros() === false) {
$objWriter->writeAttribute('showZeros', '0');
}
// View Layout Type
if ($worksheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) {
$objWriter->writeAttribute('view', $worksheet->getSheetView()->getView());
}
// Gridlines
if ($worksheet->getShowGridlines()) {
$objWriter->writeAttribute('showGridLines', 'true');
} else {
$objWriter->writeAttribute('showGridLines', 'false');
}
// Row and column headers
if ($worksheet->getShowRowColHeaders()) {
$objWriter->writeAttribute('showRowColHeaders', '1');
} else {
$objWriter->writeAttribute('showRowColHeaders', '0');
}
// Right-to-left
if ($worksheet->getRightToLeft()) {
$objWriter->writeAttribute('rightToLeft', 'true');
}
$topLeftCell = $worksheet->getTopLeftCell();
if (!empty($topLeftCell) && $worksheet->getPaneState() !== PhpspreadsheetWorksheet::PANE_FROZEN && $worksheet->getPaneState() !== PhpspreadsheetWorksheet::PANE_FROZENSPLIT) {
$objWriter->writeAttribute('topLeftCell', $topLeftCell);
}
$activeCell = $worksheet->getActiveCell();
$sqref = $worksheet->getSelectedCells();
// Pane
if ($worksheet->usesPanes()) {
$objWriter->startElement('pane');
$xSplit = $worksheet->getXSplit();
$ySplit = $worksheet->getYSplit();
$pane = $worksheet->getActivePane();
$paneTopLeftCell = $worksheet->getPaneTopLeftCell();
$paneState = $worksheet->getPaneState();
$normalFreeze = '';
if ($paneState === PhpspreadsheetWorksheet::PANE_FROZEN) {
if ($ySplit > 0) {
$normalFreeze = ($xSplit <= 0) ? 'bottomLeft' : 'bottomRight';
} else {
$normalFreeze = 'topRight';
}
}
if ($xSplit > 0) {
$objWriter->writeAttribute('xSplit', "$xSplit");
}
if ($ySplit > 0) {
$objWriter->writeAttribute('ySplit', "$ySplit");
}
if ($normalFreeze !== '') {
$objWriter->writeAttribute('activePane', $normalFreeze);
} elseif ($pane !== '') {
$objWriter->writeAttribute('activePane', $pane);
}
if ($paneState !== '') {
$objWriter->writeAttribute('state', $paneState);
}
if ($paneTopLeftCell !== '') {
$objWriter->writeAttribute('topLeftCell', $paneTopLeftCell);
}
$objWriter->endElement(); // pane
if ($normalFreeze !== '') {
$objWriter->startElement('selection');
$objWriter->writeAttribute('pane', $normalFreeze);
if ($activeCell !== '') {
$objWriter->writeAttribute('activeCell', $activeCell);
}
if ($sqref !== '') {
$objWriter->writeAttribute('sqref', $sqref);
}
$objWriter->endElement(); // selection
$sqref = $activeCell = '';
} else {
foreach ($worksheet->getPanes() as $panex) {
if ($panex !== null) {
$sqref = $activeCell = '';
$objWriter->startElement('selection');
$objWriter->writeAttribute('pane', $panex->getPosition());
$activeCellPane = $panex->getActiveCell();
if ($activeCellPane !== '') {
$objWriter->writeAttribute('activeCell', $activeCellPane);
}
$sqrefPane = $panex->getSqref();
if ($sqrefPane !== '') {
$objWriter->writeAttribute('sqref', $sqrefPane);
}
$objWriter->endElement(); // selection
}
}
}
}
// Selection
// Only need to write selection element if we have a split pane
// We cheat a little by over-riding the active cell selection, setting it to the split cell
if (!empty($sqref) || !empty($activeCell)) {
$objWriter->startElement('selection');
if (!empty($activeCell)) {
$objWriter->writeAttribute('activeCell', $activeCell);
}
if (!empty($sqref)) {
$objWriter->writeAttribute('sqref', $sqref);
}
$objWriter->endElement(); // selection
}
$objWriter->endElement();
$objWriter->endElement();
}
/**
* Write SheetFormatPr.
*/
private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// sheetFormatPr
$objWriter->startElement('sheetFormatPr');
// Default row height
if ($worksheet->getDefaultRowDimension()->getRowHeight() >= 0) {
$objWriter->writeAttribute('customHeight', 'true');
$objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($worksheet->getDefaultRowDimension()->getRowHeight()));
} else {
$objWriter->writeAttribute('defaultRowHeight', '14.4');
}
// Set Zero Height row
if ($worksheet->getDefaultRowDimension()->getZeroHeight()) {
$objWriter->writeAttribute('zeroHeight', '1');
}
// Default column width
if ($worksheet->getDefaultColumnDimension()->getWidth() >= 0) {
$objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($worksheet->getDefaultColumnDimension()->getWidthForOutput($this->restrictMaxColumnWidth)));
}
// Outline level - row
$outlineLevelRow = 0;
foreach ($worksheet->getRowDimensions() as $dimension) {
if ($dimension->getOutlineLevel() > $outlineLevelRow) {
$outlineLevelRow = $dimension->getOutlineLevel();
}
}
$objWriter->writeAttribute('outlineLevelRow', (string) (int) $outlineLevelRow);
// Outline level - column
$outlineLevelCol = 0;
foreach ($worksheet->getColumnDimensions() as $dimension) {
if ($dimension->getOutlineLevel() > $outlineLevelCol) {
$outlineLevelCol = $dimension->getOutlineLevel();
}
}
$objWriter->writeAttribute('outlineLevelCol', (string) (int) $outlineLevelCol);
$objWriter->endElement();
}
/**
* Write Cols.
*/
private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// cols
if (count($worksheet->getColumnDimensions()) > 0) {
$objWriter->startElement('cols');
$worksheet->calculateColumnWidths();
// Loop through column dimensions
foreach ($worksheet->getColumnDimensions() as $colDimension) {
// col
$objWriter->startElement('col');
$objWriter->writeAttribute('min', (string) Coordinate::columnIndexFromString($colDimension->getColumnIndex()));
$objWriter->writeAttribute('max', (string) Coordinate::columnIndexFromString($colDimension->getColumnIndex()));
if ($colDimension->getWidth() < 0) {
// No width set, apply default of 10
$objWriter->writeAttribute('width', '9.10');
} else {
// Width set
$objWriter->writeAttribute('width', StringHelper::formatNumber($colDimension->getWidthForOutput($this->restrictMaxColumnWidth)));
}
// Column visibility
if ($colDimension->getVisible() === false) {
$objWriter->writeAttribute('hidden', 'true');
}
// Auto size?
if ($colDimension->getAutoSize()) {
$objWriter->writeAttribute('bestFit', 'true');
}
// Custom width?
if ($colDimension->getWidth() != $worksheet->getDefaultColumnDimension()->getWidth()) {
$objWriter->writeAttribute('customWidth', 'true');
}
// Collapsed
if ($colDimension->getCollapsed() === true) {
$objWriter->writeAttribute('collapsed', 'true');
}
// Outline level
if ($colDimension->getOutlineLevel() > 0) {
$objWriter->writeAttribute('outlineLevel', (string) $colDimension->getOutlineLevel());
}
// Style
$objWriter->writeAttribute('style', (string) $colDimension->getXfIndex());
$objWriter->endElement();
}
$objWriter->endElement();
}
}
/**
* Write SheetProtection.
*/
private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
$protection = $worksheet->getProtection();
if (!$protection->isProtectionEnabled()) {
return;
}
// sheetProtection
$objWriter->startElement('sheetProtection');
if ($protection->getAlgorithm()) {
$objWriter->writeAttribute('algorithmName', $protection->getAlgorithm());
$objWriter->writeAttribute('hashValue', $protection->getPassword());
$objWriter->writeAttribute('saltValue', $protection->getSalt());
$objWriter->writeAttribute('spinCount', (string) $protection->getSpinCount());
} elseif ($protection->getPassword() !== '') {
$objWriter->writeAttribute('password', $protection->getPassword());
}
self::writeProtectionAttribute($objWriter, 'sheet', $protection->getSheet());
self::writeProtectionAttribute($objWriter, 'objects', $protection->getObjects());
self::writeProtectionAttribute($objWriter, 'scenarios', $protection->getScenarios());
self::writeProtectionAttribute($objWriter, 'formatCells', $protection->getFormatCells());
self::writeProtectionAttribute($objWriter, 'formatColumns', $protection->getFormatColumns());
self::writeProtectionAttribute($objWriter, 'formatRows', $protection->getFormatRows());
self::writeProtectionAttribute($objWriter, 'insertColumns', $protection->getInsertColumns());
self::writeProtectionAttribute($objWriter, 'insertRows', $protection->getInsertRows());
self::writeProtectionAttribute($objWriter, 'insertHyperlinks', $protection->getInsertHyperlinks());
self::writeProtectionAttribute($objWriter, 'deleteColumns', $protection->getDeleteColumns());
self::writeProtectionAttribute($objWriter, 'deleteRows', $protection->getDeleteRows());
self::writeProtectionAttribute($objWriter, 'sort', $protection->getSort());
self::writeProtectionAttribute($objWriter, 'autoFilter', $protection->getAutoFilter());
self::writeProtectionAttribute($objWriter, 'pivotTables', $protection->getPivotTables());
self::writeProtectionAttribute($objWriter, 'selectLockedCells', $protection->getSelectLockedCells());
self::writeProtectionAttribute($objWriter, 'selectUnlockedCells', $protection->getSelectUnlockedCells());
$objWriter->endElement();
}
private static function writeProtectionAttribute(XMLWriter $objWriter, string $name, ?bool $value): void
{
if ($value === true) {
$objWriter->writeAttribute($name, '1');
} elseif ($value === false) {
$objWriter->writeAttribute($name, '0');
}
}
private static function writeAttributeIf(XMLWriter $objWriter, ?bool $condition, string $attr, string $val): void
{
if ($condition) {
$objWriter->writeAttribute($attr, $val);
}
}
private static function writeAttributeNotNull(XMLWriter $objWriter, string $attr, ?string $val): void
{
if ($val !== null) {
$objWriter->writeAttribute($attr, $val);
}
}
private static function writeElementIf(XMLWriter $objWriter, bool $condition, string $attr, string $val): void
{
if ($condition) {
$objWriter->writeElement($attr, $val);
}
}
private static function writeOtherCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void
{
$conditions = $conditional->getConditions();
if (
$conditional->getConditionType() == Conditional::CONDITION_CELLIS
|| $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION
|| !empty($conditions)
) {
foreach ($conditions as $formula) {
// Formula
if (is_bool($formula)) {
$formula = $formula ? 'TRUE' : 'FALSE';
}
$objWriter->writeElement('formula', FunctionPrefix::addFunctionPrefix("$formula"));
}
} else {
if ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSBLANKS) {
// formula copied from ms xlsx xml source file
$objWriter->writeElement('formula', 'LEN(TRIM(' . $cellCoordinate . '))=0');
} elseif ($conditional->getConditionType() == Conditional::CONDITION_NOTCONTAINSBLANKS) {
// formula copied from ms xlsx xml source file
$objWriter->writeElement('formula', 'LEN(TRIM(' . $cellCoordinate . '))>0');
} elseif ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSERRORS) {
// formula copied from ms xlsx xml source file
$objWriter->writeElement('formula', 'ISERROR(' . $cellCoordinate . ')');
} elseif ($conditional->getConditionType() == Conditional::CONDITION_NOTCONTAINSERRORS) {
// formula copied from ms xlsx xml source file
$objWriter->writeElement('formula', 'NOT(ISERROR(' . $cellCoordinate . '))');
}
}
}
private static function writeTimePeriodCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void
{
$txt = $conditional->getText();
if (!empty($txt)) {
$objWriter->writeAttribute('timePeriod', $txt);
if (empty($conditional->getConditions())) {
if ($conditional->getOperatorType() == Conditional::TIMEPERIOD_TODAY) {
$objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()');
} elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_TOMORROW) {
$objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()+1');
} elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_YESTERDAY) {
$objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()-1');
} elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_7_DAYS) {
$objWriter->writeElement('formula', 'AND(TODAY()-FLOOR(' . $cellCoordinate . ',1)<=6,FLOOR(' . $cellCoordinate . ',1)<=TODAY())');
} elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_WEEK) {
$objWriter->writeElement('formula', 'AND(TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)>=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)<(WEEKDAY(TODAY())+7))');
} elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_THIS_WEEK) {
$objWriter->writeElement('formula', 'AND(TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)<=WEEKDAY(TODAY())-1,ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()<=7-WEEKDAY(TODAY()))');
} elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_NEXT_WEEK) {
$objWriter->writeElement('formula', 'AND(ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()>(7-WEEKDAY(TODAY())),ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()<(15-WEEKDAY(TODAY())))');
} elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_MONTH) {
$objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(EDATE(TODAY(),0-1)),YEAR(' . $cellCoordinate . ')=YEAR(EDATE(TODAY(),0-1)))');
} elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_THIS_MONTH) {
$objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(TODAY()),YEAR(' . $cellCoordinate . ')=YEAR(TODAY()))');
} elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_NEXT_MONTH) {
$objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(EDATE(TODAY(),0+1)),YEAR(' . $cellCoordinate . ')=YEAR(EDATE(TODAY(),0+1)))');
}
} else {
$objWriter->writeElement('formula', (string) ($conditional->getConditions()[0]));
}
}
}
private static function writeTextCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void
{
$txt = $conditional->getText();
if (!empty($txt)) {
$objWriter->writeAttribute('text', $txt);
if (empty($conditional->getConditions())) {
if ($conditional->getOperatorType() == Conditional::OPERATOR_CONTAINSTEXT) {
$objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $txt . '",' . $cellCoordinate . ')))');
} elseif ($conditional->getOperatorType() == Conditional::OPERATOR_BEGINSWITH) {
$objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',LEN("' . $txt . '"))="' . $txt . '"');
} elseif ($conditional->getOperatorType() == Conditional::OPERATOR_ENDSWITH) {
$objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',LEN("' . $txt . '"))="' . $txt . '"');
} elseif ($conditional->getOperatorType() == Conditional::OPERATOR_NOTCONTAINS) {
$objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $txt . '",' . $cellCoordinate . '))');
}
} else {
$objWriter->writeElement('formula', (string) ($conditional->getConditions()[0]));
}
}
}
private static function writeExtConditionalFormattingElements(XMLWriter $objWriter, ConditionalFormattingRuleExtension $ruleExtension): void
{
$prefix = 'x14';
$objWriter->startElementNs($prefix, 'conditionalFormatting', null);
$objWriter->startElementNs($prefix, 'cfRule', null);
$objWriter->writeAttribute('type', $ruleExtension->getCfRule());
$objWriter->writeAttribute('id', $ruleExtension->getId());
$objWriter->startElementNs($prefix, 'dataBar', null);
$dataBar = $ruleExtension->getDataBarExt();
foreach ($dataBar->getXmlAttributes() as $attrKey => $val) {
/** @var string $val */
$objWriter->writeAttribute($attrKey, $val);
}
$minCfvo = $dataBar->getMinimumConditionalFormatValueObject();
// Phpstan is wrong about the next statement.
if ($minCfvo !== null) { // @phpstan-ignore-line
$objWriter->startElementNs($prefix, 'cfvo', null);
$objWriter->writeAttribute('type', $minCfvo->getType());
if ($minCfvo->getCellFormula()) {
$objWriter->writeElement('xm:f', $minCfvo->getCellFormula());
}
$objWriter->endElement(); //end cfvo
}
$maxCfvo = $dataBar->getMaximumConditionalFormatValueObject();
// Phpstan is wrong about the next statement.
if ($maxCfvo !== null) { // @phpstan-ignore-line
$objWriter->startElementNs($prefix, 'cfvo', null);
$objWriter->writeAttribute('type', $maxCfvo->getType());
if ($maxCfvo->getCellFormula()) {
$objWriter->writeElement('xm:f', $maxCfvo->getCellFormula());
}
$objWriter->endElement(); //end cfvo
}
foreach ($dataBar->getXmlElements() as $elmKey => $elmAttr) {
/** @var string[] $elmAttr */
$objWriter->startElementNs($prefix, $elmKey, null);
foreach ($elmAttr as $attrKey => $attrVal) {
$objWriter->writeAttribute($attrKey, $attrVal);
}
$objWriter->endElement(); //end elmKey
}
$objWriter->endElement(); //end dataBar
$objWriter->endElement(); //end cfRule
$objWriter->writeElement('xm:sqref', $ruleExtension->getSqref());
$objWriter->endElement(); //end conditionalFormatting
}
private static function writeDataBarElements(XMLWriter $objWriter, ?ConditionalDataBar $dataBar): void
{
if ($dataBar) {
$objWriter->startElement('dataBar');
self::writeAttributeIf($objWriter, null !== $dataBar->getShowValue(), 'showValue', $dataBar->getShowValue() ? '1' : '0');
$minCfvo = $dataBar->getMinimumConditionalFormatValueObject();
if ($minCfvo) {
$objWriter->startElement('cfvo');
$objWriter->writeAttribute('type', $minCfvo->getType());
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | true |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php | src/PhpSpreadsheet/Writer/Xlsx/DocProps.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Document\Properties;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\Shared\Date;
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): string
{
// 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', Namespaces::EXTENDED_PROPERTIES);
$objWriter->writeAttribute('xmlns:vt', Namespaces::PROPERTIES_VTYPES);
// 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', (string) $spreadsheet->getSheetCount());
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
// TitlesOfParts
$objWriter->startElement('TitlesOfParts');
// Vector
$objWriter->startElement('vt:vector');
$objWriter->writeAttribute('size', (string) $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');
// HyperlinkBase
$objWriter->writeElement('HyperlinkBase', $spreadsheet->getProperties()->getHyperlinkBase());
// 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): string
{
// 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', Namespaces::CORE_PROPERTIES2);
$objWriter->writeAttribute('xmlns:dc', Namespaces::DC_ELEMENTS);
$objWriter->writeAttribute('xmlns:dcterms', Namespaces::DC_TERMS);
$objWriter->writeAttribute('xmlns:dcmitype', Namespaces::DC_DCMITYPE);
$objWriter->writeAttribute('xmlns:xsi', Namespaces::SCHEMA_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');
$created = $spreadsheet->getProperties()->getCreated();
$date = Date::dateTimeFromTimestamp("$created");
$objWriter->writeRawData($date->format(DATE_W3C));
$objWriter->endElement();
// dcterms:modified
$objWriter->startElement('dcterms:modified');
$objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF');
$created = $spreadsheet->getProperties()->getModified();
$date = Date::dateTimeFromTimestamp("$created");
$objWriter->writeRawData($date->format(DATE_W3C));
$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 null|string XML Output
*/
public function writeDocPropsCustom(Spreadsheet $spreadsheet): ?string
{
$customPropertyList = $spreadsheet->getProperties()->getCustomProperties();
if (empty($customPropertyList)) {
return null;
}
// 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', Namespaces::CUSTOM_PROPERTIES);
$objWriter->writeAttribute('xmlns:vt', Namespaces::PROPERTIES_VTYPES);
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', (string) ($key + 2));
$objWriter->writeAttribute('name', $customProperty);
switch ($propertyType) {
case Properties::PROPERTY_TYPE_INTEGER:
$objWriter->writeElement('vt:i4', (string) $propertyValue);
break;
case Properties::PROPERTY_TYPE_FLOAT:
$objWriter->writeElement('vt:r8', sprintf('%F', $propertyValue));
break;
case Properties::PROPERTY_TYPE_BOOLEAN:
$objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false');
break;
case Properties::PROPERTY_TYPE_DATE:
$objWriter->startElement('vt:filetime');
$date = Date::dateTimeFromTimestamp("$propertyValue");
$objWriter->writeRawData($date->format(DATE_W3C));
$objWriter->endElement();
break;
default:
$objWriter->writeElement('vt:lpwstr', (string) $propertyValue);
break;
}
$objWriter->endElement();
}
$objWriter->endElement();
return $objWriter->getData();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/RelsVBA.php | src/PhpSpreadsheet/Writer/Xlsx/RelsVBA.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
class RelsVBA extends WriterPart
{
/**
* Write relationships for a signed VBA Project.
*
* @return string XML Output
*/
public function writeVBARelationships(): string
{
// 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', Namespaces::RELATIONSHIPS);
$objWriter->startElement('Relationship');
$objWriter->writeAttribute('Id', 'rId1');
$objWriter->writeAttribute('Type', Namespaces::VBA_SIGNATURE);
$objWriter->writeAttribute('Target', 'vbaProjectSignature.bin');
$objWriter->endElement();
$objWriter->endElement();
return $objWriter->getData();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/AutoFilter.php | src/PhpSpreadsheet/Writer/Xlsx/AutoFilter.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column;
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as ActualWorksheet;
class AutoFilter extends WriterPart
{
/**
* Write AutoFilter.
*/
public static function writeAutoFilter(XMLWriter $objWriter, ActualWorksheet $worksheet): void
{
$autoFilterRange = $worksheet->getAutoFilter()->getRange();
if (!empty($autoFilterRange)) {
// autoFilter
$objWriter->startElement('autoFilter');
// Strip any worksheet reference from the filter coordinates
$range = Coordinate::splitRange($autoFilterRange);
$range = $range[0];
// Strip any worksheet ref
[, $range[0]] = ActualWorksheet::extractSheetTitle($range[0], true);
$range = implode(':', $range);
$objWriter->writeAttribute('ref', str_replace('$', '', $range));
$columns = $worksheet->getAutoFilter()->getColumns();
if (count($columns) > 0) {
foreach ($columns as $columnID => $column) {
$colId = $worksheet->getAutoFilter()->getColumnOffset($columnID);
self::writeAutoFilterColumn($objWriter, $column, $colId);
}
}
$objWriter->endElement();
}
}
/**
* Write AutoFilter's filterColumn.
*/
public static function writeAutoFilterColumn(XMLWriter $objWriter, Column $column, int $colId): void
{
$rules = $column->getRules();
if (count($rules) > 0) {
$objWriter->startElement('filterColumn');
$objWriter->writeAttribute('colId', "$colId");
$objWriter->startElement($column->getFilterType());
if ($column->getJoin() == Column::AUTOFILTER_COLUMN_JOIN_AND) {
$objWriter->writeAttribute('and', '1');
}
foreach ($rules as $rule) {
self::writeAutoFilterColumnRule($column, $rule, $objWriter);
}
$objWriter->endElement();
$objWriter->endElement();
}
}
/**
* Write AutoFilter's filterColumn Rule.
*/
private static function writeAutoFilterColumnRule(Column $column, Rule $rule, XMLWriter $objWriter): void
{
if (
($column->getFilterType() === Column::AUTOFILTER_FILTERTYPE_FILTER)
&& ($rule->getOperator() === Rule::AUTOFILTER_COLUMN_RULE_EQUAL)
&& ($rule->getValue() === '')
) {
// Filter rule for Blanks
$objWriter->writeAttribute('blank', '1');
} elseif ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER) {
// Dynamic Filter Rule
$objWriter->writeAttribute('type', $rule->getGrouping());
$val = $column->getAttribute('val');
if ($val !== null) {
$objWriter->writeAttribute('val', "$val");
}
$maxVal = $column->getAttribute('maxVal');
if ($maxVal !== null) {
$objWriter->writeAttribute('maxVal', "$maxVal");
}
} elseif ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) {
// Top 10 Filter Rule
$ruleValue = $rule->getValue();
if (!is_array($ruleValue)) {
$objWriter->writeAttribute('val', "$ruleValue");
}
$objWriter->writeAttribute('percent', (($rule->getOperator() === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) ? '1' : '0'));
$objWriter->writeAttribute('top', (($rule->getGrouping() === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? '1' : '0'));
} else {
// Filter, DateGroupItem or CustomFilter
$objWriter->startElement($rule->getRuleType());
if ($rule->getOperator() !== Rule::AUTOFILTER_COLUMN_RULE_EQUAL) {
$objWriter->writeAttribute('operator', $rule->getOperator());
}
if ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_DATEGROUP) {
// Date Group filters
$ruleValue = $rule->getValue();
if (is_array($ruleValue)) {
foreach ($ruleValue as $key => $value) {
$objWriter->writeAttribute($key, "$value");
}
}
$objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping());
} else {
$ruleValue = $rule->getValue();
if (!is_array($ruleValue)) {
$objWriter->writeAttribute('val', "$ruleValue");
}
}
$objWriter->endElement();
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php | src/PhpSpreadsheet/Writer/Xlsx/StringTable.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Chart\ChartColor;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\RichText\Run;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Style\Font;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as ActualWorksheet;
class StringTable extends WriterPart
{
/**
* Create worksheet stringtable.
*
* @param string[] $existingTable Existing table to eventually merge with
*
* @return string[] String table for worksheet
*/
public function createStringTable(ActualWorksheet $worksheet, ?array $existingTable = null): array
{
// Create string lookup table
/** @var string[] */
$aStringTable = $existingTable ?? [];
// Fill index array
$aFlippedStringTable = $this->flipStringTable($aStringTable);
// Loop through cells
foreach ($worksheet->getCellCollection()->getCoordinates() as $coordinate) {
/** @var Cell $cell */
$cell = $worksheet->getCellCollection()->get($coordinate);
/** @var null|int|RichText|string */
$cellValue = $cell->getValue();
if (
!is_object($cellValue)
&& ($cellValue !== null)
&& $cellValue !== ''
&& ($cell->getDataType() == DataType::TYPE_STRING || $cell->getDataType() == DataType::TYPE_STRING2 || $cell->getDataType() == DataType::TYPE_NULL)
&& !isset($aFlippedStringTable[$cellValue])
) {
$aStringTable[] = $cellValue;
$aFlippedStringTable[$cellValue] = true;
} elseif (
$cellValue instanceof RichText
&& !isset($aFlippedStringTable[$cellValue->getHashCode()])
) {
$aStringTable[] = $cellValue;
$aFlippedStringTable[$cellValue->getHashCode()] = true;
}
}
/** @var string[] $aStringTable */
return $aStringTable;
}
/**
* Write string table to XML format.
*
* @param (RichText|string)[] $stringTable
*
* @return string XML Output
*/
public function writeStringTable(array $stringTable): string
{
// 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', Namespaces::MAIN);
$objWriter->writeAttribute('uniqueCount', (string) count($stringTable));
// Loop through string table
foreach ($stringTable 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();
} else {
$this->writeRichText($objWriter, $textElement);
}
$objWriter->endElement();
}
$objWriter->endElement();
return $objWriter->getData();
}
/**
* Write Rich Text.
*
* @param ?string $prefix Optional Namespace prefix
*/
public function writeRichText(XMLWriter $objWriter, RichText $richText, ?string $prefix = null, ?Font $defaultFont = null): void
{
if ($prefix !== null) {
$prefix .= ':';
}
// Loop through rich text elements
$elements = $richText->getRichTextElements();
foreach ($elements as $element) {
// r
$objWriter->startElement($prefix . 'r');
$font = ($element instanceof Run) ? $element->getFont() : $defaultFont;
// rPr
if ($font !== null) {
// rPr
$objWriter->startElement($prefix . 'rPr');
// rFont
if ($font->getName() !== null) {
$objWriter->startElement($prefix . 'rFont');
$objWriter->writeAttribute('val', $font->getName());
$objWriter->endElement();
}
// Bold
$objWriter->startElement($prefix . 'b');
$objWriter->writeAttribute('val', ($font->getBold() ? 'true' : 'false'));
$objWriter->endElement();
// Italic
$objWriter->startElement($prefix . 'i');
$objWriter->writeAttribute('val', ($font->getItalic() ? 'true' : 'false'));
$objWriter->endElement();
// Superscript / subscript
if ($font->getSuperscript() || $font->getSubscript()) {
$objWriter->startElement($prefix . 'vertAlign');
if ($font->getSuperscript()) {
$objWriter->writeAttribute('val', 'superscript');
} elseif ($font->getSubscript()) {
$objWriter->writeAttribute('val', 'subscript');
}
$objWriter->endElement();
}
// Strikethrough
$objWriter->startElement($prefix . 'strike');
$objWriter->writeAttribute('val', ($font->getStrikethrough() ? 'true' : 'false'));
$objWriter->endElement();
// Color
if ($font->getColor()->getARGB() !== null) {
$objWriter->startElement($prefix . 'color');
$objWriter->writeAttribute('rgb', $font->getColor()->getARGB());
$objWriter->endElement();
}
// Size
if ($font->getSize() !== null) {
$objWriter->startElement($prefix . 'sz');
$objWriter->writeAttribute('val', (string) $font->getSize());
$objWriter->endElement();
}
// Underline
if ($font->getUnderline() !== null) {
$objWriter->startElement($prefix . 'u');
$objWriter->writeAttribute('val', $font->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 RichText|string $richText text string or Rich text
* @param string $prefix Optional Namespace prefix
*/
public function writeRichTextForCharts(XMLWriter $objWriter, $richText = null, string $prefix = ''): void
{
if (!($richText instanceof RichText)) {
$textRun = $richText;
$richText = new RichText();
$run = $richText->createTextRun($textRun ?? '');
$run->setFont(null);
}
if ($prefix !== '') {
$prefix .= ':';
}
// Loop through rich text elements
$elements = $richText->getRichTextElements();
foreach ($elements as $element) {
// r
$objWriter->startElement($prefix . 'r');
if ($element->getFont() !== null) {
// rPr
$objWriter->startElement($prefix . 'rPr');
$fontSize = $element->getFont()->getSize();
if (is_numeric($fontSize)) {
$fontSize *= (($fontSize < 100) ? 100 : 1);
$objWriter->writeAttribute('sz', (string) $fontSize);
}
// 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;
}
if ($underlineType !== null) {
$objWriter->writeAttribute('u', $underlineType);
}
// Strikethrough
$objWriter->writeAttribute('strike', ($element->getFont()->getStriketype() ?: 'noStrike'));
// Superscript/subscript
if ($element->getFont()->getBaseLine()) {
$objWriter->writeAttribute('baseline', (string) $element->getFont()->getBaseLine());
}
// Color
$this->writeChartTextColor($objWriter, $element->getFont()->getChartColor(), $prefix);
// Underscore Color
$this->writeChartTextColor($objWriter, $element->getFont()->getUnderlineColor(), $prefix, 'uFill');
// fontName
if ($element->getFont()->getLatin()) {
$objWriter->startElement($prefix . 'latin');
$objWriter->writeAttribute('typeface', $element->getFont()->getLatin());
$objWriter->endElement();
}
if ($element->getFont()->getEastAsian()) {
$objWriter->startElement($prefix . 'ea');
$objWriter->writeAttribute('typeface', $element->getFont()->getEastAsian());
$objWriter->endElement();
}
if ($element->getFont()->getComplexScript()) {
$objWriter->startElement($prefix . 'cs');
$objWriter->writeAttribute('typeface', $element->getFont()->getComplexScript());
$objWriter->endElement();
}
$objWriter->endElement();
}
// t
$objWriter->startElement($prefix . 't');
$objWriter->writeRawData(StringHelper::controlCharacterPHP2OOXML($element->getText()));
$objWriter->endElement();
$objWriter->endElement();
}
}
private function writeChartTextColor(XMLWriter $objWriter, ?ChartColor $underlineColor, string $prefix, ?string $openTag = ''): void
{
if ($underlineColor !== null) {
$type = $underlineColor->getType();
$value = $underlineColor->getValue();
if (!empty($type) && !empty($value)) {
if ($openTag !== '') {
$objWriter->startElement($prefix . $openTag);
}
$objWriter->startElement($prefix . 'solidFill');
$objWriter->startElement($prefix . $type);
$objWriter->writeAttribute('val', $value);
$alpha = $underlineColor->getAlpha();
if (is_numeric($alpha)) {
$objWriter->startElement($prefix . 'alpha');
$objWriter->writeAttribute('val', ChartColor::alphaToXml((int) $alpha));
$objWriter->endElement();
}
$objWriter->endElement(); // srgbClr/schemeClr/prstClr
$objWriter->endElement(); // solidFill
if ($openTag !== '') {
$objWriter->endElement(); // uFill
}
}
}
}
/**
* Flip string table (for index searching).
*
* @param array<RichText|string> $stringTable Stringtable
*
* @return array<RichText|string>
*/
public function flipStringTable(array $stringTable): array
{
// 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;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/Chart.php | src/PhpSpreadsheet/Writer/Xlsx/Chart.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Chart\Axis;
use PhpOffice\PhpSpreadsheet\Chart\ChartColor;
use PhpOffice\PhpSpreadsheet\Chart\DataSeries;
use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues;
use PhpOffice\PhpSpreadsheet\Chart\Layout;
use PhpOffice\PhpSpreadsheet\Chart\Legend;
use PhpOffice\PhpSpreadsheet\Chart\PlotArea;
use PhpOffice\PhpSpreadsheet\Chart\Properties;
use PhpOffice\PhpSpreadsheet\Chart\Title;
use PhpOffice\PhpSpreadsheet\Chart\TrendLine;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Style\Font;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
class Chart extends WriterPart
{
private int $seriesIndex;
/**
* Write charts to XML format.
*
* @return string XML Output
*/
public function writeChart(\PhpOffice\PhpSpreadsheet\Chart\Chart $chart, bool $calculateCellValues = true): string
{
// 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);
}
// Ensure that data series values are up-to-date before we save
if ($calculateCellValues) {
$chart->refresh();
}
// XML header
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// c:chartSpace
$objWriter->startElement('c:chartSpace');
$objWriter->writeAttribute('xmlns:c', Namespaces::CHART);
$objWriter->writeAttribute('xmlns:a', Namespaces::DRAWINGML);
$objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT);
$objWriter->startElement('c:date1904');
$objWriter->writeAttribute('val', '0');
$objWriter->endElement();
$objWriter->startElement('c:lang');
$objWriter->writeAttribute('val', 'en-GB');
$objWriter->endElement();
$objWriter->startElement('c:roundedCorners');
$objWriter->writeAttribute('val', $chart->getRoundedCorners() ? '1' : '0');
$objWriter->endElement();
$this->writeAlternateContent($objWriter);
$objWriter->startElement('c:chart');
$this->writeTitle($objWriter, $chart->getTitle());
$objWriter->startElement('c:autoTitleDeleted');
$objWriter->writeAttribute('val', (string) (int) $chart->getAutoTitleDeleted());
$objWriter->endElement();
$objWriter->startElement('c:view3D');
$surface2D = false;
$plotArea = $chart->getPlotArea();
if ($plotArea !== null) {
$seriesArray = $plotArea->getPlotGroup();
foreach ($seriesArray as $series) {
if ($series->getPlotType() === DataSeries::TYPE_SURFACECHART) {
$surface2D = true;
break;
}
}
}
$this->writeView3D($objWriter, $chart->getRotX(), 'c:rotX', $surface2D, 90);
$this->writeView3D($objWriter, $chart->getRotY(), 'c:rotY', $surface2D);
$this->writeView3D($objWriter, $chart->getRAngAx(), 'c:rAngAx', $surface2D);
$this->writeView3D($objWriter, $chart->getPerspective(), 'c:perspective', $surface2D);
$objWriter->endElement(); // view3D
$this->writePlotArea($objWriter, $chart->getPlotArea(), $chart->getXAxisLabel(), $chart->getYAxisLabel(), $chart->getChartAxisX(), $chart->getChartAxisY());
$this->writeLegend($objWriter, $chart->getLegend());
$objWriter->startElement('c:plotVisOnly');
$objWriter->writeAttribute('val', (string) (int) $chart->getPlotVisibleOnly());
$objWriter->endElement();
$objWriter->startElement('c:dispBlanksAs');
$objWriter->writeAttribute('val', $chart->getDisplayBlanksAs());
$objWriter->endElement();
$objWriter->startElement('c:showDLblsOverMax');
$objWriter->writeAttribute('val', '0');
$objWriter->endElement();
$objWriter->endElement(); // c:chart
$objWriter->startElement('c:spPr');
if ($chart->getNoFill()) {
$objWriter->startElement('a:noFill');
$objWriter->endElement(); // a:noFill
}
$fillColor = $chart->getFillColor();
if ($fillColor->isUsable()) {
$this->writeColor($objWriter, $fillColor);
}
$borderLines = $chart->getBorderLines();
$this->writeLineStyles($objWriter, $borderLines, $chart->getNoBorder());
$this->writeEffects($objWriter, $borderLines);
$objWriter->endElement(); // c:spPr
$this->writePrintSettings($objWriter);
$objWriter->endElement(); // c:chartSpace
// Return
return $objWriter->getData();
}
private function writeView3D(XMLWriter $objWriter, ?int $value, string $tag, bool $surface2D, int $default = 0): void
{
if ($value === null && $surface2D) {
$value = $default;
}
if ($value !== null) {
$objWriter->startElement($tag);
$objWriter->writeAttribute('val', "$value");
$objWriter->endElement();
}
}
/**
* Write Chart Title.
*/
private function writeTitle(XMLWriter $objWriter, ?Title $title = null): void
{
if ($title === null) {
return;
}
if ($this->writeCalculatedTitle($objWriter, $title)) {
return;
}
$objWriter->startElement('c:title');
$caption = $title->getCaption();
$objWriter->startElement('c:tx');
$objWriter->startElement('c:rich');
$objWriter->startElement('a:bodyPr');
$objWriter->endElement(); // a:bodyPr
$objWriter->startElement('a:lstStyle');
$objWriter->endElement(); // a:lstStyle
$objWriter->startElement('a:p');
$objWriter->startElement('a:pPr');
$objWriter->startElement('a:defRPr');
$objWriter->endElement(); // a:defRPr
$objWriter->endElement(); // a:pPr
if (is_array($caption)) {
$caption = $caption[0] ?? '';
}
$this->getParentWriter()->getWriterPartstringtable()->writeRichTextForCharts($objWriter, $caption, 'a');
$objWriter->endElement(); // a:p
$objWriter->endElement(); // c:rich
$objWriter->endElement(); // c:tx
$this->writeLayout($objWriter, $title->getLayout());
$objWriter->startElement('c:overlay');
$objWriter->writeAttribute('val', ($title->getOverlay()) ? '1' : '0');
$objWriter->endElement(); // c:overlay
$objWriter->endElement(); // c:title
}
/**
* Write Calculated Chart Title.
*/
private function writeCalculatedTitle(XMLWriter $objWriter, Title $title): bool
{
$calc = $title->getCalculatedTitle($this->getParentWriter()->getSpreadsheet());
if (empty($calc)) {
return false;
}
$objWriter->startElement('c:title');
$objWriter->startElement('c:tx');
$objWriter->startElement('c:strRef');
$objWriter->writeElement('c:f', $title->getCellReference());
$objWriter->startElement('c:strCache');
$objWriter->startElement('c:ptCount');
$objWriter->writeAttribute('val', '1');
$objWriter->endElement(); // c:ptCount
$objWriter->startElement('c:pt');
$objWriter->writeAttribute('idx', '0');
$objWriter->writeElement('c:v', $calc);
$objWriter->endElement(); // c:pt
$objWriter->endElement(); // c:strCache
$objWriter->endElement(); // c:strRef
$objWriter->endElement(); // c:tx
$this->writeLayout($objWriter, $title->getLayout());
$objWriter->startElement('c:overlay');
$objWriter->writeAttribute('val', ($title->getOverlay()) ? '1' : '0');
$objWriter->endElement(); // c:overlay
// c:spPr
// c:txPr
$labelFont = $title->getFont();
if ($labelFont !== null) {
$objWriter->startElement('c:txPr');
$objWriter->startElement('a:bodyPr');
$objWriter->endElement(); // a:bodyPr
$objWriter->startElement('a:lstStyle');
$objWriter->endElement(); // a:lstStyle
$this->writeLabelFont($objWriter, $labelFont, null);
$objWriter->endElement(); // c:txPr
}
$objWriter->endElement(); // c:title
return true;
}
/**
* Write Chart Legend.
*/
private function writeLegend(XMLWriter $objWriter, ?Legend $legend = null): void
{
if ($legend === null) {
return;
}
$objWriter->startElement('c:legend');
$objWriter->startElement('c:legendPos');
$objWriter->writeAttribute('val', $legend->getPosition());
$objWriter->endElement();
$this->writeLayout($objWriter, $legend->getLayout());
$objWriter->startElement('c:overlay');
$objWriter->writeAttribute('val', ($legend->getOverlay()) ? '1' : '0');
$objWriter->endElement();
$objWriter->startElement('c:spPr');
$fillColor = $legend->getFillColor();
if ($fillColor->isUsable()) {
$this->writeColor($objWriter, $fillColor);
}
$borderLines = $legend->getBorderLines();
$this->writeLineStyles($objWriter, $borderLines);
$this->writeEffects($objWriter, $borderLines);
$objWriter->endElement(); // c:spPr
$legendText = $legend->getLegendText();
$objWriter->startElement('c:txPr');
$objWriter->startElement('a:bodyPr');
$objWriter->endElement();
$objWriter->startElement('a:lstStyle');
$objWriter->endElement();
$objWriter->startElement('a:p');
$objWriter->startElement('a:pPr');
$objWriter->writeAttribute('rtl', '0');
$objWriter->startElement('a:defRPr');
if ($legendText !== null) {
$this->writeColor($objWriter, $legendText->getFillColorObject());
$this->writeEffects($objWriter, $legendText);
}
$objWriter->endElement(); // a:defRpr
$objWriter->endElement(); // a:pPr
$objWriter->startElement('a:endParaRPr');
$objWriter->writeAttribute('lang', 'en-US');
$objWriter->endElement(); // a:endParaRPr
$objWriter->endElement(); // a:p
$objWriter->endElement(); // c:txPr
$objWriter->endElement(); // c:legend
}
/**
* Write Chart Plot Area.
*/
private function writePlotArea(XMLWriter $objWriter, ?PlotArea $plotArea, ?Title $xAxisLabel = null, ?Title $yAxisLabel = null, ?Axis $xAxis = null, ?Axis $yAxis = null): void
{
if ($plotArea === null) {
return;
}
$id1 = $id2 = $id3 = '0';
$this->seriesIndex = 0;
$objWriter->startElement('c:plotArea');
$layout = $plotArea->getLayout();
$this->writeLayout($objWriter, $layout);
$chartTypes = self::getChartType($plotArea);
$catIsMultiLevelSeries = $valIsMultiLevelSeries = false;
$plotGroupingType = '';
$chartType = null;
foreach ($chartTypes as $chartType) {
$objWriter->startElement('c:' . $chartType);
$groupCount = $plotArea->getPlotGroupCount();
$plotGroup = null;
for ($i = 0; $i < $groupCount; ++$i) {
$plotGroup = $plotArea->getPlotGroupByIndex($i);
$groupType = $plotGroup->getPlotType();
if ($groupType == $chartType) {
$plotStyle = $plotGroup->getPlotStyle();
if (!empty($plotStyle) && $groupType === DataSeries::TYPE_RADARCHART) {
$objWriter->startElement('c:radarStyle');
$objWriter->writeAttribute('val', $plotStyle);
$objWriter->endElement();
} elseif (!empty($plotStyle) && $groupType === DataSeries::TYPE_SCATTERCHART) {
$objWriter->startElement('c:scatterStyle');
$objWriter->writeAttribute('val', $plotStyle);
$objWriter->endElement();
} elseif ($groupType === DataSeries::TYPE_SURFACECHART_3D || $groupType === DataSeries::TYPE_SURFACECHART) {
$objWriter->startElement('c:wireframe');
$objWriter->writeAttribute('val', $plotStyle ? '1' : '0');
$objWriter->endElement();
}
$this->writePlotGroup($plotGroup, $chartType, $objWriter, $catIsMultiLevelSeries, $valIsMultiLevelSeries, $plotGroupingType);
}
}
$this->writeDataLabels($objWriter, $layout);
if ($chartType === DataSeries::TYPE_LINECHART && $plotGroup) {
// Line only, Line3D can't be smoothed
$objWriter->startElement('c:smooth');
$objWriter->writeAttribute('val', (string) (int) $plotGroup->getSmoothLine());
$objWriter->endElement();
} elseif (($chartType === DataSeries::TYPE_BARCHART) || ($chartType === DataSeries::TYPE_BARCHART_3D)) {
$objWriter->startElement('c:gapWidth');
$objWriter->writeAttribute('val', '150');
$objWriter->endElement();
if ($plotGroupingType == 'percentStacked' || $plotGroupingType == 'stacked') {
$objWriter->startElement('c:overlap');
$objWriter->writeAttribute('val', '100');
$objWriter->endElement();
}
} elseif ($chartType === DataSeries::TYPE_BUBBLECHART) {
$scale = ($plotGroup === null) ? '' : (string) $plotGroup->getPlotStyle();
if ($scale !== '') {
$objWriter->startElement('c:bubbleScale');
$objWriter->writeAttribute('val', $scale);
$objWriter->endElement();
}
$objWriter->startElement('c:showNegBubbles');
$objWriter->writeAttribute('val', '0');
$objWriter->endElement();
} elseif ($chartType === DataSeries::TYPE_STOCKCHART) {
$objWriter->startElement('c:hiLowLines');
$objWriter->endElement();
$gapWidth = $plotArea->getGapWidth();
$upBars = $plotArea->getUseUpBars();
$downBars = $plotArea->getUseDownBars();
if ($gapWidth !== null || $upBars || $downBars) {
$objWriter->startElement('c:upDownBars');
if ($gapWidth !== null) {
$objWriter->startElement('c:gapWidth');
$objWriter->writeAttribute('val', "$gapWidth");
$objWriter->endElement();
}
if ($upBars) {
$objWriter->startElement('c:upBars');
$objWriter->endElement();
}
if ($downBars) {
$objWriter->startElement('c:downBars');
$objWriter->endElement();
}
$objWriter->endElement(); // c:upDownBars
}
}
// Generate 3 unique numbers to use for axId values
$id1 = '110438656';
$id2 = '110444544';
$id3 = '110365312'; // used in Surface Chart
if (($chartType !== DataSeries::TYPE_PIECHART) && ($chartType !== DataSeries::TYPE_PIECHART_3D) && ($chartType !== DataSeries::TYPE_DONUTCHART)) {
$objWriter->startElement('c:axId');
$objWriter->writeAttribute('val', $id1);
$objWriter->endElement();
$objWriter->startElement('c:axId');
$objWriter->writeAttribute('val', $id2);
$objWriter->endElement();
if ($chartType === DataSeries::TYPE_SURFACECHART_3D || $chartType === DataSeries::TYPE_SURFACECHART) {
$objWriter->startElement('c:axId');
$objWriter->writeAttribute('val', $id3);
$objWriter->endElement();
}
} else {
$objWriter->startElement('c:firstSliceAng');
$objWriter->writeAttribute('val', '0');
$objWriter->endElement();
if ($chartType === DataSeries::TYPE_DONUTCHART) {
$objWriter->startElement('c:holeSize');
$objWriter->writeAttribute('val', '50');
$objWriter->endElement();
}
}
$objWriter->endElement();
}
if (($chartType !== DataSeries::TYPE_PIECHART) && ($chartType !== DataSeries::TYPE_PIECHART_3D) && ($chartType !== DataSeries::TYPE_DONUTCHART)) {
if ($chartType === DataSeries::TYPE_BUBBLECHART) {
$this->writeValueAxis($objWriter, $xAxisLabel, $chartType, $id2, $id1, $catIsMultiLevelSeries, $xAxis ?? new Axis());
} else {
$this->writeCategoryAxis($objWriter, $xAxisLabel, $id1, $id2, $catIsMultiLevelSeries, $xAxis ?? new Axis());
}
$this->writeValueAxis($objWriter, $yAxisLabel, $chartType, $id1, $id2, $valIsMultiLevelSeries, $yAxis ?? new Axis());
if ($chartType === DataSeries::TYPE_SURFACECHART_3D || $chartType === DataSeries::TYPE_SURFACECHART) {
$this->writeSerAxis($objWriter, $id2, $id3);
}
}
$stops = $plotArea->getGradientFillStops();
if ($plotArea->getNoFill() || !empty($stops)) {
$objWriter->startElement('c:spPr');
if ($plotArea->getNoFill()) {
$objWriter->startElement('a:noFill');
$objWriter->endElement(); // a:noFill
}
if (!empty($stops)) {
$objWriter->startElement('a:gradFill');
$objWriter->startElement('a:gsLst');
foreach ($stops as $stop) {
$objWriter->startElement('a:gs');
$objWriter->writeAttribute('pos', (string) (Properties::PERCENTAGE_MULTIPLIER * (float) $stop[0]));
$this->writeColor($objWriter, $stop[1], false);
$objWriter->endElement(); // a:gs
}
$objWriter->endElement(); // a:gsLst
$angle = $plotArea->getGradientFillAngle();
if ($angle !== null) {
$objWriter->startElement('a:lin');
$objWriter->writeAttribute('ang', Properties::angleToXml($angle));
$objWriter->endElement(); // a:lin
}
$objWriter->endElement(); // a:gradFill
}
$objWriter->endElement(); // c:spPr
}
$objWriter->endElement(); // c:plotArea
}
private function writeDataLabelsBool(XMLWriter $objWriter, string $name, ?bool $value): void
{
if ($value !== null) {
$objWriter->startElement("c:$name");
$objWriter->writeAttribute('val', $value ? '1' : '0');
$objWriter->endElement();
}
}
/**
* Write Data Labels.
*/
private function writeDataLabels(XMLWriter $objWriter, ?Layout $chartLayout = null): void
{
if (!isset($chartLayout)) {
return;
}
$objWriter->startElement('c:dLbls');
$fillColor = $chartLayout->getLabelFillColor();
$borderColor = $chartLayout->getLabelBorderColor();
if ($fillColor && $fillColor->isUsable()) {
$objWriter->startElement('c:spPr');
$this->writeColor($objWriter, $fillColor);
if ($borderColor && $borderColor->isUsable()) {
$objWriter->startElement('a:ln');
$this->writeColor($objWriter, $borderColor);
$objWriter->endElement(); // a:ln
}
$objWriter->endElement(); // c:spPr
}
$labelFont = $chartLayout->getLabelFont();
if ($labelFont !== null) {
$objWriter->startElement('c:txPr');
$objWriter->startElement('a:bodyPr');
$objWriter->writeAttribute('wrap', 'square');
$objWriter->writeAttribute('lIns', '38100');
$objWriter->writeAttribute('tIns', '19050');
$objWriter->writeAttribute('rIns', '38100');
$objWriter->writeAttribute('bIns', '19050');
$objWriter->writeAttribute('anchor', 'ctr');
$objWriter->startElement('a:spAutoFit');
$objWriter->endElement(); // a:spAutoFit
$objWriter->endElement(); // a:bodyPr
$objWriter->startElement('a:lstStyle');
$objWriter->endElement(); // a:lstStyle
$this->writeLabelFont($objWriter, $labelFont, $chartLayout->getLabelEffects());
$objWriter->endElement(); // c:txPr
}
if ($chartLayout->getNumFmtCode() !== '') {
$objWriter->startElement('c:numFmt');
$objWriter->writeAttribute('formatCode', $chartLayout->getnumFmtCode());
$objWriter->writeAttribute('sourceLinked', (string) (int) $chartLayout->getnumFmtLinked());
$objWriter->endElement(); // c:numFmt
}
if ($chartLayout->getDLblPos() !== '') {
$objWriter->startElement('c:dLblPos');
$objWriter->writeAttribute('val', $chartLayout->getDLblPos());
$objWriter->endElement(); // c:dLblPos
}
$this->writeDataLabelsBool($objWriter, 'showLegendKey', $chartLayout->getShowLegendKey());
$this->writeDataLabelsBool($objWriter, 'showVal', $chartLayout->getShowVal());
$this->writeDataLabelsBool($objWriter, 'showCatName', $chartLayout->getShowCatName());
$this->writeDataLabelsBool($objWriter, 'showSerName', $chartLayout->getShowSerName());
$this->writeDataLabelsBool($objWriter, 'showPercent', $chartLayout->getShowPercent());
$this->writeDataLabelsBool($objWriter, 'showBubbleSize', $chartLayout->getShowBubbleSize());
$this->writeDataLabelsBool($objWriter, 'showLeaderLines', $chartLayout->getShowLeaderLines());
$objWriter->endElement(); // c:dLbls
}
/**
* Write Category Axis.
*/
private function writeCategoryAxis(XMLWriter $objWriter, ?Title $xAxisLabel, string $id1, string $id2, bool $isMultiLevelSeries, Axis $yAxis): void
{
// N.B. writeCategoryAxis may be invoked with the last parameter($yAxis) using $xAxis for ScatterChart, etc
// In that case, xAxis may contain values like the yAxis, or it may be a date axis (LINECHART).
$axisType = $yAxis->getAxisType();
if ($axisType !== '') {
$objWriter->startElement("c:$axisType");
} elseif ($yAxis->getAxisIsNumericFormat()) {
$objWriter->startElement('c:' . Axis::AXIS_TYPE_VALUE);
} else {
$objWriter->startElement('c:' . Axis::AXIS_TYPE_CATEGORY);
}
$majorGridlines = $yAxis->getMajorGridlines();
$minorGridlines = $yAxis->getMinorGridlines();
if ($id1 !== '0') {
$objWriter->startElement('c:axId');
$objWriter->writeAttribute('val', $id1);
$objWriter->endElement();
}
$objWriter->startElement('c:scaling');
if (is_numeric($yAxis->getAxisOptionsProperty('logBase'))) {
$logBase = $yAxis->getAxisOptionsProperty('logBase') + 0;
if ($logBase >= 2 && $logBase <= 1000) {
$objWriter->startElement('c:logBase');
$objWriter->writeAttribute('val', (string) $logBase);
$objWriter->endElement();
}
}
if ($yAxis->getAxisOptionsProperty('maximum') !== null) {
$objWriter->startElement('c:max');
$objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('maximum'));
$objWriter->endElement();
}
if ($yAxis->getAxisOptionsProperty('minimum') !== null) {
$objWriter->startElement('c:min');
$objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('minimum'));
$objWriter->endElement();
}
if (!empty($yAxis->getAxisOptionsProperty('orientation'))) {
$objWriter->startElement('c:orientation');
$objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('orientation'));
$objWriter->endElement();
}
$objWriter->endElement(); // c:scaling
$objWriter->startElement('c:delete');
$objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('hidden') ?? '0');
$objWriter->endElement();
$objWriter->startElement('c:axPos');
$objWriter->writeAttribute('val', 'b');
$objWriter->endElement();
if ($majorGridlines !== null) {
$objWriter->startElement('c:majorGridlines');
$objWriter->startElement('c:spPr');
$this->writeLineStyles($objWriter, $majorGridlines);
$this->writeEffects($objWriter, $majorGridlines);
$objWriter->endElement(); //end spPr
$objWriter->endElement(); //end majorGridLines
}
if ($minorGridlines !== null && $minorGridlines->getObjectState()) {
$objWriter->startElement('c:minorGridlines');
$objWriter->startElement('c:spPr');
$this->writeLineStyles($objWriter, $minorGridlines);
$this->writeEffects($objWriter, $minorGridlines);
$objWriter->endElement(); //end spPr
$objWriter->endElement(); //end minorGridLines
}
if ($xAxisLabel !== null) {
$objWriter->startElement('c:title');
$caption = $xAxisLabel->getCaption();
$objWriter->startElement('c:tx');
$objWriter->startElement('c:rich');
$objWriter->startElement('a:bodyPr');
$objWriter->endElement(); // a:bodyPr
$objWriter->startElement('a:lstStyle');
$objWriter->endElement(); // a::lstStyle
$objWriter->startElement('a:p');
if (is_array($caption)) {
$caption = $caption[0];
}
$this->getParentWriter()->getWriterPartstringtable()->writeRichTextForCharts($objWriter, $caption, 'a');
$objWriter->endElement(); // a:p
$objWriter->endElement(); // c:rich
$objWriter->endElement(); // c:tx
$layout = $xAxisLabel->getLayout();
$this->writeLayout($objWriter, $layout);
$objWriter->startElement('c:overlay');
$objWriter->writeAttribute('val', '0');
$objWriter->endElement(); // c:overlay
$objWriter->endElement(); // c:title
}
$objWriter->startElement('c:numFmt');
$objWriter->writeAttribute('formatCode', $yAxis->getAxisNumberFormat());
$objWriter->writeAttribute('sourceLinked', $yAxis->getAxisNumberSourceLinked());
$objWriter->endElement();
if (!empty($yAxis->getAxisOptionsProperty('major_tick_mark'))) {
$objWriter->startElement('c:majorTickMark');
$objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('major_tick_mark'));
$objWriter->endElement();
}
if (!empty($yAxis->getAxisOptionsProperty('minor_tick_mark'))) {
$objWriter->startElement('c:minorTickMark');
$objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('minor_tick_mark'));
$objWriter->endElement();
}
if (!empty($yAxis->getAxisOptionsProperty('axis_labels'))) {
$objWriter->startElement('c:tickLblPos');
$objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('axis_labels'));
$objWriter->endElement();
}
$textRotation = $yAxis->getAxisOptionsProperty('textRotation');
$axisText = $yAxis->getAxisText();
if ($axisText !== null || is_numeric($textRotation)) {
$objWriter->startElement('c:txPr');
$objWriter->startElement('a:bodyPr');
if (is_numeric($textRotation)) {
$objWriter->writeAttribute('rot', Properties::angleToXml((float) $textRotation));
}
$objWriter->endElement(); // a:bodyPr
$objWriter->startElement('a:lstStyle');
$objWriter->endElement(); // a:lstStyle
$this->writeLabelFont($objWriter, ($axisText === null) ? null : $axisText->getFont(), $axisText);
$objWriter->endElement(); // c:txPr
}
$objWriter->startElement('c:spPr');
$this->writeColor($objWriter, $yAxis->getFillColorObject());
$this->writeLineStyles($objWriter, $yAxis, $yAxis->getNoFill());
$this->writeEffects($objWriter, $yAxis);
$objWriter->endElement(); // spPr
if ($yAxis->getAxisOptionsProperty('major_unit') !== null) {
$objWriter->startElement('c:majorUnit');
$objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('major_unit'));
$objWriter->endElement();
}
if ($yAxis->getAxisOptionsProperty('minor_unit') !== null) {
$objWriter->startElement('c:minorUnit');
$objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('minor_unit'));
$objWriter->endElement();
}
if ($id2 !== '0') {
$objWriter->startElement('c:crossAx');
$objWriter->writeAttribute('val', $id2);
$objWriter->endElement();
if (!empty($yAxis->getAxisOptionsProperty('horizontal_crosses'))) {
$objWriter->startElement('c:crosses');
$objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('horizontal_crosses'));
$objWriter->endElement();
}
}
$objWriter->startElement('c:auto');
// LineChart with dateAx wants '0'
$objWriter->writeAttribute('val', ($axisType === Axis::AXIS_TYPE_DATE) ? '0' : '1');
$objWriter->endElement();
$objWriter->startElement('c:lblAlgn');
$objWriter->writeAttribute('val', 'ctr');
$objWriter->endElement();
$objWriter->startElement('c:lblOffset');
$objWriter->writeAttribute('val', '100');
$objWriter->endElement();
if ($axisType === Axis::AXIS_TYPE_DATE) {
$property = 'baseTimeUnit';
$propertyVal = $yAxis->getAxisOptionsProperty($property);
if (!empty($propertyVal)) {
$objWriter->startElement("c:$property");
$objWriter->writeAttribute('val', $propertyVal);
$objWriter->endElement();
}
$property = 'majorTimeUnit';
$propertyVal = $yAxis->getAxisOptionsProperty($property);
if (!empty($propertyVal)) {
$objWriter->startElement("c:$property");
$objWriter->writeAttribute('val', $propertyVal);
$objWriter->endElement();
}
$property = 'minorTimeUnit';
$propertyVal = $yAxis->getAxisOptionsProperty($property);
if (!empty($propertyVal)) {
$objWriter->startElement("c:$property");
$objWriter->writeAttribute('val', $propertyVal);
$objWriter->endElement();
}
}
if ($isMultiLevelSeries) {
$objWriter->startElement('c:noMultiLvlLbl');
$objWriter->writeAttribute('val', '0');
$objWriter->endElement();
}
$objWriter->endElement();
}
/**
* Write Value Axis.
*
* @param null|string $groupType Chart type
*/
private function writeValueAxis(XMLWriter $objWriter, ?Title $yAxisLabel, ?string $groupType, string $id1, string $id2, bool $isMultiLevelSeries, Axis $xAxis): void
{
$objWriter->startElement('c:' . Axis::AXIS_TYPE_VALUE);
$majorGridlines = $xAxis->getMajorGridlines();
$minorGridlines = $xAxis->getMinorGridlines();
if ($id2 !== '0') {
$objWriter->startElement('c:axId');
$objWriter->writeAttribute('val', $id2);
$objWriter->endElement();
}
$objWriter->startElement('c:scaling');
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | true |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php | src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Composer\Pcre\Preg;
use Exception;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as ActualWorksheet;
class DefinedNames
{
private XMLWriter $objWriter;
private Spreadsheet $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 $definedName): void
{
// definedName for named range
$local = -1;
if ($definedName->getLocalOnly() && $definedName->getScope() !== null) {
try {
$local = $definedName->getScope()->getParentOrThrow()->getIndex($definedName->getScope());
} catch (Exception) {
// See issue 2266 - deleting sheet which contains
// defined names will cause Exception above.
return;
}
}
$this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', $definedName->getName());
if ($local >= 0) {
$this->objWriter->writeAttribute(
'localSheetId',
"$local"
);
}
$definedRange = $this->getDefinedRange($definedName);
$this->objWriter->writeRawData($definedRange);
$this->objWriter->endElement();
}
/**
* Write Defined Name for autoFilter.
*/
private function writeNamedRangeForAutofilter(ActualWorksheet $worksheet, int $worksheetId = 0): void
{
// NamedRange for autoFilter
$autoFilterRange = $worksheet->getAutoFilter()->getRange();
if (!empty($autoFilterRange)) {
$this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', '_xlnm._FilterDatabase');
$this->objWriter->writeAttribute('localSheetId', "$worksheetId");
$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
[, $range[0]] = ActualWorksheet::extractSheetTitle($range[0], true);
$range[0] = Coordinate::absoluteCoordinate($range[0] ?? '');
if (count($range) > 1) {
$range[1] = Coordinate::absoluteCoordinate($range[1] ?? '');
}
$range = implode(':', $range);
$this->objWriter->writeRawData('\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!' . $range);
$this->objWriter->endElement();
}
}
/**
* Write Defined Name for PrintTitles.
*/
private function writeNamedRangeForPrintTitles(ActualWorksheet $worksheet, int $worksheetId = 0): void
{
// NamedRange for PrintTitles
if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
$this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', '_xlnm.Print_Titles');
$this->objWriter->writeAttribute('localSheetId', "$worksheetId");
// Setting string
$settingString = '';
// Columns to repeat
if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
$repeat = $worksheet->getPageSetup()->getColumnsToRepeatAtLeft();
$settingString .= '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
}
// Rows to repeat
if ($worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
$settingString .= ',';
}
$repeat = $worksheet->getPageSetup()->getRowsToRepeatAtTop();
$settingString .= '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
}
$this->objWriter->writeRawData($settingString);
$this->objWriter->endElement();
}
}
/**
* Write Defined Name for PrintTitles.
*/
private function writeNamedRangeForPrintArea(ActualWorksheet $worksheet, int $worksheetId = 0): void
{
// NamedRange for PrintArea
if ($worksheet->getPageSetup()->isPrintAreaSet()) {
$this->objWriter->startElement('definedName');
$this->objWriter->writeAttribute('name', '_xlnm.Print_Area');
$this->objWriter->writeAttribute('localSheetId', "$worksheetId");
// Print area
$printArea = Coordinate::splitRange($worksheet->getPageSetup()->getPrintArea());
$chunks = [];
foreach ($printArea as $printAreaRect) {
$printAreaRect[0] = Coordinate::absoluteReference($printAreaRect[0]);
$printAreaRect[1] = Coordinate::absoluteReference($printAreaRect[1]);
$chunks[] = '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!' . implode(':', $printAreaRect);
}
$this->objWriter->writeRawData(implode(',', $chunks));
$this->objWriter->endElement();
}
}
private function getDefinedRange(DefinedName $definedName): string
{
$definedRange = $definedName->getValue();
$splitCount = Preg::matchAllWithOffsets(
'/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
$definedRange,
$splitRanges
);
$lengths = array_map([StringHelper::class, 'strlenAllowNull'], 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
$ws = $definedName->getWorksheet();
$worksheet = ($ws === null) ? null : $ws->getTitle();
}
} else {
$worksheet = str_replace("''", "'", trim($worksheet, "'"));
}
if (!empty($worksheet)) {
$newRange = "'" . str_replace("'", "''", $worksheet) . "'!";
}
$newRange = "{$newRange}{$column}{$row}";
$definedRange = substr($definedRange, 0, $offset) . $newRange . substr($definedRange, $offset + $length);
}
if (str_starts_with($definedRange, '=')) {
$definedRange = substr($definedRange, 1);
}
return $definedRange;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/Comments.php | src/PhpSpreadsheet/Writer/Xlsx/Comments.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Comment;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
class Comments extends WriterPart
{
private const VALID_HORIZONTAL_ALIGNMENT = [
Alignment::HORIZONTAL_CENTER,
Alignment::HORIZONTAL_DISTRIBUTED,
Alignment::HORIZONTAL_JUSTIFY,
Alignment::HORIZONTAL_LEFT,
Alignment::HORIZONTAL_RIGHT,
];
/**
* Write comments to XML format.
*
* @return string XML Output
*/
public function writeComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet): string
{
// 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 = $worksheet->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', Namespaces::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 string $cellReference Cell reference
* @param Comment $comment Comment
* @param array<string, int> $authors Array of authors
*/
private function writeComment(XMLWriter $objWriter, string $cellReference, Comment $comment, array $authors): void
{
// comment
$objWriter->startElement('comment');
$objWriter->writeAttribute('ref', $cellReference);
$objWriter->writeAttribute('authorId', (string) $authors[$comment->getAuthor()]);
// text
$objWriter->startElement('text');
$this->getParentWriter()->getWriterPartstringtable()->writeRichText($objWriter, $comment->getText());
$objWriter->endElement();
$objWriter->endElement();
}
/**
* Write VML comments to XML format.
*
* @return string XML Output
*/
public function writeVMLComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet): string
{
// 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 = $worksheet->getComments();
// xml
$objWriter->startElement('xml');
$objWriter->writeAttribute('xmlns:v', Namespaces::URN_VML);
$objWriter->writeAttribute('xmlns:o', Namespaces::URN_MSOFFICE);
$objWriter->writeAttribute('xmlns:x', Namespaces::URN_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 string $cellReference Cell reference, eg: 'A1'
* @param Comment $comment Comment
*/
private function writeVMLComment(XMLWriter $objWriter, string $cellReference, Comment $comment): void
{
// Metadata
[$column, $row] = Coordinate::indexesFromString($cellReference);
$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:' . $comment->getMarginLeft() . ';margin-top:' . $comment->getMarginTop() . ';width:' . $comment->getWidth() . ';height:' . $comment->getHeight() . ';z-index:1;visibility:' . ($comment->getVisible() ? 'visible' : 'hidden'));
$objWriter->writeAttribute('fillcolor', '#' . $comment->getFillColor()->getRGB());
$objWriter->writeAttribute('o:insetmode', 'auto');
// v:fill
$objWriter->startElement('v:fill');
$objWriter->writeAttribute('color2', '#' . $comment->getFillColor()->getRGB());
if ($comment->hasBackgroundImage()) {
$bgImage = $comment->getBackgroundImage();
$objWriter->writeAttribute('o:relid', 'rId' . $bgImage->getImageIndex());
$objWriter->writeAttribute('o:title', $bgImage->getName());
$objWriter->writeAttribute('type', 'frame');
}
$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
$textBoxArray = [Comment::TEXTBOX_DIRECTION_RTL => 'rtl', Comment::TEXTBOX_DIRECTION_LTR => 'ltr'];
$textboxRtl = $textBoxArray[strtolower($comment->getTextBoxDirection())] ?? 'auto';
$objWriter->startElement('v:textbox');
$objWriter->writeAttribute('style', "mso-direction-alt:$textboxRtl");
// div
$objWriter->startElement('div');
$objWriter->writeAttribute('style', ($textboxRtl === 'rtl' ? 'text-align:right;direction:rtl' : '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:TextHAlign horizontal alignment of text
$alignment = strtolower($comment->getAlignment());
if (in_array($alignment, self::VALID_HORIZONTAL_ALIGNMENT, true)) {
$objWriter->writeElement('x:TextHAlign', ucfirst($alignment));
}
// x:Row
$objWriter->writeElement('x:Row', (string) ($row - 1));
// x:Column
$objWriter->writeElement('x:Column', (string) ($column - 1));
$objWriter->endElement();
$objWriter->endElement();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/WriterPart.php | src/PhpSpreadsheet/Writer/Xlsx/WriterPart.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
abstract class WriterPart
{
/**
* Parent Xlsx object.
*/
private Xlsx $parentWriter;
/**
* Get parent Xlsx object.
*/
public function getParentWriter(): Xlsx
{
return $this->parentWriter;
}
/**
* Set parent Xlsx object.
*/
public function __construct(Xlsx $writer)
{
$this->parentWriter = $writer;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/Style.php | src/PhpSpreadsheet/Writer/Xlsx/Style.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
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): string
{
// 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('xmlns', Namespaces::MAIN);
// numFmts
$objWriter->startElement('numFmts');
$objWriter->writeAttribute('count', (string) $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', (string) $this->getParentWriter()->getFontHashTable()->count());
// font
for ($i = 0; $i < $this->getParentWriter()->getFontHashTable()->count(); ++$i) {
$thisfont = $this->getParentWriter()->getFontHashTable()->getByIndex($i);
if ($thisfont !== null) {
$this->writeFont($objWriter, $thisfont, $spreadsheet);
}
}
$objWriter->endElement();
// fills
$objWriter->startElement('fills');
$objWriter->writeAttribute('count', (string) $this->getParentWriter()->getFillHashTable()->count());
// fill
for ($i = 0; $i < $this->getParentWriter()->getFillHashTable()->count(); ++$i) {
$thisfill = $this->getParentWriter()->getFillHashTable()->getByIndex($i);
if ($thisfill !== null) {
$this->writeFill($objWriter, $thisfill);
}
}
$objWriter->endElement();
// borders
$objWriter->startElement('borders');
$objWriter->writeAttribute('count', (string) $this->getParentWriter()->getBordersHashTable()->count());
// border
for ($i = 0; $i < $this->getParentWriter()->getBordersHashTable()->count(); ++$i) {
$thisborder = $this->getParentWriter()->getBordersHashTable()->getByIndex($i);
if ($thisborder !== null) {
$this->writeBorder($objWriter, $thisborder);
}
}
$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', (string) count($spreadsheet->getCellXfCollection()));
// xf
$alignment = new Alignment();
$defaultAlignHash = $alignment->getHashCode();
if ($defaultAlignHash !== $spreadsheet->getDefaultStyle()->getAlignment()->getHashCode()) {
$defaultAlignHash = '';
}
foreach ($spreadsheet->getCellXfCollection() as $cellXf) {
$this->writeCellStyleXf($objWriter, $cellXf, $spreadsheet, $defaultAlignHash);
}
$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', (string) $this->getParentWriter()->getStylesConditionalHashTable()->count());
// dxf
for ($i = 0; $i < $this->getParentWriter()->getStylesConditionalHashTable()->count(); ++$i) {
/** @var ?Conditional */
$thisstyle = $this->getParentWriter()->getStylesConditionalHashTable()->getByIndex($i);
if ($thisstyle !== null) {
$this->writeCellStyleDxf($objWriter, $thisstyle->getStyle(), $spreadsheet);
}
}
$objWriter->endElement();
// tableStyles
$objWriter->startElement('tableStyles');
$objWriter->writeAttribute('defaultTableStyle', 'TableStyleMedium9');
$objWriter->writeAttribute('defaultPivotStyle', 'PivotTableStyle1');
$objWriter->endElement();
$objWriter->endElement();
// Return
return $objWriter->getData();
}
/**
* Write Fill.
*/
private function writeFill(XMLWriter $objWriter, Fill $fill): void
{
// Check if this is a pattern type or gradient type
if (
$fill->getFillType() === Fill::FILL_GRADIENT_LINEAR
|| $fill->getFillType() === Fill::FILL_GRADIENT_PATH
) {
// Gradient fill
$this->writeGradientFill($objWriter, $fill);
} elseif ($fill->getFillType() !== null) {
// Pattern fill
$this->writePatternFill($objWriter, $fill);
}
}
/**
* Write Gradient Fill.
*/
private function writeGradientFill(XMLWriter $objWriter, Fill $fill): void
{
// fill
$objWriter->startElement('fill');
// gradientFill
$objWriter->startElement('gradientFill');
$objWriter->writeAttribute('type', (string) $fill->getFillType());
$objWriter->writeAttribute('degree', (string) $fill->getRotation());
// stop
$objWriter->startElement('stop');
$objWriter->writeAttribute('position', '0');
// color
if (!empty($fill->getStartColor()->getARGB())) {
$objWriter->startElement('color');
$objWriter->writeAttribute('rgb', $fill->getStartColor()->getARGB());
$objWriter->endElement();
}
$objWriter->endElement();
// stop
$objWriter->startElement('stop');
$objWriter->writeAttribute('position', '1');
// color
if (!empty($fill->getEndColor()->getARGB())) {
$objWriter->startElement('color');
$objWriter->writeAttribute('rgb', $fill->getEndColor()->getARGB());
$objWriter->endElement();
}
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
}
private static function writePatternColors(Fill $fill): bool
{
if ($fill->getFillType() === Fill::FILL_NONE) {
return false;
}
return $fill->getFillType() === Fill::FILL_SOLID || $fill->getColorsChanged();
}
/**
* Write Pattern Fill.
*/
private function writePatternFill(XMLWriter $objWriter, Fill $fill): void
{
// fill
$objWriter->startElement('fill');
// patternFill
$objWriter->startElement('patternFill');
if ($fill->getFillType()) {
$objWriter->writeAttribute('patternType', (string) $fill->getFillType());
}
if (self::writePatternColors($fill)) {
// fgColor
if ($fill->getStartColor()->getARGB()) {
if (!$fill->getEndColor()->getARGB() && $fill->getFillType() === Fill::FILL_SOLID) {
$objWriter->startElement('bgColor');
$objWriter->writeAttribute('rgb', $fill->getStartColor()->getARGB());
} else {
$objWriter->startElement('fgColor');
$objWriter->writeAttribute('rgb', $fill->getStartColor()->getARGB());
}
$objWriter->endElement();
}
// bgColor
if ($fill->getEndColor()->getARGB()) {
$objWriter->startElement('bgColor');
$objWriter->writeAttribute('rgb', $fill->getEndColor()->getARGB());
$objWriter->endElement();
}
}
$objWriter->endElement();
$objWriter->endElement();
}
/**
* @param-out true $fontStarted
*/
private function startFont(XMLWriter $objWriter, bool &$fontStarted): void
{
if (!$fontStarted) {
$fontStarted = true;
$objWriter->startElement('font');
}
}
/**
* Write Font.
*/
private function writeFont(XMLWriter $objWriter, Font $font, Spreadsheet $spreadsheet): void
{
$fontStarted = false;
// 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 ($font->getBold() !== null) {
$this->startFont($objWriter, $fontStarted);
$objWriter->startElement('b');
$objWriter->writeAttribute('val', $font->getBold() ? '1' : '0');
$objWriter->endElement();
}
// Italic
if ($font->getItalic() !== null) {
$this->startFont($objWriter, $fontStarted);
$objWriter->startElement('i');
$objWriter->writeAttribute('val', $font->getItalic() ? '1' : '0');
$objWriter->endElement();
}
// Strikethrough
if ($font->getStrikethrough() !== null) {
$this->startFont($objWriter, $fontStarted);
$objWriter->startElement('strike');
$objWriter->writeAttribute('val', $font->getStrikethrough() ? '1' : '0');
$objWriter->endElement();
}
// Underline
if ($font->getUnderline() !== null) {
$this->startFont($objWriter, $fontStarted);
$objWriter->startElement('u');
$objWriter->writeAttribute('val', $font->getUnderline());
$objWriter->endElement();
}
// Superscript / subscript
if ($font->getSuperscript() === true || $font->getSubscript() === true) {
$this->startFont($objWriter, $fontStarted);
$objWriter->startElement('vertAlign');
if ($font->getSuperscript() === true) {
$objWriter->writeAttribute('val', 'superscript');
} elseif ($font->getSubscript() === true) {
$objWriter->writeAttribute('val', 'subscript');
}
$objWriter->endElement();
}
// Size
if ($font->getSize() !== null) {
$this->startFont($objWriter, $fontStarted);
$objWriter->startElement('sz');
$objWriter->writeAttribute('val', StringHelper::formatNumber($font->getSize()));
$objWriter->endElement();
}
// Foreground color
if ($font->getAutoColor()) {
$this->startFont($objWriter, $fontStarted);
$objWriter->startElement('auto');
$objWriter->writeAttribute('val', '1');
$objWriter->endElement();
} elseif ($font->getColor()->getTheme() >= 0) {
$this->startFont($objWriter, $fontStarted);
$objWriter->startElement('color');
$objWriter->writeAttribute('theme', (string) $font->getColor()->getTheme());
$objWriter->endElement();
} elseif ($font->getColor()->getARGB() !== null) {
$this->startFont($objWriter, $fontStarted);
$objWriter->startElement('color');
$objWriter->writeAttribute('rgb', $font->getColor()->getARGB());
$objWriter->endElement();
}
// Name
if ($font->getName() !== null) {
$this->startFont($objWriter, $fontStarted);
$objWriter->startElement('name');
$objWriter->writeAttribute('val', $font->getName());
$objWriter->endElement();
$charset = $spreadsheet->getFontCharset($font->getName());
if ($charset >= 0 && $charset <= 255) {
$objWriter->startElement('charset');
$objWriter->writeAttribute('val', "$charset");
$objWriter->endElement();
}
}
if (!empty($font->getScheme())) {
$this->startFont($objWriter, $fontStarted);
$objWriter->startElement('scheme');
$objWriter->writeAttribute('val', $font->getScheme());
$objWriter->endElement();
}
if ($fontStarted) {
$objWriter->endElement();
}
}
/**
* Write Border.
*/
private function writeBorder(XMLWriter $objWriter, Borders $borders): void
{
// Write border
$objWriter->startElement('border');
// Diagonal?
switch ($borders->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', $borders->getLeft());
$this->writeBorderPr($objWriter, 'right', $borders->getRight());
$this->writeBorderPr($objWriter, 'top', $borders->getTop());
$this->writeBorderPr($objWriter, 'bottom', $borders->getBottom());
$this->writeBorderPr($objWriter, 'diagonal', $borders->getDiagonal());
$objWriter->endElement();
}
/**
* Write Cell Style Xf.
*/
private function writeCellStyleXf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $style, Spreadsheet $spreadsheet, string $defaultAlignHash): void
{
// xf
$objWriter->startElement('xf');
$objWriter->writeAttribute('xfId', '0');
$objWriter->writeAttribute('fontId', (string) (int) $this->getParentWriter()->getFontHashTable()->getIndexForHashCode($style->getFont()->getHashCode()));
if ($style->getQuotePrefix()) {
$objWriter->writeAttribute('quotePrefix', '1');
}
if ($style->getNumberFormat()->getBuiltInFormatCode() === false) {
$objWriter->writeAttribute('numFmtId', (string) (int) ($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($style->getNumberFormat()->getHashCode()) + 164));
} else {
$objWriter->writeAttribute('numFmtId', (string) (int) $style->getNumberFormat()->getBuiltInFormatCode());
}
$objWriter->writeAttribute('fillId', (string) (int) $this->getParentWriter()->getFillHashTable()->getIndexForHashCode($style->getFill()->getHashCode()));
$objWriter->writeAttribute('borderId', (string) (int) $this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($style->getBorders()->getHashCode()));
// Apply styles?
$objWriter->writeAttribute('applyFont', ($spreadsheet->getDefaultStyle()->getFont()->getHashCode() != $style->getFont()->getHashCode()) ? '1' : '0');
$objWriter->writeAttribute('applyNumberFormat', ($spreadsheet->getDefaultStyle()->getNumberFormat()->getHashCode() != $style->getNumberFormat()->getHashCode()) ? '1' : '0');
$objWriter->writeAttribute('applyFill', ($spreadsheet->getDefaultStyle()->getFill()->getHashCode() != $style->getFill()->getHashCode()) ? '1' : '0');
$objWriter->writeAttribute('applyBorder', ($spreadsheet->getDefaultStyle()->getBorders()->getHashCode() != $style->getBorders()->getHashCode()) ? '1' : '0');
if ($defaultAlignHash !== '' && $defaultAlignHash === $style->getAlignment()->getHashCode()) {
$applyAlignment = '0';
} else {
$applyAlignment = '1';
}
$objWriter->writeAttribute('applyAlignment', $applyAlignment);
if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) {
$objWriter->writeAttribute('applyProtection', 'true');
}
// alignment
if ($applyAlignment === '1') {
$objWriter->startElement('alignment');
$vertical = Alignment::VERTICAL_ALIGNMENT_FOR_XLSX[$style->getAlignment()->getVertical()] ?? '';
$horizontal = Alignment::HORIZONTAL_ALIGNMENT_FOR_XLSX[$style->getAlignment()->getHorizontal()] ?? '';
if ($horizontal !== '') {
$objWriter->writeAttribute('horizontal', $horizontal);
}
if ($vertical !== '') {
$objWriter->writeAttribute('vertical', $vertical);
}
$justifyLastLine = $style->getAlignment()->getJustifyLastLine();
if (is_bool($justifyLastLine)) {
$objWriter->writeAttribute('justifyLastLine', (string) (int) $justifyLastLine);
}
if ($style->getAlignment()->getTextRotation() >= 0) {
$textRotation = $style->getAlignment()->getTextRotation();
} else {
$textRotation = 90 - $style->getAlignment()->getTextRotation();
}
$objWriter->writeAttribute('textRotation', (string) $textRotation);
$objWriter->writeAttribute('wrapText', ($style->getAlignment()->getWrapText() ? 'true' : 'false'));
$objWriter->writeAttribute('shrinkToFit', ($style->getAlignment()->getShrinkToFit() ? 'true' : 'false'));
if ($style->getAlignment()->getIndent() > 0) {
$objWriter->writeAttribute('indent', (string) $style->getAlignment()->getIndent());
}
if ($style->getAlignment()->getReadOrder() > 0) {
$objWriter->writeAttribute('readingOrder', (string) $style->getAlignment()->getReadOrder());
}
$objWriter->endElement();
}
// protection
if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) {
$objWriter->startElement('protection');
if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT) {
$objWriter->writeAttribute('locked', ($style->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
}
if ($style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) {
$objWriter->writeAttribute('hidden', ($style->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
}
$objWriter->endElement();
}
$objWriter->endElement();
}
/**
* Write Cell Style Dxf.
*/
private function writeCellStyleDxf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $style, Spreadsheet $spreadsheet): void
{
// dxf
$objWriter->startElement('dxf');
// font
$this->writeFont($objWriter, $style->getFont(), $spreadsheet);
// numFmt
$this->writeNumFmt($objWriter, $style->getNumberFormat());
// fill
$this->writeFill($objWriter, $style->getFill());
// border
$this->writeBorder($objWriter, $style->getBorders());
$objWriter->endElement();
}
/**
* Write BorderPr.
*
* @param string $name Element name
*/
private function writeBorderPr(XMLWriter $objWriter, string $name, Border $border): void
{
// Write BorderPr
if ($border->getBorderStyle() === Border::BORDER_OMIT) {
return;
}
$objWriter->startElement($name);
if ($border->getBorderStyle() !== Border::BORDER_NONE) {
$objWriter->writeAttribute('style', $border->getBorderStyle());
// color
if ($border->getColor()->getARGB() !== null) {
$objWriter->startElement('color');
$objWriter->writeAttribute('rgb', $border->getColor()->getARGB());
$objWriter->endElement();
}
}
$objWriter->endElement();
}
/**
* Write NumberFormat.
*
* @param int $id Number Format identifier
*/
private function writeNumFmt(XMLWriter $objWriter, ?NumberFormat $numberFormat, int $id = 0): void
{
// Translate formatcode
$formatCode = ($numberFormat === null) ? null : $numberFormat->getFormatCode();
// numFmt
if ($formatCode !== null) {
$objWriter->startElement('numFmt');
$objWriter->writeAttribute('numFmtId', (string) ($id + 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): array
{
return $spreadsheet->getCellXfCollection();
}
/**
* Get an array of all conditional styles.
*
* @return Conditional[] All conditional styles in PhpSpreadsheet
*/
public function allConditionalStyles(Spreadsheet $spreadsheet): array
{
// 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): array
{
// 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);
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): array
{
// Get an array of unique fonts
$aFonts = [];
$aStyles = $this->allStyles($spreadsheet);
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): array
{
// Get an array of unique borders
$aBorders = [];
$aStyles = $this->allStyles($spreadsheet);
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): array
{
// Get an array of unique number formats
$aNumFmts = [];
$aStyles = $this->allStyles($spreadsheet);
foreach ($aStyles as $style) {
if ($style->getNumberFormat()->getBuiltInFormatCode() === false && !isset($aNumFmts[$style->getNumberFormat()->getHashCode()])) {
$aNumFmts[$style->getNumberFormat()->getHashCode()] = $style->getNumberFormat();
}
}
return $aNumFmts;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx/FunctionPrefix.php | src/PhpSpreadsheet/Writer/Xlsx/FunctionPrefix.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Composer\Pcre\Preg;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
class FunctionPrefix
{
const XLFNREGEXP = '/(?:_xlfn\.)?((?:_xlws\.)?\b('
// functions added with Excel 2010
. 'beta[.]dist'
. '|beta[.]inv'
. '|binom[.]dist'
. '|binom[.]inv'
. '|ceiling[.]precise'
. '|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'
. '|floor[.]precise'
. '|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'
// probably added with Excel 2010 but not properly documented
. '|base'
// 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'
. '|ifs'
. '|maxifs'
. '|minifs'
. '|textjoin'
// functions added with Excel 365
. '|anchorarray'
. '|arraytotext'
. '|bycol'
. '|byrow'
. '|call'
. '|choosecols'
. '|chooserows'
. '|drop'
. '|expand'
. '|filter'
. '|groupby'
. '|hstack'
. '|isomitted'
. '|lambda'
. '|let'
. '|makearray'
. '|map'
. '|randarray'
. '|reduce'
. '|register[.]id'
. '|scan'
. '|sequence'
. '|single'
. '|sort'
. '|sortby'
. '|take'
. '|textafter'
. '|textbefore'
. '|textjoin'
. '|textsplit'
. '|tocol'
. '|torow'
. '|unique'
. '|valuetotext'
. '|vstack'
. '|wrapcols'
. '|wraprows'
. '|xlookup'
. '|xmatch'
. '))\s*\(/Umui';
const XLWSREGEXP = '/(?<!_xlws\.)('
// functions added with Excel 365
. 'filter'
. '|sort'
. ')\s*\(/mui';
/**
* Prefix function name in string with _xlfn. where required.
*/
protected static function addXlfnPrefix(string $functionString): string
{
return Preg::replace(self::XLFNREGEXP, '_xlfn.$1(', $functionString);
}
/**
* Prefix function name in string with _xlws. where required.
*/
protected static function addXlwsPrefix(string $functionString): string
{
return Preg::replace(self::XLWSREGEXP, '_xlws.$1(', $functionString);
}
/**
* Prefix function name in string with _xlfn. where required.
*/
public static function addFunctionPrefix(string $functionString): string
{
$functionString = Preg::replaceCallback(
Calculation::CALCULATION_REGEXP_CELLREF_SPILL,
fn (array $matches) => 'ANCHORARRAY(' . substr((string) $matches[0], 0, -1) . ')',
$functionString
);
return self::addXlwsPrefix(self::addXlfnPrefix($functionString));
}
/**
* Prefix function name in string with _xlfn. where required.
* Leading character, expected to be equals sign, is stripped.
*/
public static function addFunctionPrefixStripEquals(string $functionString): string
{
$functionString = Preg::replace(
[
'/\b(CEILING|FLOOR)[.]ODS\s*[(]/',
'/\b(CEILING|FLOOR)[.]XCL\s*[(]/',
],
[
'$1.MATH(',
'$1(',
],
$functionString
);
return self::addFunctionPrefix(substr($functionString, 1));
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/AxisText.php | src/PhpSpreadsheet/Chart/AxisText.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
use PhpOffice\PhpSpreadsheet\Style\Font;
class AxisText extends Properties
{
private ?int $rotation = null;
private Font $font;
public function __construct()
{
parent::__construct();
$this->font = new Font();
$this->font->setSize(null, true);
}
public function setRotation(?int $rotation): self
{
$this->rotation = $rotation;
return $this;
}
public function getRotation(): ?int
{
return $this->rotation;
}
public function getFillColorObject(): ChartColor
{
$fillColor = $this->font->getChartColor();
if ($fillColor === null) {
$fillColor = new ChartColor();
$this->font->setChartColorFromObject($fillColor);
}
return $fillColor;
}
public function getFont(): Font
{
return $this->font;
}
public function setFont(Font $font): self
{
$this->font = $font;
return $this;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
parent::__clone();
$this->font = clone $this->font;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/Layout.php | src/PhpSpreadsheet/Chart/Layout.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
use PhpOffice\PhpSpreadsheet\Style\Font;
class Layout
{
/**
* layoutTarget.
*/
private ?string $layoutTarget = null;
/**
* X Mode.
*/
private ?string $xMode = null;
/**
* Y Mode.
*/
private ?string $yMode = null;
/**
* X-Position.
*/
private ?float $xPos = null;
/**
* Y-Position.
*/
private ?float $yPos = null;
/**
* width.
*/
private ?float $width = null;
/**
* height.
*/
private ?float $height = null;
/**
* Position - t=top.
*/
private string $dLblPos = '';
private string $numFmtCode = '';
private bool $numFmtLinked = false;
/**
* show legend key
* Specifies that legend keys should be shown in data labels.
*/
private ?bool $showLegendKey = null;
/**
* show value
* Specifies that the value should be shown in a data label.
*/
private ?bool $showVal = null;
/**
* show category name
* Specifies that the category name should be shown in the data label.
*/
private ?bool $showCatName = null;
/**
* show data series name
* Specifies that the series name should be shown in the data label.
*/
private ?bool $showSerName = null;
/**
* show percentage
* Specifies that the percentage should be shown in the data label.
*/
private ?bool $showPercent = null;
/**
* show bubble size.
*/
private ?bool $showBubbleSize = null;
/**
* show leader lines
* Specifies that leader lines should be shown for the data label.
*/
private ?bool $showLeaderLines = null;
private ?ChartColor $labelFillColor = null;
private ?ChartColor $labelBorderColor = null;
private ?Font $labelFont = null;
private ?Properties $labelEffects = null;
/**
* Create a new Layout.
*
* @param array<mixed> $layout
*/
public function __construct(array $layout = [])
{
/** @var array{layoutTarget?: string, xMode?: string, yMode?: string, x?: float, y?: float, w?:float, h?:float, dLblPos?: string, labelFont?: ?mixed, labelFontColor?: ?mixed, labelEffects?: ?mixed, numFmtCode?: string} $layout */
if (isset($layout['layoutTarget'])) {
$this->layoutTarget = $layout['layoutTarget'];
}
if (isset($layout['xMode'])) {
$this->xMode = $layout['xMode'];
}
if (isset($layout['yMode'])) {
$this->yMode = $layout['yMode'];
}
if (isset($layout['x'])) {
$this->xPos = (float) $layout['x'];
}
if (isset($layout['y'])) {
$this->yPos = (float) $layout['y'];
}
if (isset($layout['w'])) {
$this->width = (float) $layout['w'];
}
if (isset($layout['h'])) {
$this->height = (float) $layout['h'];
}
if (isset($layout['dLblPos'])) {
$this->dLblPos = (string) $layout['dLblPos'];
}
if (isset($layout['numFmtCode'])) {
$this->numFmtCode = (string) $layout['numFmtCode'];
}
$this->initBoolean($layout, 'showLegendKey');
$this->initBoolean($layout, 'showVal');
$this->initBoolean($layout, 'showCatName');
$this->initBoolean($layout, 'showSerName');
$this->initBoolean($layout, 'showPercent');
$this->initBoolean($layout, 'showBubbleSize');
$this->initBoolean($layout, 'showLeaderLines');
$this->initBoolean($layout, 'numFmtLinked');
$this->initColor($layout, 'labelFillColor');
$this->initColor($layout, 'labelBorderColor');
$labelFont = $layout['labelFont'] ?? null;
if ($labelFont instanceof Font) {
$this->labelFont = $labelFont;
}
$labelFontColor = $layout['labelFontColor'] ?? null;
if ($labelFontColor instanceof ChartColor) {
$this->setLabelFontColor($labelFontColor);
}
$labelEffects = $layout['labelEffects'] ?? null;
if ($labelEffects instanceof Properties) {
$this->labelEffects = $labelEffects;
}
}
/** @param mixed[] $layout */
private function initBoolean(array $layout, string $name): void
{
if (isset($layout[$name])) {
$this->$name = (bool) $layout[$name];
}
}
/** @param mixed[] $layout */
private function initColor(array $layout, string $name): void
{
if (isset($layout[$name]) && $layout[$name] instanceof ChartColor) {
$this->$name = $layout[$name];
}
}
/**
* Get Layout Target.
*/
public function getLayoutTarget(): ?string
{
return $this->layoutTarget;
}
/**
* Set Layout Target.
*
* @return $this
*/
public function setLayoutTarget(?string $target): static
{
$this->layoutTarget = $target;
return $this;
}
/**
* Get X-Mode.
*/
public function getXMode(): ?string
{
return $this->xMode;
}
/**
* Set X-Mode.
*
* @return $this
*/
public function setXMode(?string $mode): static
{
$this->xMode = (string) $mode;
return $this;
}
/**
* Get Y-Mode.
*/
public function getYMode(): ?string
{
return $this->yMode;
}
/**
* Set Y-Mode.
*
* @return $this
*/
public function setYMode(?string $mode): static
{
$this->yMode = (string) $mode;
return $this;
}
/**
* Get X-Position.
*/
public function getXPosition(): null|float|int
{
return $this->xPos;
}
/**
* Set X-Position.
*
* @return $this
*/
public function setXPosition(float $position): static
{
$this->xPos = $position;
return $this;
}
/**
* Get Y-Position.
*/
public function getYPosition(): ?float
{
return $this->yPos;
}
/**
* Set Y-Position.
*
* @return $this
*/
public function setYPosition(float $position): static
{
$this->yPos = $position;
return $this;
}
/**
* Get Width.
*/
public function getWidth(): ?float
{
return $this->width;
}
/**
* Set Width.
*
* @return $this
*/
public function setWidth(?float $width): static
{
$this->width = $width;
return $this;
}
/**
* Get Height.
*/
public function getHeight(): ?float
{
return $this->height;
}
/**
* Set Height.
*
* @return $this
*/
public function setHeight(?float $height): static
{
$this->height = $height;
return $this;
}
public function getShowLegendKey(): ?bool
{
return $this->showLegendKey;
}
/**
* Set show legend key
* Specifies that legend keys should be shown in data labels.
*/
public function setShowLegendKey(?bool $showLegendKey): self
{
$this->showLegendKey = $showLegendKey;
return $this;
}
public function getShowVal(): ?bool
{
return $this->showVal;
}
/**
* Set show val
* Specifies that the value should be shown in data labels.
*/
public function setShowVal(?bool $showDataLabelValues): self
{
$this->showVal = $showDataLabelValues;
return $this;
}
public function getShowCatName(): ?bool
{
return $this->showCatName;
}
/**
* Set show cat name
* Specifies that the category name should be shown in data labels.
*/
public function setShowCatName(?bool $showCategoryName): self
{
$this->showCatName = $showCategoryName;
return $this;
}
public function getShowSerName(): ?bool
{
return $this->showSerName;
}
/**
* Set show data series name.
* Specifies that the series name should be shown in data labels.
*/
public function setShowSerName(?bool $showSeriesName): self
{
$this->showSerName = $showSeriesName;
return $this;
}
public function getShowPercent(): ?bool
{
return $this->showPercent;
}
/**
* Set show percentage.
* Specifies that the percentage should be shown in data labels.
*/
public function setShowPercent(?bool $showPercentage): self
{
$this->showPercent = $showPercentage;
return $this;
}
public function getShowBubbleSize(): ?bool
{
return $this->showBubbleSize;
}
/**
* Set show bubble size.
* Specifies that the bubble size should be shown in data labels.
*/
public function setShowBubbleSize(?bool $showBubbleSize): self
{
$this->showBubbleSize = $showBubbleSize;
return $this;
}
public function getShowLeaderLines(): ?bool
{
return $this->showLeaderLines;
}
/**
* Set show leader lines.
* Specifies that leader lines should be shown in data labels.
*/
public function setShowLeaderLines(?bool $showLeaderLines): self
{
$this->showLeaderLines = $showLeaderLines;
return $this;
}
public function getLabelFillColor(): ?ChartColor
{
return $this->labelFillColor;
}
public function setLabelFillColor(?ChartColor $chartColor): self
{
$this->labelFillColor = $chartColor;
return $this;
}
public function getLabelBorderColor(): ?ChartColor
{
return $this->labelBorderColor;
}
public function setLabelBorderColor(?ChartColor $chartColor): self
{
$this->labelBorderColor = $chartColor;
return $this;
}
public function getLabelFont(): ?Font
{
return $this->labelFont;
}
public function setLabelFont(?Font $labelFont): self
{
$this->labelFont = $labelFont;
return $this;
}
public function getLabelEffects(): ?Properties
{
return $this->labelEffects;
}
public function getLabelFontColor(): ?ChartColor
{
if ($this->labelFont === null) {
return null;
}
return $this->labelFont->getChartColor();
}
public function setLabelFontColor(?ChartColor $chartColor): self
{
if ($this->labelFont === null) {
$this->labelFont = new Font();
$this->labelFont->setSize(null, true);
}
$this->labelFont->setChartColorFromObject($chartColor);
return $this;
}
public function getDLblPos(): string
{
return $this->dLblPos;
}
public function setDLblPos(string $dLblPos): self
{
$this->dLblPos = $dLblPos;
return $this;
}
public function getNumFmtCode(): string
{
return $this->numFmtCode;
}
public function setNumFmtCode(string $numFmtCode): self
{
$this->numFmtCode = $numFmtCode;
return $this;
}
public function getNumFmtLinked(): bool
{
return $this->numFmtLinked;
}
public function setNumFmtLinked(bool $numFmtLinked): self
{
$this->numFmtLinked = $numFmtLinked;
return $this;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$this->labelFillColor = ($this->labelFillColor === null) ? null : clone $this->labelFillColor;
$this->labelBorderColor = ($this->labelBorderColor === null) ? null : clone $this->labelBorderColor;
$this->labelFont = ($this->labelFont === null) ? null : clone $this->labelFont;
$this->labelEffects = ($this->labelEffects === null) ? null : clone $this->labelEffects;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/Legend.php | src/PhpSpreadsheet/Chart/Legend.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
class Legend
{
/** Legend positions */
const XL_LEGEND_POSITION_BOTTOM = -4107; // Below the chart.
const XL_LEGEND_POSITION_CORNER = 2; // In the upper right-hand corner of the chart border.
const XL_LEGEND_POSITION_CUSTOM = -4161; // A custom position.
const XL_LEGEND_POSITION_LEFT = -4131; // Left of the chart.
const XL_LEGEND_POSITION_RIGHT = -4152; // Right of the chart.
const XL_LEGEND_POSITION_TOP = -4160; // Above the chart.
const POSITION_RIGHT = 'r';
const POSITION_LEFT = 'l';
const POSITION_BOTTOM = 'b';
const POSITION_TOP = 't';
const POSITION_TOPRIGHT = 'tr';
const POSITION_XLREF = [
self::XL_LEGEND_POSITION_BOTTOM => self::POSITION_BOTTOM,
self::XL_LEGEND_POSITION_CORNER => self::POSITION_TOPRIGHT,
self::XL_LEGEND_POSITION_CUSTOM => '??',
self::XL_LEGEND_POSITION_LEFT => self::POSITION_LEFT,
self::XL_LEGEND_POSITION_RIGHT => self::POSITION_RIGHT,
self::XL_LEGEND_POSITION_TOP => self::POSITION_TOP,
];
/**
* Legend position.
*/
private string $position = self::POSITION_RIGHT;
/**
* Allow overlay of other elements?
*/
private bool $overlay = true;
/**
* Legend Layout.
*/
private ?Layout $layout;
private GridLines $borderLines;
private ChartColor $fillColor;
private ?AxisText $legendText = null;
/**
* Create a new Legend.
*/
public function __construct(string $position = self::POSITION_RIGHT, ?Layout $layout = null, bool $overlay = false)
{
$this->setPosition($position);
$this->layout = $layout;
$this->setOverlay($overlay);
$this->borderLines = new GridLines();
$this->fillColor = new ChartColor();
}
public function getFillColor(): ChartColor
{
return $this->fillColor;
}
/**
* Get legend position as an Excel string value.
*/
public function getPosition(): string
{
return $this->position;
}
/**
* Get legend position using an Excel string value.
*
* @param string $position see self::POSITION_*
*/
public function setPosition(string $position): bool
{
if (!in_array($position, self::POSITION_XLREF)) {
return false;
}
$this->position = $position;
return true;
}
/**
* Get legend position as an Excel internal numeric value.
*/
public function getPositionXL(): false|int
{
return array_search($this->position, self::POSITION_XLREF);
}
/**
* Set legend position using an Excel internal numeric value.
*
* @param int $positionXL see self::XL_LEGEND_POSITION_*
*/
public function setPositionXL(int $positionXL): bool
{
if (!isset(self::POSITION_XLREF[$positionXL])) {
return false;
}
$this->position = self::POSITION_XLREF[$positionXL];
return true;
}
/**
* Get allow overlay of other elements?
*/
public function getOverlay(): bool
{
return $this->overlay;
}
/**
* Set allow overlay of other elements?
*/
public function setOverlay(bool $overlay): void
{
$this->overlay = $overlay;
}
/**
* Get Layout.
*/
public function getLayout(): ?Layout
{
return $this->layout;
}
public function getLegendText(): ?AxisText
{
return $this->legendText;
}
public function setLegendText(?AxisText $legendText): self
{
$this->legendText = $legendText;
return $this;
}
public function getBorderLines(): GridLines
{
return $this->borderLines;
}
public function setBorderLines(GridLines $borderLines): self
{
$this->borderLines = $borderLines;
return $this;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$this->layout = ($this->layout === null) ? null : clone $this->layout;
$this->legendText = ($this->legendText === null) ? null : clone $this->legendText;
$this->borderLines = clone $this->borderLines;
$this->fillColor = clone $this->fillColor;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/Title.php | src/PhpSpreadsheet/Chart/Title.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Font;
class Title
{
public const TITLE_CELL_REFERENCE
= '/^(.*)!' // beginning of string, everything up to ! is match[1]
. '[$]([A-Z]{1,3})' // absolute column string match[2]
. '[$](\d{1,7})$/i'; // absolute row string match[3]
/**
* Title Caption.
*
* @var array<RichText|string>|RichText|string
*/
private array|RichText|string $caption;
/**
* Allow overlay of other elements?
*/
private bool $overlay = true;
/**
* Title Layout.
*/
private ?Layout $layout;
private string $cellReference = '';
private ?Font $font = null;
/**
* Create a new Title.
*
* @param array<RichText|string>|RichText|string $caption
*/
public function __construct(array|RichText|string $caption = '', ?Layout $layout = null, bool $overlay = false)
{
$this->caption = $caption;
$this->layout = $layout;
$this->setOverlay($overlay);
}
/**
* Get caption.
*
* @return array<RichText|string>|RichText|string
*/
public function getCaption(): array|RichText|string
{
return $this->caption;
}
public function getCaptionText(?Spreadsheet $spreadsheet = null): string
{
if ($spreadsheet !== null) {
$caption = $this->getCalculatedTitle($spreadsheet);
if ($caption !== null) {
return $caption;
}
}
$caption = $this->caption;
if (is_string($caption)) {
return $caption;
}
if ($caption instanceof RichText) {
return $caption->getPlainText();
}
$retVal = '';
foreach ($caption as $textx) {
/** @var RichText|string $text */
$text = $textx;
if ($text instanceof RichText) {
$retVal .= $text->getPlainText();
} else {
$retVal .= $text;
}
}
return $retVal;
}
/**
* Set caption.
*
* @param array<RichText|string>|RichText|string $caption
*
* @return $this
*/
public function setCaption(array|RichText|string $caption): static
{
$this->caption = $caption;
return $this;
}
/**
* Get allow overlay of other elements?
*/
public function getOverlay(): bool
{
return $this->overlay;
}
/**
* Set allow overlay of other elements?
*/
public function setOverlay(bool $overlay): self
{
$this->overlay = $overlay;
return $this;
}
public function getLayout(): ?Layout
{
return $this->layout;
}
public function setCellReference(string $cellReference): self
{
$this->cellReference = $cellReference;
return $this;
}
public function getCellReference(): string
{
return $this->cellReference;
}
public function getCalculatedTitle(?Spreadsheet $spreadsheet): ?string
{
preg_match(self::TITLE_CELL_REFERENCE, $this->cellReference, $matches);
if (count($matches) === 0 || $spreadsheet === null) {
return null;
}
$sheetName = preg_replace("/^'(.*)'$/", '$1', $matches[1]) ?? '';
return $spreadsheet->getSheetByName($sheetName)?->getCell($matches[2] . $matches[3])?->getFormattedValue();
}
public function getFont(): ?Font
{
return $this->font;
}
public function setFont(?Font $font): self
{
$this->font = $font;
return $this;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$this->layout = ($this->layout === null) ? null : clone $this->layout;
$this->font = ($this->font === null) ? null : clone $this->font;
if (is_array($this->caption)) {
$captions = [];
foreach ($this->caption as $caption) {
$captions[] = is_object($caption) ? (clone $caption) : $caption;
}
$this->caption = $captions;
} else {
$this->caption = is_object($this->caption) ? (clone $this->caption) : $this->caption;
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/Exception.php | src/PhpSpreadsheet/Chart/Exception.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
class Exception extends PhpSpreadsheetException
{
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/Axis.php | src/PhpSpreadsheet/Chart/Axis.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
/**
* Created by PhpStorm.
* User: Wiktor Trzonkowski
* Date: 6/17/14
* Time: 12:11 PM.
*/
class Axis extends Properties
{
const AXIS_TYPE_CATEGORY = 'catAx';
const AXIS_TYPE_DATE = 'dateAx';
const AXIS_TYPE_VALUE = 'valAx';
const TIME_UNIT_DAYS = 'days';
const TIME_UNIT_MONTHS = 'months';
const TIME_UNIT_YEARS = 'years';
public function __construct()
{
parent::__construct();
$this->fillColor = new ChartColor();
}
/**
* Chart Major Gridlines as.
*/
private ?GridLines $majorGridlines = null;
/**
* Chart Minor Gridlines as.
*/
private ?GridLines $minorGridlines = null;
/**
* Axis Number.
*
* @var array{format: string, source_linked: int, numeric: ?bool}
*/
private array $axisNumber = [
'format' => self::FORMAT_CODE_GENERAL,
'source_linked' => 1,
'numeric' => null,
];
private string $axisType = '';
private ?AxisText $axisText = null;
private ?Title $dispUnitsTitle = null;
/**
* Axis Options.
*
* @var array<string, null|string>
*/
private array $axisOptions = [
'minimum' => null,
'maximum' => null,
'major_unit' => null,
'minor_unit' => null,
'orientation' => self::ORIENTATION_NORMAL,
'minor_tick_mark' => self::TICK_MARK_NONE,
'major_tick_mark' => self::TICK_MARK_NONE,
'axis_labels' => self::AXIS_LABELS_NEXT_TO,
'horizontal_crosses' => self::HORIZONTAL_CROSSES_AUTOZERO,
'horizontal_crosses_value' => null,
'textRotation' => null,
'hidden' => null,
'majorTimeUnit' => self::TIME_UNIT_YEARS,
'minorTimeUnit' => self::TIME_UNIT_MONTHS,
'baseTimeUnit' => self::TIME_UNIT_DAYS,
'logBase' => null,
'dispUnitsBuiltIn' => null,
];
public const DISP_UNITS_HUNDREDS = 'hundreds';
public const DISP_UNITS_THOUSANDS = 'thousands';
public const DISP_UNITS_TEN_THOUSANDS = 'tenThousands';
public const DISP_UNITS_HUNDRED_THOUSANDS = 'hundredThousands';
public const DISP_UNITS_MILLIONS = 'millions';
public const DISP_UNITS_TEN_MILLIONS = 'tenMillions';
public const DISP_UNITS_HUNDRED_MILLIONS = 'hundredMillions';
public const DISP_UNITS_BILLIONS = 'billions';
public const DISP_UNITS_TRILLIONS = 'trillions';
public const TRILLION_INDEX = (PHP_INT_SIZE > 4) ? 1000000000000 : '1000000000000';
public const DISP_UNITS_BUILTIN_INT = [
100 => self::DISP_UNITS_HUNDREDS,
1000 => self::DISP_UNITS_THOUSANDS,
10000 => self::DISP_UNITS_TEN_THOUSANDS,
100000 => self::DISP_UNITS_HUNDRED_THOUSANDS,
1000000 => self::DISP_UNITS_MILLIONS,
10000000 => self::DISP_UNITS_TEN_MILLIONS,
100000000 => self::DISP_UNITS_HUNDRED_MILLIONS,
1000000000 => self::DISP_UNITS_BILLIONS,
self::TRILLION_INDEX => self::DISP_UNITS_TRILLIONS, // overflow for 32-bit
];
/**
* Fill Properties.
*/
private ChartColor $fillColor;
private const NUMERIC_FORMAT = [
Properties::FORMAT_CODE_NUMBER,
Properties::FORMAT_CODE_DATE,
Properties::FORMAT_CODE_DATE_ISO8601,
];
private bool $noFill = false;
/**
* Get Series Data Type.
*/
public function setAxisNumberProperties(string $format_code, ?bool $numeric = null, int $sourceLinked = 0): void
{
$format = $format_code;
$this->axisNumber['format'] = $format;
$this->axisNumber['source_linked'] = $sourceLinked;
if (is_bool($numeric)) {
$this->axisNumber['numeric'] = $numeric;
} elseif (in_array($format, self::NUMERIC_FORMAT, true)) {
$this->axisNumber['numeric'] = true;
}
}
/**
* Get Axis Number Format Data Type.
*/
public function getAxisNumberFormat(): string
{
return $this->axisNumber['format'];
}
/**
* Get Axis Number Source Linked.
*/
public function getAxisNumberSourceLinked(): string
{
return (string) $this->axisNumber['source_linked'];
}
public function getAxisIsNumericFormat(): bool
{
return $this->axisType === self::AXIS_TYPE_DATE || (bool) $this->axisNumber['numeric'];
}
public function setAxisOption(string $key, null|float|int|string $value): void
{
if ($value !== null && $value !== '') {
$this->axisOptions[$key] = (string) $value;
}
}
/**
* Set Axis Options Properties.
*/
public function setAxisOptionsProperties(
string $axisLabels,
?string $horizontalCrossesValue = null,
?string $horizontalCrosses = null,
?string $axisOrientation = null,
?string $majorTmt = null,
?string $minorTmt = null,
null|float|int|string $minimum = null,
null|float|int|string $maximum = null,
null|float|int|string $majorUnit = null,
null|float|int|string $minorUnit = null,
null|float|int|string $textRotation = null,
?string $hidden = null,
?string $baseTimeUnit = null,
?string $majorTimeUnit = null,
?string $minorTimeUnit = null,
null|float|int|string $logBase = null,
?string $dispUnitsBuiltIn = null
): void {
$this->axisOptions['axis_labels'] = $axisLabels;
$this->setAxisOption('horizontal_crosses_value', $horizontalCrossesValue);
$this->setAxisOption('horizontal_crosses', $horizontalCrosses);
$this->setAxisOption('orientation', $axisOrientation);
$this->setAxisOption('major_tick_mark', $majorTmt);
$this->setAxisOption('minor_tick_mark', $minorTmt);
$this->setAxisOption('minimum', $minimum);
$this->setAxisOption('maximum', $maximum);
$this->setAxisOption('major_unit', $majorUnit);
$this->setAxisOption('minor_unit', $minorUnit);
$this->setAxisOption('textRotation', $textRotation);
$this->setAxisOption('hidden', $hidden);
$this->setAxisOption('baseTimeUnit', $baseTimeUnit);
$this->setAxisOption('majorTimeUnit', $majorTimeUnit);
$this->setAxisOption('minorTimeUnit', $minorTimeUnit);
$this->setAxisOption('logBase', $logBase);
$this->setAxisOption('dispUnitsBuiltIn', $dispUnitsBuiltIn);
}
/**
* Get Axis Options Property.
*/
public function getAxisOptionsProperty(string $property): ?string
{
if ($property === 'textRotation') {
if ($this->axisText !== null) {
if ($this->axisText->getRotation() !== null) {
return (string) $this->axisText->getRotation();
}
}
}
return $this->axisOptions[$property];
}
/**
* Set Axis Orientation Property.
*/
public function setAxisOrientation(string $orientation): void
{
$this->axisOptions['orientation'] = (string) $orientation;
}
public function getAxisType(): string
{
return $this->axisType;
}
public function setAxisType(string $type): self
{
if ($type === self::AXIS_TYPE_CATEGORY || $type === self::AXIS_TYPE_VALUE || $type === self::AXIS_TYPE_DATE) {
$this->axisType = $type;
} else {
$this->axisType = '';
}
return $this;
}
/**
* Set Fill Property.
*/
public function setFillParameters(?string $color, ?int $alpha = null, ?string $AlphaType = ChartColor::EXCEL_COLOR_TYPE_RGB): void
{
$this->fillColor->setColorProperties($color, $alpha, $AlphaType);
}
/**
* Get Fill Property.
*/
public function getFillProperty(string $property): string
{
return (string) $this->fillColor->getColorProperty($property);
}
public function getFillColorObject(): ChartColor
{
return $this->fillColor;
}
private string $crossBetween = ''; // 'between' or 'midCat' might be better
public function setCrossBetween(string $crossBetween): self
{
$this->crossBetween = $crossBetween;
return $this;
}
public function getCrossBetween(): string
{
return $this->crossBetween;
}
public function getMajorGridlines(): ?GridLines
{
return $this->majorGridlines;
}
public function getMinorGridlines(): ?GridLines
{
return $this->minorGridlines;
}
public function setMajorGridlines(?GridLines $gridlines): self
{
$this->majorGridlines = $gridlines;
return $this;
}
public function setMinorGridlines(?GridLines $gridlines): self
{
$this->minorGridlines = $gridlines;
return $this;
}
public function getAxisText(): ?AxisText
{
return $this->axisText;
}
public function setAxisText(?AxisText $axisText): self
{
$this->axisText = $axisText;
return $this;
}
public function setNoFill(bool $noFill): self
{
$this->noFill = $noFill;
return $this;
}
public function getNoFill(): bool
{
return $this->noFill;
}
public function setDispUnitsTitle(?Title $dispUnitsTitle): self
{
$this->dispUnitsTitle = $dispUnitsTitle;
return $this;
}
public function getDispUnitsTitle(): ?Title
{
return $this->dispUnitsTitle;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
parent::__clone();
$this->majorGridlines = ($this->majorGridlines === null) ? null : clone $this->majorGridlines;
$this->majorGridlines = ($this->minorGridlines === null) ? null : clone $this->minorGridlines;
$this->axisText = ($this->axisText === null) ? null : clone $this->axisText;
$this->dispUnitsTitle = ($this->dispUnitsTitle === null) ? null : clone $this->dispUnitsTitle;
$this->fillColor = clone $this->fillColor;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/DataSeries.php | src/PhpSpreadsheet/Chart/DataSeries.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class DataSeries
{
const TYPE_BARCHART = 'barChart';
const TYPE_BARCHART_3D = 'bar3DChart';
const TYPE_LINECHART = 'lineChart';
const TYPE_LINECHART_3D = 'line3DChart';
const TYPE_AREACHART = 'areaChart';
const TYPE_AREACHART_3D = 'area3DChart';
const TYPE_PIECHART = 'pieChart';
const TYPE_PIECHART_3D = 'pie3DChart';
const TYPE_DOUGHNUTCHART = 'doughnutChart';
const TYPE_DONUTCHART = self::TYPE_DOUGHNUTCHART; // Synonym
const TYPE_SCATTERCHART = 'scatterChart';
const TYPE_SURFACECHART = 'surfaceChart';
const TYPE_SURFACECHART_3D = 'surface3DChart';
const TYPE_RADARCHART = 'radarChart';
const TYPE_BUBBLECHART = 'bubbleChart';
const TYPE_STOCKCHART = 'stockChart';
const TYPE_CANDLECHART = self::TYPE_STOCKCHART; // Synonym
const GROUPING_CLUSTERED = 'clustered';
const GROUPING_STACKED = 'stacked';
const GROUPING_PERCENT_STACKED = 'percentStacked';
const GROUPING_STANDARD = 'standard';
const DIRECTION_BAR = 'bar';
const DIRECTION_HORIZONTAL = self::DIRECTION_BAR;
const DIRECTION_COL = 'col';
const DIRECTION_COLUMN = self::DIRECTION_COL;
const DIRECTION_VERTICAL = self::DIRECTION_COL;
const STYLE_LINEMARKER = 'lineMarker';
const STYLE_SMOOTHMARKER = 'smoothMarker';
const STYLE_MARKER = 'marker';
const STYLE_FILLED = 'filled';
const EMPTY_AS_GAP = 'gap';
const EMPTY_AS_ZERO = 'zero';
const EMPTY_AS_SPAN = 'span';
const DEFAULT_EMPTY_AS = self::EMPTY_AS_GAP;
const VALID_EMPTY_AS = [self::EMPTY_AS_GAP, self::EMPTY_AS_ZERO, self::EMPTY_AS_SPAN];
/**
* Series Plot Type.
*/
private ?string $plotType;
/**
* Plot Grouping Type.
*/
private ?string $plotGrouping;
/**
* Plot Direction.
*/
private string $plotDirection;
/**
* Plot Style.
*/
private ?string $plotStyle;
/**
* Order of plots in Series.
*
* @var int[]
*/
private array $plotOrder;
/**
* Plot Label.
*
* @var DataSeriesValues[]
*/
private array $plotLabel;
/**
* Plot Category.
*
* @var DataSeriesValues[]
*/
private array $plotCategory;
/**
* Smooth Line. Must be specified for both DataSeries and DataSeriesValues.
*/
private bool $smoothLine;
/**
* Plot Values.
*
* @var DataSeriesValues[]
*/
private array $plotValues;
/**
* Plot Bubble Sizes.
*
* @var DataSeriesValues[]
*/
private array $plotBubbleSizes = [];
/**
* Create a new DataSeries.
*
* @param int[] $plotOrder
* @param DataSeriesValues[] $plotLabel
* @param DataSeriesValues[] $plotCategory
* @param DataSeriesValues[] $plotValues
*/
public function __construct(
null|string $plotType = null,
null|string $plotGrouping = null,
array $plotOrder = [],
array $plotLabel = [],
array $plotCategory = [],
array $plotValues = [],
?string $plotDirection = null,
bool $smoothLine = false,
?string $plotStyle = null
) {
$this->plotType = $plotType;
$this->plotGrouping = $plotGrouping;
$this->plotOrder = $plotOrder;
$keys = array_keys($plotValues);
$this->plotValues = $plotValues;
if (!isset($plotLabel[$keys[0]])) {
$plotLabel[$keys[0]] = new DataSeriesValues();
}
$this->plotLabel = $plotLabel;
if (!isset($plotCategory[$keys[0]])) {
$plotCategory[$keys[0]] = new DataSeriesValues();
}
$this->plotCategory = $plotCategory;
$this->smoothLine = (bool) $smoothLine;
$this->plotStyle = $plotStyle;
if ($plotDirection === null) {
$plotDirection = self::DIRECTION_COL;
}
$this->plotDirection = $plotDirection;
}
/**
* Get Plot Type.
*/
public function getPlotType(): ?string
{
return $this->plotType;
}
/**
* Set Plot Type.
*
* @return $this
*/
public function setPlotType(string $plotType): static
{
$this->plotType = $plotType;
return $this;
}
/**
* Get Plot Grouping Type.
*/
public function getPlotGrouping(): ?string
{
return $this->plotGrouping;
}
/**
* Set Plot Grouping Type.
*
* @return $this
*/
public function setPlotGrouping(string $groupingType): static
{
$this->plotGrouping = $groupingType;
return $this;
}
/**
* Get Plot Direction.
*/
public function getPlotDirection(): string
{
return $this->plotDirection;
}
/**
* Set Plot Direction.
*
* @return $this
*/
public function setPlotDirection(string $plotDirection): static
{
$this->plotDirection = $plotDirection;
return $this;
}
/**
* Get Plot Order.
*
* @return int[]
*/
public function getPlotOrder(): array
{
return $this->plotOrder;
}
/**
* Get Plot Labels.
*
* @return DataSeriesValues[]
*/
public function getPlotLabels(): array
{
return $this->plotLabel;
}
/**
* Get Plot Label by Index.
*
* @return DataSeriesValues|false
*/
public function getPlotLabelByIndex(int $index): bool|DataSeriesValues
{
$keys = array_keys($this->plotLabel);
if (in_array($index, $keys)) {
return $this->plotLabel[$index];
}
return false;
}
/**
* Get Plot Categories.
*
* @return DataSeriesValues[]
*/
public function getPlotCategories(): array
{
return $this->plotCategory;
}
/**
* Get Plot Category by Index.
*
* @return DataSeriesValues|false
*/
public function getPlotCategoryByIndex(int $index): bool|DataSeriesValues
{
$keys = array_keys($this->plotCategory);
if (in_array($index, $keys)) {
return $this->plotCategory[$index];
} elseif (isset($keys[$index])) {
return $this->plotCategory[$keys[$index]];
}
return false;
}
/**
* Get Plot Style.
*/
public function getPlotStyle(): ?string
{
return $this->plotStyle;
}
/**
* Set Plot Style.
*
* @return $this
*/
public function setPlotStyle(?string $plotStyle): static
{
$this->plotStyle = $plotStyle;
return $this;
}
/**
* Get Plot Values.
*
* @return DataSeriesValues[]
*/
public function getPlotValues(): array
{
return $this->plotValues;
}
/**
* Get Plot Values by Index.
*
* @return DataSeriesValues|false
*/
public function getPlotValuesByIndex(int $index): bool|DataSeriesValues
{
$keys = array_keys($this->plotValues);
if (in_array($index, $keys)) {
return $this->plotValues[$index];
}
return false;
}
/**
* Get Plot Bubble Sizes.
*
* @return DataSeriesValues[]
*/
public function getPlotBubbleSizes(): array
{
return $this->plotBubbleSizes;
}
/**
* Set Plot Bubble Sizes.
*
* @param DataSeriesValues[] $plotBubbleSizes
*/
public function setPlotBubbleSizes(array $plotBubbleSizes): self
{
$this->plotBubbleSizes = $plotBubbleSizes;
return $this;
}
/**
* Get Number of Plot Series.
*/
public function getPlotSeriesCount(): int
{
return count($this->plotValues);
}
/**
* Get Smooth Line.
*/
public function getSmoothLine(): bool
{
return $this->smoothLine;
}
/**
* Set Smooth Line.
*
* @return $this
*/
public function setSmoothLine(bool $smoothLine): static
{
$this->smoothLine = $smoothLine;
return $this;
}
public function refresh(Worksheet $worksheet): void
{
foreach ($this->plotValues as $plotValues) {
$plotValues->refresh($worksheet, true);
}
foreach ($this->plotLabel as $plotValues) {
$plotValues->refresh($worksheet, true);
}
foreach ($this->plotCategory as $plotValues) {
$plotValues->refresh($worksheet, false);
}
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$plotLabels = $this->plotLabel;
$this->plotLabel = [];
foreach ($plotLabels as $plotLabel) {
$this->plotLabel[] = $plotLabel;
}
$plotCategories = $this->plotCategory;
$this->plotCategory = [];
foreach ($plotCategories as $plotCategory) {
$this->plotCategory[] = clone $plotCategory;
}
$plotValues = $this->plotValues;
$this->plotValues = [];
foreach ($plotValues as $plotValue) {
$this->plotValues[] = clone $plotValue;
}
$plotBubbleSizes = $this->plotBubbleSizes;
$this->plotBubbleSizes = [];
foreach ($plotBubbleSizes as $plotBubbleSize) {
$this->plotBubbleSizes[] = clone $plotBubbleSize;
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/Properties.php | src/PhpSpreadsheet/Chart/Properties.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
/**
* Created by PhpStorm.
* User: nhw2h8s
* Date: 7/2/14
* Time: 5:45 PM.
*/
abstract class Properties
{
const AXIS_LABELS_LOW = 'low';
const AXIS_LABELS_HIGH = 'high';
const AXIS_LABELS_NEXT_TO = 'nextTo';
const AXIS_LABELS_NONE = 'none';
const TICK_MARK_NONE = 'none';
const TICK_MARK_INSIDE = 'in';
const TICK_MARK_OUTSIDE = 'out';
const TICK_MARK_CROSS = 'cross';
const HORIZONTAL_CROSSES_AUTOZERO = 'autoZero';
const HORIZONTAL_CROSSES_MAXIMUM = 'max';
const FORMAT_CODE_GENERAL = 'General';
const FORMAT_CODE_NUMBER = '#,##0.00';
const FORMAT_CODE_CURRENCY = '$#,##0.00';
const FORMAT_CODE_ACCOUNTING = '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)';
const FORMAT_CODE_DATE = 'm/d/yyyy';
const FORMAT_CODE_DATE_ISO8601 = 'yyyy-mm-dd';
const FORMAT_CODE_TIME = '[$-F400]h:mm:ss AM/PM';
const FORMAT_CODE_PERCENTAGE = '0.00%';
const FORMAT_CODE_FRACTION = '# ?/?';
const FORMAT_CODE_SCIENTIFIC = '0.00E+00';
const FORMAT_CODE_TEXT = '@';
const FORMAT_CODE_SPECIAL = '00000';
const ORIENTATION_NORMAL = 'minMax';
const ORIENTATION_REVERSED = 'maxMin';
const LINE_STYLE_COMPOUND_SIMPLE = 'sng';
const LINE_STYLE_COMPOUND_DOUBLE = 'dbl';
const LINE_STYLE_COMPOUND_THICKTHIN = 'thickThin';
const LINE_STYLE_COMPOUND_THINTHICK = 'thinThick';
const LINE_STYLE_COMPOUND_TRIPLE = 'tri';
const LINE_STYLE_DASH_SOLID = 'solid';
const LINE_STYLE_DASH_ROUND_DOT = 'sysDot';
const LINE_STYLE_DASH_SQUARE_DOT = 'sysDash';
const LINE_STYPE_DASH_DASH = 'dash';
const LINE_STYLE_DASH_DASH_DOT = 'dashDot';
const LINE_STYLE_DASH_LONG_DASH = 'lgDash';
const LINE_STYLE_DASH_LONG_DASH_DOT = 'lgDashDot';
const LINE_STYLE_DASH_LONG_DASH_DOT_DOT = 'lgDashDotDot';
const LINE_STYLE_CAP_SQUARE = 'sq';
const LINE_STYLE_CAP_ROUND = 'rnd';
const LINE_STYLE_CAP_FLAT = 'flat';
const LINE_STYLE_JOIN_ROUND = 'round';
const LINE_STYLE_JOIN_MITER = 'miter';
const LINE_STYLE_JOIN_BEVEL = 'bevel';
const LINE_STYLE_ARROW_TYPE_NOARROW = null;
const LINE_STYLE_ARROW_TYPE_ARROW = 'triangle';
const LINE_STYLE_ARROW_TYPE_OPEN = 'arrow';
const LINE_STYLE_ARROW_TYPE_STEALTH = 'stealth';
const LINE_STYLE_ARROW_TYPE_DIAMOND = 'diamond';
const LINE_STYLE_ARROW_TYPE_OVAL = 'oval';
const LINE_STYLE_ARROW_SIZE_1 = 1;
const LINE_STYLE_ARROW_SIZE_2 = 2;
const LINE_STYLE_ARROW_SIZE_3 = 3;
const LINE_STYLE_ARROW_SIZE_4 = 4;
const LINE_STYLE_ARROW_SIZE_5 = 5;
const LINE_STYLE_ARROW_SIZE_6 = 6;
const LINE_STYLE_ARROW_SIZE_7 = 7;
const LINE_STYLE_ARROW_SIZE_8 = 8;
const LINE_STYLE_ARROW_SIZE_9 = 9;
const SHADOW_PRESETS_NOSHADOW = null;
const SHADOW_PRESETS_OUTER_BOTTTOM_RIGHT = 1;
const SHADOW_PRESETS_OUTER_BOTTOM = 2;
const SHADOW_PRESETS_OUTER_BOTTOM_LEFT = 3;
const SHADOW_PRESETS_OUTER_RIGHT = 4;
const SHADOW_PRESETS_OUTER_CENTER = 5;
const SHADOW_PRESETS_OUTER_LEFT = 6;
const SHADOW_PRESETS_OUTER_TOP_RIGHT = 7;
const SHADOW_PRESETS_OUTER_TOP = 8;
const SHADOW_PRESETS_OUTER_TOP_LEFT = 9;
const SHADOW_PRESETS_INNER_BOTTTOM_RIGHT = 10;
const SHADOW_PRESETS_INNER_BOTTOM = 11;
const SHADOW_PRESETS_INNER_BOTTOM_LEFT = 12;
const SHADOW_PRESETS_INNER_RIGHT = 13;
const SHADOW_PRESETS_INNER_CENTER = 14;
const SHADOW_PRESETS_INNER_LEFT = 15;
const SHADOW_PRESETS_INNER_TOP_RIGHT = 16;
const SHADOW_PRESETS_INNER_TOP = 17;
const SHADOW_PRESETS_INNER_TOP_LEFT = 18;
const SHADOW_PRESETS_PERSPECTIVE_BELOW = 19;
const SHADOW_PRESETS_PERSPECTIVE_UPPER_RIGHT = 20;
const SHADOW_PRESETS_PERSPECTIVE_UPPER_LEFT = 21;
const SHADOW_PRESETS_PERSPECTIVE_LOWER_RIGHT = 22;
const SHADOW_PRESETS_PERSPECTIVE_LOWER_LEFT = 23;
const POINTS_WIDTH_MULTIPLIER = 12700;
const ANGLE_MULTIPLIER = 60000; // direction and size-kx size-ky
const PERCENTAGE_MULTIPLIER = 100000; // size sx and sy
protected bool $objectState = false; // used only for minor gridlines
protected ?float $glowSize = null;
protected ChartColor $glowColor;
/** @var array{size: ?float} */
protected array $softEdges = [
'size' => null,
];
/** @var mixed[] */
protected array $shadowProperties = self::PRESETS_OPTIONS[0];
protected ChartColor $shadowColor;
public function __construct()
{
$this->lineColor = new ChartColor();
$this->glowColor = new ChartColor();
$this->shadowColor = new ChartColor();
$this->shadowColor->setType(ChartColor::EXCEL_COLOR_TYPE_STANDARD);
$this->shadowColor->setValue('black');
$this->shadowColor->setAlpha(40);
}
/**
* Get Object State.
*/
public function getObjectState(): bool
{
return $this->objectState;
}
/**
* Change Object State to True.
*
* @return $this
*/
public function activateObject()
{
$this->objectState = true;
return $this;
}
public static function pointsToXml(float $width): string
{
return (string) (int) ($width * self::POINTS_WIDTH_MULTIPLIER);
}
public static function xmlToPoints(string $width): float
{
return ((float) $width) / self::POINTS_WIDTH_MULTIPLIER;
}
public static function angleToXml(float $angle): string
{
return (string) (int) ($angle * self::ANGLE_MULTIPLIER);
}
public static function xmlToAngle(string $angle): float
{
return ((float) $angle) / self::ANGLE_MULTIPLIER;
}
public static function tenthOfPercentToXml(float $value): string
{
return (string) (int) ($value * self::PERCENTAGE_MULTIPLIER);
}
public static function xmlToTenthOfPercent(string $value): float
{
return ((float) $value) / self::PERCENTAGE_MULTIPLIER;
}
/** @return array{type: ?string, value: ?string, alpha: ?int} */
protected function setColorProperties(?string $color, null|float|int|string $alpha, ?string $colorType): array
{
return [
'type' => $colorType,
'value' => $color,
'alpha' => ($alpha === null) ? null : (int) $alpha,
];
}
protected const PRESETS_OPTIONS = [
//NONE
0 => [
'presets' => self::SHADOW_PRESETS_NOSHADOW,
'effect' => null,
//'color' => [
// 'type' => ChartColor::EXCEL_COLOR_TYPE_STANDARD,
// 'value' => 'black',
// 'alpha' => 40,
//],
'size' => [
'sx' => null,
'sy' => null,
'kx' => null,
'ky' => null,
],
'blur' => null,
'direction' => null,
'distance' => null,
'algn' => null,
'rotWithShape' => null,
],
//OUTER
1 => [
'effect' => 'outerShdw',
'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 2700000 / self::ANGLE_MULTIPLIER,
'algn' => 'tl',
'rotWithShape' => '0',
],
2 => [
'effect' => 'outerShdw',
'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 5400000 / self::ANGLE_MULTIPLIER,
'algn' => 't',
'rotWithShape' => '0',
],
3 => [
'effect' => 'outerShdw',
'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 8100000 / self::ANGLE_MULTIPLIER,
'algn' => 'tr',
'rotWithShape' => '0',
],
4 => [
'effect' => 'outerShdw',
'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER,
'algn' => 'l',
'rotWithShape' => '0',
],
5 => [
'effect' => 'outerShdw',
'size' => [
'sx' => 102000 / self::PERCENTAGE_MULTIPLIER,
'sy' => 102000 / self::PERCENTAGE_MULTIPLIER,
],
'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER,
'algn' => 'ctr',
'rotWithShape' => '0',
],
6 => [
'effect' => 'outerShdw',
'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 10800000 / self::ANGLE_MULTIPLIER,
'algn' => 'r',
'rotWithShape' => '0',
],
7 => [
'effect' => 'outerShdw',
'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 18900000 / self::ANGLE_MULTIPLIER,
'algn' => 'bl',
'rotWithShape' => '0',
],
8 => [
'effect' => 'outerShdw',
'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 16200000 / self::ANGLE_MULTIPLIER,
'rotWithShape' => '0',
],
9 => [
'effect' => 'outerShdw',
'blur' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 38100 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 13500000 / self::ANGLE_MULTIPLIER,
'algn' => 'br',
'rotWithShape' => '0',
],
//INNER
10 => [
'effect' => 'innerShdw',
'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 2700000 / self::ANGLE_MULTIPLIER,
],
11 => [
'effect' => 'innerShdw',
'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 5400000 / self::ANGLE_MULTIPLIER,
],
12 => [
'effect' => 'innerShdw',
'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 8100000 / self::ANGLE_MULTIPLIER,
],
13 => [
'effect' => 'innerShdw',
'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
],
14 => [
'effect' => 'innerShdw',
'blur' => 114300 / self::POINTS_WIDTH_MULTIPLIER,
],
15 => [
'effect' => 'innerShdw',
'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 10800000 / self::ANGLE_MULTIPLIER,
],
16 => [
'effect' => 'innerShdw',
'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 18900000 / self::ANGLE_MULTIPLIER,
],
17 => [
'effect' => 'innerShdw',
'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 16200000 / self::ANGLE_MULTIPLIER,
],
18 => [
'effect' => 'innerShdw',
'blur' => 63500 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 50800 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 13500000 / self::ANGLE_MULTIPLIER,
],
//perspective
19 => [
'effect' => 'outerShdw',
'blur' => 152400 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 317500 / self::POINTS_WIDTH_MULTIPLIER,
'size' => [
'sx' => 90000 / self::PERCENTAGE_MULTIPLIER,
'sy' => -19000 / self::PERCENTAGE_MULTIPLIER,
],
'direction' => 5400000 / self::ANGLE_MULTIPLIER,
'rotWithShape' => '0',
],
20 => [
'effect' => 'outerShdw',
'blur' => 76200 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 18900000 / self::ANGLE_MULTIPLIER,
'size' => [
'sy' => 23000 / self::PERCENTAGE_MULTIPLIER,
'kx' => -1200000 / self::ANGLE_MULTIPLIER,
],
'algn' => 'bl',
'rotWithShape' => '0',
],
21 => [
'effect' => 'outerShdw',
'blur' => 76200 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 13500000 / self::ANGLE_MULTIPLIER,
'size' => [
'sy' => 23000 / self::PERCENTAGE_MULTIPLIER,
'kx' => 1200000 / self::ANGLE_MULTIPLIER,
],
'algn' => 'br',
'rotWithShape' => '0',
],
22 => [
'effect' => 'outerShdw',
'blur' => 76200 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 12700 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 2700000 / self::ANGLE_MULTIPLIER,
'size' => [
'sy' => -23000 / self::PERCENTAGE_MULTIPLIER,
'kx' => -800400 / self::ANGLE_MULTIPLIER,
],
'algn' => 'bl',
'rotWithShape' => '0',
],
23 => [
'effect' => 'outerShdw',
'blur' => 76200 / self::POINTS_WIDTH_MULTIPLIER,
'distance' => 12700 / self::POINTS_WIDTH_MULTIPLIER,
'direction' => 8100000 / self::ANGLE_MULTIPLIER,
'size' => [
'sy' => -23000 / self::PERCENTAGE_MULTIPLIER,
'kx' => 800400 / self::ANGLE_MULTIPLIER,
],
'algn' => 'br',
'rotWithShape' => '0',
],
];
/** @return mixed[] */
protected function getShadowPresetsMap(int $presetsOption): array
{
return self::PRESETS_OPTIONS[$presetsOption] ?? self::PRESETS_OPTIONS[0];
}
/**
* Get value of array element.
*
* @param mixed[] $properties
* @param array<mixed>|int|string $elements
*/
protected function getArrayElementsValue(array $properties, array|int|string $elements): mixed
{
$reference = &$properties;
if (!is_array($elements)) {
return $reference[$elements];
}
foreach ($elements as $keys) {
$reference = &$reference[$keys]; //* @phpstan-ignore-line
}
return $reference;
}
/**
* Set Glow Properties.
*/
public function setGlowProperties(float $size, ?string $colorValue = null, ?int $colorAlpha = null, ?string $colorType = null): void
{
$this
->activateObject()
->setGlowSize($size);
$this->glowColor->setColorPropertiesArray(
[
'value' => $colorValue,
'type' => $colorType,
'alpha' => $colorAlpha,
]
);
}
/**
* Get Glow Property.
*
* @param mixed[]|string $property
*
* @return null|array<mixed>|float|int|string
*/
public function getGlowProperty(array|string $property): null|array|float|int|string
{
$retVal = null;
if ($property === 'size') {
$retVal = $this->glowSize;
} elseif ($property === 'color') {
$retVal = [
'value' => $this->glowColor->getColorProperty('value'),
'type' => $this->glowColor->getColorProperty('type'),
'alpha' => $this->glowColor->getColorProperty('alpha'),
];
} elseif (is_array($property) && count($property) >= 2 && $property[0] === 'color') {
/** @var string */
$temp = $property[1];
$retVal = $this->glowColor->getColorProperty($temp);
}
return $retVal;
}
/**
* Get Glow Color Property.
*/
public function getGlowColor(string $propertyName): null|int|string
{
return $this->glowColor->getColorProperty($propertyName);
}
public function getGlowColorObject(): ChartColor
{
return $this->glowColor;
}
/**
* Get Glow Size.
*/
public function getGlowSize(): ?float
{
return $this->glowSize;
}
/**
* Set Glow Size.
*
* @return $this
*/
protected function setGlowSize(?float $size)
{
$this->glowSize = $size;
return $this;
}
/**
* Set Soft Edges Size.
*/
public function setSoftEdges(?float $size): void
{
if ($size !== null) {
$this->activateObject();
$this->softEdges['size'] = $size;
}
}
/**
* Get Soft Edges Size.
*/
public function getSoftEdgesSize(): ?float
{
return $this->softEdges['size'];
}
/** @param null|array{value?: ?string, alpha?: null|int|string, brightness?: null|int|string, type?: ?string}|float|string $value */
public function setShadowProperty(string $propertyName, mixed $value): self
{
$this->activateObject();
if ($propertyName === 'color' && is_array($value)) {
/** @var array{value: ?string, alpha: null|int|string, brightness?: null|int|string, type: ?string} */
$valuex = $value;
$this->shadowColor->setColorPropertiesArray($valuex);
} else {
$this->shadowProperties[$propertyName] = $value;
}
return $this;
}
/**
* Set Shadow Properties.
*/
public function setShadowProperties(int $presets, ?string $colorValue = null, ?string $colorType = null, null|float|int|string $colorAlpha = null, ?float $blur = null, ?int $angle = null, ?float $distance = null): void
{
$this->activateObject()->setShadowPresetsProperties((int) $presets);
if ($presets === 0) {
$this->shadowColor->setType(ChartColor::EXCEL_COLOR_TYPE_STANDARD);
$this->shadowColor->setValue('black');
$this->shadowColor->setAlpha(40);
}
if ($colorValue !== null) {
$this->shadowColor->setValue($colorValue);
}
if ($colorType !== null) {
$this->shadowColor->setType($colorType);
}
if (is_numeric($colorAlpha)) {
$this->shadowColor->setAlpha((int) $colorAlpha);
}
$this
->setShadowBlur($blur)
->setShadowAngle($angle)
->setShadowDistance($distance);
}
/**
* Set Shadow Presets Properties.
*
* @return $this
*/
protected function setShadowPresetsProperties(int $presets)
{
$this->shadowProperties['presets'] = $presets;
$this->setShadowPropertiesMapValues($this->getShadowPresetsMap($presets));
return $this;
}
protected const SHADOW_ARRAY_KEYS = ['size', 'color'];
/**
* Set Shadow Properties Values.
*
* @param mixed[] $propertiesMap
* @param null|mixed[] $reference
*
* @return $this
*/
protected function setShadowPropertiesMapValues(array $propertiesMap, ?array &$reference = null)
{
$base_reference = $reference;
foreach ($propertiesMap as $property_key => $property_val) {
if (is_array($property_val)) {
if (in_array($property_key, self::SHADOW_ARRAY_KEYS, true)) {
/** @var null|array<mixed> */
$temp = &$this->shadowProperties[$property_key];
$reference = &$temp;
$this->setShadowPropertiesMapValues(
$property_val,
$reference
);
}
} else {
if ($base_reference === null) {
$this->shadowProperties[$property_key] = $property_val;
} else {
$reference[$property_key] = $property_val;
}
}
}
return $this;
}
/**
* Set Shadow Blur.
*
* @return $this
*/
protected function setShadowBlur(?float $blur)
{
if ($blur !== null) {
$this->shadowProperties['blur'] = $blur;
}
return $this;
}
/**
* Set Shadow Angle.
*
* @return $this
*/
protected function setShadowAngle(null|float|int|string $angle)
{
if (is_numeric($angle)) {
$this->shadowProperties['direction'] = $angle;
}
return $this;
}
/**
* Set Shadow Distance.
*
* @return $this
*/
protected function setShadowDistance(?float $distance)
{
if ($distance !== null) {
$this->shadowProperties['distance'] = $distance;
}
return $this;
}
public function getShadowColorObject(): ChartColor
{
return $this->shadowColor;
}
/**
* Get Shadow Property.
*
* @param string|string[] $elements
*
* @return null|mixed[]|string
*/
public function getShadowProperty($elements): array|string|null
{
if ($elements === 'color') {
return [
'value' => $this->shadowColor->getValue(),
'type' => $this->shadowColor->getType(),
'alpha' => $this->shadowColor->getAlpha(),
];
}
$retVal = $this->getArrayElementsValue($this->shadowProperties, $elements);
if (is_scalar($retVal)) {
$retVal = (string) $retVal;
} elseif ($retVal !== null && !is_array($retVal)) {
// @codeCoverageIgnoreStart
throw new Exception('Unexpected value for shadowProperty');
// @codeCoverageIgnoreEnd
}
return $retVal;
}
/** @return mixed[] */
public function getShadowArray(): array
{
$array = $this->shadowProperties;
if ($this->getShadowColorObject()->isUsable()) {
$array['color'] = $this->getShadowProperty('color');
}
return $array;
}
protected ChartColor $lineColor;
/** @var array{width: null|float|int|string, compound: ?string, dash: ?string, cap: ?string, join: ?string, arrow: array{head: array{type: ?string, size: null|int|string, w: ?string, len: ?string}, end: array{type: ?string, size: null|int|string, w: ?string, len: ?string}}} */
protected array $lineStyleProperties = [
'width' => null, //'9525',
'compound' => '', //self::LINE_STYLE_COMPOUND_SIMPLE,
'dash' => '', //self::LINE_STYLE_DASH_SOLID,
'cap' => '', //self::LINE_STYLE_CAP_FLAT,
'join' => '', //self::LINE_STYLE_JOIN_BEVEL,
'arrow' => [
'head' => [
'type' => '', //self::LINE_STYLE_ARROW_TYPE_NOARROW,
'size' => '', //self::LINE_STYLE_ARROW_SIZE_5,
'w' => '',
'len' => '',
],
'end' => [
'type' => '', //self::LINE_STYLE_ARROW_TYPE_NOARROW,
'size' => '', //self::LINE_STYLE_ARROW_SIZE_8,
'w' => '',
'len' => '',
],
],
];
public function copyLineStyles(self $otherProperties): void
{
$this->lineStyleProperties = $otherProperties->lineStyleProperties;
$this->lineColor = $otherProperties->lineColor;
$this->glowSize = $otherProperties->glowSize;
$this->glowColor = $otherProperties->glowColor;
$this->softEdges = $otherProperties->softEdges;
$this->shadowProperties = $otherProperties->shadowProperties;
}
public function getLineColor(): ChartColor
{
return $this->lineColor;
}
/**
* Set Line Color Properties.
*/
public function setLineColorProperties(?string $value, ?int $alpha = null, ?string $colorType = null): void
{
$this->activateObject();
$this->lineColor->setColorPropertiesArray(
$this->setColorProperties(
$value,
$alpha,
$colorType
)
);
}
/**
* Get Line Color Property.
*/
public function getLineColorProperty(string $propertyName): null|int|string
{
return $this->lineColor->getColorProperty($propertyName);
}
/**
* Set Line Style Properties.
*/
public function setLineStyleProperties(
null|float|int|string $lineWidth = null,
?string $compoundType = '',
?string $dashType = '',
?string $capType = '',
?string $joinType = '',
?string $headArrowType = '',
int $headArrowSize = 0,
?string $endArrowType = '',
int $endArrowSize = 0,
?string $headArrowWidth = '',
?string $headArrowLength = '',
?string $endArrowWidth = '',
?string $endArrowLength = ''
): void {
$this->activateObject();
if (is_numeric($lineWidth)) {
$this->lineStyleProperties['width'] = $lineWidth;
}
if ($compoundType !== '') {
$this->lineStyleProperties['compound'] = $compoundType;
}
if ($dashType !== '') {
$this->lineStyleProperties['dash'] = $dashType;
}
if ($capType !== '') {
$this->lineStyleProperties['cap'] = $capType;
}
if ($joinType !== '') {
$this->lineStyleProperties['join'] = $joinType;
}
if ($headArrowType !== '') {
$this->lineStyleProperties['arrow']['head']['type'] = $headArrowType;
}
if (isset(self::ARROW_SIZES[$headArrowSize])) {
$this->lineStyleProperties['arrow']['head']['size'] = $headArrowSize;
$this->lineStyleProperties['arrow']['head']['w'] = self::ARROW_SIZES[$headArrowSize]['w'];
$this->lineStyleProperties['arrow']['head']['len'] = self::ARROW_SIZES[$headArrowSize]['len'];
}
if ($endArrowType !== '') {
$this->lineStyleProperties['arrow']['end']['type'] = $endArrowType;
}
if (isset(self::ARROW_SIZES[$endArrowSize])) {
$this->lineStyleProperties['arrow']['end']['size'] = $endArrowSize;
$this->lineStyleProperties['arrow']['end']['w'] = self::ARROW_SIZES[$endArrowSize]['w'];
$this->lineStyleProperties['arrow']['end']['len'] = self::ARROW_SIZES[$endArrowSize]['len'];
}
if ($headArrowWidth !== '') {
$this->lineStyleProperties['arrow']['head']['w'] = $headArrowWidth;
}
if ($headArrowLength !== '') {
$this->lineStyleProperties['arrow']['head']['len'] = $headArrowLength;
}
if ($endArrowWidth !== '') {
$this->lineStyleProperties['arrow']['end']['w'] = $endArrowWidth;
}
if ($endArrowLength !== '') {
$this->lineStyleProperties['arrow']['end']['len'] = $endArrowLength;
}
}
/** @return mixed[] */
public function getLineStyleArray(): array
{
return $this->lineStyleProperties;
}
/** @param mixed[] $lineStyleProperties */
public function setLineStyleArray(array $lineStyleProperties = []): self
{
/** @var array{width?: ?string, compound?: string, dash?: string, cap?: string, join?: string, arrow?: array{head?: array{type?: string, size?: int, w?: string, len?: string}, end?: array{type?: string, size?: int, w?: string, len?: string}}} $lineStyleProperties */
$this->activateObject();
$this->lineStyleProperties['width'] = $lineStyleProperties['width'] ?? null;
$this->lineStyleProperties['compound'] = $lineStyleProperties['compound'] ?? '';
$this->lineStyleProperties['dash'] = $lineStyleProperties['dash'] ?? '';
$this->lineStyleProperties['cap'] = $lineStyleProperties['cap'] ?? '';
$this->lineStyleProperties['join'] = $lineStyleProperties['join'] ?? '';
$this->lineStyleProperties['arrow']['head']['type'] = $lineStyleProperties['arrow']['head']['type'] ?? '';
$this->lineStyleProperties['arrow']['head']['size'] = $lineStyleProperties['arrow']['head']['size'] ?? '';
$this->lineStyleProperties['arrow']['head']['w'] = $lineStyleProperties['arrow']['head']['w'] ?? '';
$this->lineStyleProperties['arrow']['head']['len'] = $lineStyleProperties['arrow']['head']['len'] ?? '';
$this->lineStyleProperties['arrow']['end']['type'] = $lineStyleProperties['arrow']['end']['type'] ?? '';
$this->lineStyleProperties['arrow']['end']['size'] = $lineStyleProperties['arrow']['end']['size'] ?? '';
$this->lineStyleProperties['arrow']['end']['w'] = $lineStyleProperties['arrow']['end']['w'] ?? '';
$this->lineStyleProperties['arrow']['end']['len'] = $lineStyleProperties['arrow']['end']['len'] ?? '';
return $this;
}
public function setLineStyleProperty(string $propertyName, mixed $value): self
{
$this->activateObject();
$this->lineStyleProperties[$propertyName] = $value; //* @phpstan-ignore-line
return $this;
}
/**
* Get Line Style Property.
*
* @param array<mixed>|string $elements
*/
public function getLineStyleProperty(array|string $elements): ?string
{
$retVal = $this->getArrayElementsValue($this->lineStyleProperties, $elements);
if (is_scalar($retVal)) {
$retVal = (string) $retVal;
} elseif ($retVal !== null) {
// @codeCoverageIgnoreStart
throw new Exception('Unexpected value for lineStyleProperty');
// @codeCoverageIgnoreEnd
}
return $retVal;
}
protected const ARROW_SIZES = [
1 => ['w' => 'sm', 'len' => 'sm'],
2 => ['w' => 'sm', 'len' => 'med'],
3 => ['w' => 'sm', 'len' => 'lg'],
4 => ['w' => 'med', 'len' => 'sm'],
5 => ['w' => 'med', 'len' => 'med'],
6 => ['w' => 'med', 'len' => 'lg'],
7 => ['w' => 'lg', 'len' => 'sm'],
8 => ['w' => 'lg', 'len' => 'med'],
9 => ['w' => 'lg', 'len' => 'lg'],
];
/**
* Get Line Style Arrow Size.
*/
protected function getLineStyleArrowSize(int $arraySelector, string $arrayKaySelector): string
{
return self::ARROW_SIZES[$arraySelector][$arrayKaySelector] ?? '';
}
/**
* Get Line Style Arrow Parameters.
*/
public function getLineStyleArrowParameters(string $arrowSelector, string $propertySelector): string
{
return $this->getLineStyleArrowSize((int) $this->lineStyleProperties['arrow'][$arrowSelector]['size'], $propertySelector);
}
/**
* Get Line Style Arrow Width.
*/
public function getLineStyleArrowWidth(string $arrow): ?string
{
return $this->getLineStyleProperty(['arrow', $arrow, 'w']);
}
/**
* Get Line Style Arrow Excel Length.
*/
public function getLineStyleArrowLength(string $arrow): ?string
{
return $this->getLineStyleProperty(['arrow', $arrow, 'len']);
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$this->lineColor = clone $this->lineColor;
$this->glowColor = clone $this->glowColor;
$this->shadowColor = clone $this->shadowColor;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/ChartColor.php | src/PhpSpreadsheet/Chart/ChartColor.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
class ChartColor
{
const EXCEL_COLOR_TYPE_STANDARD = 'prstClr';
const EXCEL_COLOR_TYPE_SCHEME = 'schemeClr';
const EXCEL_COLOR_TYPE_RGB = 'srgbClr';
const EXCEL_COLOR_TYPES = [
self::EXCEL_COLOR_TYPE_RGB,
self::EXCEL_COLOR_TYPE_SCHEME,
self::EXCEL_COLOR_TYPE_STANDARD,
];
private string $value = '';
private string $type = '';
private ?int $alpha = null;
private ?int $brightness = null;
/**
* @param array{value: ?string, alpha: null|int|string, brightness?: null|int|string, type: ?string}|string $value
*/
public function __construct($value = '', ?int $alpha = null, ?string $type = null, ?int $brightness = null)
{
if (is_array($value)) {
$this->setColorPropertiesArray($value);
} else {
$this->setColorProperties($value, $alpha, $type, $brightness);
}
}
public function getValue(): string
{
return $this->value;
}
public function setValue(string $value): self
{
$this->value = $value;
return $this;
}
public function getType(): string
{
return $this->type;
}
public function setType(string $type): self
{
$this->type = $type;
return $this;
}
public function getAlpha(): ?int
{
return $this->alpha;
}
public function setAlpha(?int $alpha): self
{
$this->alpha = $alpha;
return $this;
}
public function getBrightness(): ?int
{
return $this->brightness;
}
public function setBrightness(?int $brightness): self
{
$this->brightness = $brightness;
return $this;
}
public function setColorProperties(?string $color, null|float|int|string $alpha = null, ?string $type = null, null|float|int|string $brightness = null): self
{
if (empty($type) && !empty($color)) {
if (str_starts_with($color, '*')) {
$type = 'schemeClr';
$color = substr($color, 1);
} elseif (str_starts_with($color, '/')) {
$type = 'prstClr';
$color = substr($color, 1);
} elseif (preg_match('/^[0-9A-Fa-f]{6}$/', $color) === 1) {
$type = 'srgbClr';
}
}
if ($color !== null) {
$this->setValue("$color");
}
if ($type !== null) {
$this->setType($type);
}
if ($alpha === null) {
$this->setAlpha(null);
} elseif (is_numeric($alpha)) {
$this->setAlpha((int) $alpha);
}
if ($brightness === null) {
$this->setBrightness(null);
} elseif (is_numeric($brightness)) {
$this->setBrightness((int) $brightness);
}
return $this;
}
/** @param array{value: ?string, alpha: null|int|string, brightness?: null|int|string, type: ?string} $color */
public function setColorPropertiesArray(array $color): self
{
return $this->setColorProperties(
$color['value'] ?? '',
$color['alpha'] ?? null,
$color['type'] ?? null,
$color['brightness'] ?? null
);
}
public function isUsable(): bool
{
return $this->type !== '' && $this->value !== '';
}
/**
* Get Color Property.
*/
public function getColorProperty(string $propertyName): null|int|string
{
$retVal = null;
if ($propertyName === 'value') {
$retVal = $this->value;
} elseif ($propertyName === 'type') {
$retVal = $this->type;
} elseif ($propertyName === 'alpha') {
$retVal = $this->alpha;
} elseif ($propertyName === 'brightness') {
$retVal = $this->brightness;
}
return $retVal;
}
public static function alphaToXml(int $alpha): string
{
return (string) (100 - $alpha) . '000';
}
public static function alphaFromXml(float|int|string $alpha): int
{
return 100 - ((int) $alpha / 1000);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/DataSeriesValues.php | src/PhpSpreadsheet/Chart/DataSeriesValues.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class DataSeriesValues extends Properties
{
const DATASERIES_TYPE_STRING = 'String';
const DATASERIES_TYPE_NUMBER = 'Number';
private const DATA_TYPE_VALUES = [
self::DATASERIES_TYPE_STRING,
self::DATASERIES_TYPE_NUMBER,
];
/**
* Series Data Type.
*/
private string $dataType;
/**
* Series Data Source.
*/
private ?string $dataSource;
/**
* Format Code.
*/
private ?string $formatCode;
/**
* Series Point Marker.
*/
private ?string $pointMarker;
private ChartColor $markerFillColor;
private ChartColor $markerBorderColor;
/**
* Series Point Size.
*/
private int $pointSize = 3;
/**
* Point Count (The number of datapoints in the dataseries).
*/
private int $pointCount;
/**
* Data Values.
*
* @var null|mixed[]
*/
private ?array $dataValues;
/**
* Fill color (can be array with colors if dataseries have custom colors).
*
* @var null|ChartColor|ChartColor[]
*/
private $fillColor;
private bool $scatterLines = true;
private bool $bubble3D = false;
private ?Layout $labelLayout = null;
/** @var TrendLine[] */
private array $trendLines = [];
/**
* Create a new DataSeriesValues object.
*
* @param null|mixed[] $dataValues
* @param null|ChartColor|ChartColor[]|string|string[] $fillColor
*/
public function __construct(
string $dataType = self::DATASERIES_TYPE_NUMBER,
?string $dataSource = null,
?string $formatCode = null,
int $pointCount = 0,
?array $dataValues = [],
?string $marker = null,
null|ChartColor|array|string $fillColor = null,
int|string $pointSize = 3
) {
parent::__construct();
$this->markerFillColor = new ChartColor();
$this->markerBorderColor = new ChartColor();
$this->setDataType($dataType);
$this->dataSource = $dataSource;
$this->formatCode = $formatCode;
$this->pointCount = $pointCount;
$this->dataValues = $dataValues;
$this->pointMarker = $marker;
if ($fillColor !== null) {
$this->setFillColor($fillColor);
}
if (is_numeric($pointSize)) {
$this->pointSize = (int) $pointSize;
}
}
/**
* Get Series Data Type.
*/
public function getDataType(): string
{
return $this->dataType;
}
/**
* Set Series Data Type.
*
* @param string $dataType Datatype of this data series
* Typical values are:
* DataSeriesValues::DATASERIES_TYPE_STRING
* Normally used for axis point values
* DataSeriesValues::DATASERIES_TYPE_NUMBER
* Normally used for chart data values
*
* @return $this
*/
public function setDataType(string $dataType): static
{
if (!in_array($dataType, self::DATA_TYPE_VALUES)) {
throw new Exception('Invalid datatype for chart data series values');
}
$this->dataType = $dataType;
return $this;
}
/**
* Get Series Data Source (formula).
*/
public function getDataSource(): ?string
{
return $this->dataSource;
}
/**
* Set Series Data Source (formula).
*
* @return $this
*/
public function setDataSource(?string $dataSource): static
{
$this->dataSource = $dataSource;
return $this;
}
/**
* Get Point Marker.
*/
public function getPointMarker(): ?string
{
return $this->pointMarker;
}
/**
* Set Point Marker.
*
* @return $this
*/
public function setPointMarker(string $marker): static
{
$this->pointMarker = $marker;
return $this;
}
public function getMarkerFillColor(): ChartColor
{
return $this->markerFillColor;
}
public function getMarkerBorderColor(): ChartColor
{
return $this->markerBorderColor;
}
/**
* Get Point Size.
*/
public function getPointSize(): int
{
return $this->pointSize;
}
/**
* Set Point Size.
*
* @return $this
*/
public function setPointSize(int $size = 3): static
{
$this->pointSize = $size;
return $this;
}
/**
* Get Series Format Code.
*/
public function getFormatCode(): ?string
{
return $this->formatCode;
}
/**
* Set Series Format Code.
*
* @return $this
*/
public function setFormatCode(string $formatCode): static
{
$this->formatCode = $formatCode;
return $this;
}
/**
* Get Series Point Count.
*/
public function getPointCount(): int
{
return $this->pointCount;
}
/**
* Get fill color object.
*
* @return null|ChartColor|ChartColor[]
*/
public function getFillColorObject()
{
return $this->fillColor;
}
private function stringToChartColor(string $fillString): ChartColor
{
$value = $type = '';
if (str_starts_with($fillString, '*')) {
$type = 'schemeClr';
$value = substr($fillString, 1);
} elseif (str_starts_with($fillString, '/')) {
$type = 'prstClr';
$value = substr($fillString, 1);
} elseif ($fillString !== '') {
$type = 'srgbClr';
$value = $fillString;
$this->validateColor($value);
}
return new ChartColor($value, null, $type);
}
private function chartColorToString(ChartColor $chartColor): string
{
$type = (string) $chartColor->getColorProperty('type');
$value = (string) $chartColor->getColorProperty('value');
if ($type === '' || $value === '') {
return '';
}
if ($type === 'schemeClr') {
return "*$value";
}
if ($type === 'prstClr') {
return "/$value";
}
return $value;
}
/**
* Get fill color.
*
* @return string|string[] HEX color or array with HEX colors
*/
public function getFillColor(): string|array
{
if ($this->fillColor === null) {
return '';
}
if (is_array($this->fillColor)) {
$array = [];
foreach ($this->fillColor as $chartColor) {
$array[] = $this->chartColorToString($chartColor);
}
return $array;
}
return $this->chartColorToString($this->fillColor);
}
/**
* Set fill color for series.
*
* @param ChartColor|ChartColor[]|string|string[] $color HEX color or array with HEX colors
*
* @return $this
*/
public function setFillColor($color): static
{
if (is_array($color)) {
$this->fillColor = [];
foreach ($color as $fillString) {
if ($fillString instanceof ChartColor) {
$this->fillColor[] = $fillString;
} else {
$this->fillColor[] = $this->stringToChartColor($fillString);
}
}
} elseif ($color instanceof ChartColor) {
$this->fillColor = $color;
} else {
$this->fillColor = $this->stringToChartColor($color);
}
return $this;
}
/**
* Method for validating hex color.
*
* @param string $color value for color
*/
private function validateColor(string $color): void
{
if (!preg_match('/^[a-f0-9]{6}$/i', $color)) {
throw new Exception(sprintf('Invalid hex color for chart series (color: "%s")', $color));
}
}
/**
* Get line width for series.
*/
public function getLineWidth(): null|float|int
{
/** @var null|float|int */
$temp = $this->lineStyleProperties['width'];
return $temp;
}
/**
* Set line width for the series.
*
* @return $this
*/
public function setLineWidth(null|float|int $width): static
{
$this->lineStyleProperties['width'] = $width;
return $this;
}
/**
* Identify if the Data Series is a multi-level or a simple series.
*/
public function isMultiLevelSeries(): ?bool
{
if (!empty($this->dataValues)) {
return is_array(array_values($this->dataValues)[0]);
}
return null;
}
/**
* Return the level count of a multi-level Data Series.
*/
public function multiLevelCount(): int
{
$levelCount = 0;
foreach (($this->dataValues ?? []) as $dataValueSet) {
/** @var mixed[] $dataValueSet */
$levelCount = max($levelCount, count($dataValueSet));
}
return $levelCount;
}
/**
* Get Series Data Values.
*
* @return null|mixed[]
*/
public function getDataValues(): ?array
{
return $this->dataValues;
}
/**
* Get the first Series Data value.
*/
public function getDataValue(): mixed
{
if ($this->dataValues === null) {
return null;
}
$count = count($this->dataValues);
if ($count == 0) {
return null;
} elseif ($count == 1) {
return $this->dataValues[0];
}
return $this->dataValues;
}
/**
* Set Series Data Values.
*
* @param mixed[] $dataValues
*
* @return $this
*/
public function setDataValues(array $dataValues): static
{
$this->dataValues = Functions::flattenArray($dataValues);
$this->pointCount = count($dataValues);
return $this;
}
public function refresh(Worksheet $worksheet, bool $flatten = true): void
{
if ($this->dataSource !== null) {
$calcEngine = Calculation::getInstance($worksheet->getParent());
$newDataValues = Calculation::unwrapResult(
$calcEngine->_calculateFormulaValue(
'=' . $this->dataSource,
null,
$worksheet->getCell('A1')
)
);
if ($flatten) {
$this->dataValues = Functions::flattenArray($newDataValues);
foreach ($this->dataValues as &$dataValue) {
if (is_string($dataValue) && !empty($dataValue) && $dataValue[0] == '#') {
$dataValue = 0.0;
}
}
unset($dataValue);
} else {
[, $cellRange] = Worksheet::extractSheetTitle($this->dataSource, true);
$dimensions = Coordinate::rangeDimension(str_replace('$', '', $cellRange ?? ''));
if (($dimensions[0] == 1) || ($dimensions[1] == 1)) {
$this->dataValues = Functions::flattenArray($newDataValues);
} else {
/** @var array<int, mixed[]> */
$newDataValuesx = $newDataValues;
/** @var mixed[][] $newArray */
$newArray = array_values(array_shift($newDataValuesx) ?? []);
foreach ($newArray as $i => $newDataSet) {
$newArray[$i] = [$newDataSet];
}
foreach ($newDataValuesx as $newDataSet) {
$i = 0;
foreach ($newDataSet as $newDataVal) {
array_unshift($newArray[$i++], $newDataVal);
}
}
$this->dataValues = $newArray;
}
}
$this->pointCount = count($this->dataValues ?? []);
}
}
public function getScatterLines(): bool
{
return $this->scatterLines;
}
public function setScatterLines(bool $scatterLines): self
{
$this->scatterLines = $scatterLines;
return $this;
}
public function getBubble3D(): bool
{
return $this->bubble3D;
}
public function setBubble3D(bool $bubble3D): self
{
$this->bubble3D = $bubble3D;
return $this;
}
/**
* Smooth Line. Must be specified for both DataSeries and DataSeriesValues.
*/
private bool $smoothLine = false;
/**
* Get Smooth Line.
*/
public function getSmoothLine(): bool
{
return $this->smoothLine;
}
/**
* Set Smooth Line.
*
* @return $this
*/
public function setSmoothLine(bool $smoothLine): static
{
$this->smoothLine = $smoothLine;
return $this;
}
public function getLabelLayout(): ?Layout
{
return $this->labelLayout;
}
public function setLabelLayout(?Layout $labelLayout): self
{
$this->labelLayout = $labelLayout;
return $this;
}
/** @param TrendLine[] $trendLines */
public function setTrendLines(array $trendLines): self
{
$this->trendLines = $trendLines;
return $this;
}
/** @return TrendLine[] */
public function getTrendLines(): array
{
return $this->trendLines;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
parent::__clone();
$this->markerFillColor = clone $this->markerFillColor;
$this->markerBorderColor = clone $this->markerBorderColor;
if (is_array($this->fillColor)) {
$fillColor = $this->fillColor;
$this->fillColor = [];
foreach ($fillColor as $color) {
$this->fillColor[] = clone $color;
}
} elseif ($this->fillColor instanceof ChartColor) {
$this->fillColor = clone $this->fillColor;
}
$this->labelLayout = ($this->labelLayout === null) ? null : clone $this->labelLayout;
$trendLines = $this->trendLines;
$this->trendLines = [];
foreach ($trendLines as $trendLine) {
$this->trendLines[] = clone $trendLine;
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/Chart.php | src/PhpSpreadsheet/Chart/Chart.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
use PhpOffice\PhpSpreadsheet\Settings;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class Chart
{
/**
* Chart Name.
*/
private string $name;
/**
* Worksheet.
*/
private ?Worksheet $worksheet = null;
/**
* Chart Title.
*/
private ?Title $title;
/**
* Chart Legend.
*/
private ?Legend $legend;
/**
* X-Axis Label.
*/
private ?Title $xAxisLabel;
/**
* Y-Axis Label.
*/
private ?Title $yAxisLabel;
/**
* Chart Plot Area.
*/
private ?PlotArea $plotArea;
/**
* Plot Visible Only.
*/
private bool $plotVisibleOnly;
/**
* Display Blanks as.
*/
private string $displayBlanksAs;
/**
* Chart Asix Y as.
*/
private Axis $yAxis;
/**
* Chart Asix X as.
*/
private Axis $xAxis;
/**
* Top-Left Cell Position.
*/
private string $topLeftCellRef = 'A1';
/**
* Top-Left X-Offset.
*/
private int $topLeftXOffset = 0;
/**
* Top-Left Y-Offset.
*/
private int $topLeftYOffset = 0;
/**
* Bottom-Right Cell Position.
*/
private string $bottomRightCellRef = '';
/**
* Bottom-Right X-Offset.
*/
private int $bottomRightXOffset = 10;
/**
* Bottom-Right Y-Offset.
*/
private int $bottomRightYOffset = 10;
private ?int $rotX = null;
private ?int $rotY = null;
private ?int $rAngAx = null;
private ?int $perspective = null;
private bool $oneCellAnchor = false;
private bool $autoTitleDeleted = false;
private bool $noFill = false;
private bool $noBorder = false;
private bool $roundedCorners = false;
private GridLines $borderLines;
private ChartColor $fillColor;
/**
* Rendered width in pixels.
*/
private ?float $renderedWidth = null;
/**
* Rendered height in pixels.
*/
private ?float $renderedHeight = null;
/**
* Create a new Chart.
* majorGridlines and minorGridlines are deprecated, moved to Axis.
*/
public function __construct(string $name, ?Title $title = null, ?Legend $legend = null, ?PlotArea $plotArea = null, bool $plotVisibleOnly = true, string $displayBlanksAs = DataSeries::DEFAULT_EMPTY_AS, ?Title $xAxisLabel = null, ?Title $yAxisLabel = null, ?Axis $xAxis = null, ?Axis $yAxis = null, ?GridLines $majorGridlines = null, ?GridLines $minorGridlines = null)
{
$this->name = $name;
$this->title = $title;
$this->legend = $legend;
$this->xAxisLabel = $xAxisLabel;
$this->yAxisLabel = $yAxisLabel;
$this->plotArea = $plotArea;
$this->plotVisibleOnly = $plotVisibleOnly;
$this->setDisplayBlanksAs($displayBlanksAs);
$this->xAxis = $xAxis ?? new Axis();
$this->yAxis = $yAxis ?? new Axis();
if ($majorGridlines !== null) {
$this->yAxis->setMajorGridlines($majorGridlines);
}
if ($minorGridlines !== null) {
$this->yAxis->setMinorGridlines($minorGridlines);
}
$this->fillColor = new ChartColor();
$this->borderLines = new GridLines();
}
public function __destruct()
{
$this->worksheet = null;
}
/**
* Get Name.
*/
public function getName(): string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* Get Worksheet.
*/
public function getWorksheet(): ?Worksheet
{
return $this->worksheet;
}
/**
* Set Worksheet.
*
* @return $this
*/
public function setWorksheet(?Worksheet $worksheet = null): static
{
$this->worksheet = $worksheet;
return $this;
}
public function getTitle(): ?Title
{
return $this->title;
}
/**
* Set Title.
*
* @return $this
*/
public function setTitle(Title $title): static
{
$this->title = $title;
return $this;
}
public function getLegend(): ?Legend
{
return $this->legend;
}
/**
* Set Legend.
*
* @return $this
*/
public function setLegend(Legend $legend): static
{
$this->legend = $legend;
return $this;
}
public function getXAxisLabel(): ?Title
{
return $this->xAxisLabel;
}
/**
* Set X-Axis Label.
*
* @return $this
*/
public function setXAxisLabel(Title $label): static
{
$this->xAxisLabel = $label;
return $this;
}
public function getYAxisLabel(): ?Title
{
return $this->yAxisLabel;
}
/**
* Set Y-Axis Label.
*
* @return $this
*/
public function setYAxisLabel(Title $label): static
{
$this->yAxisLabel = $label;
return $this;
}
public function getPlotArea(): ?PlotArea
{
return $this->plotArea;
}
public function getPlotAreaOrThrow(): PlotArea
{
$plotArea = $this->getPlotArea();
if ($plotArea !== null) {
return $plotArea;
}
throw new Exception('Chart has no PlotArea');
}
/**
* Set Plot Area.
*/
public function setPlotArea(PlotArea $plotArea): self
{
$this->plotArea = $plotArea;
return $this;
}
/**
* Get Plot Visible Only.
*/
public function getPlotVisibleOnly(): bool
{
return $this->plotVisibleOnly;
}
/**
* Set Plot Visible Only.
*
* @return $this
*/
public function setPlotVisibleOnly(bool $plotVisibleOnly): static
{
$this->plotVisibleOnly = $plotVisibleOnly;
return $this;
}
/**
* Get Display Blanks as.
*/
public function getDisplayBlanksAs(): string
{
return $this->displayBlanksAs;
}
/**
* Set Display Blanks as.
*
* @return $this
*/
public function setDisplayBlanksAs(string $displayBlanksAs): static
{
$displayBlanksAs = strtolower($displayBlanksAs);
$this->displayBlanksAs = in_array($displayBlanksAs, DataSeries::VALID_EMPTY_AS, true) ? $displayBlanksAs : DataSeries::DEFAULT_EMPTY_AS;
return $this;
}
public function getChartAxisY(): Axis
{
return $this->yAxis;
}
/**
* Set yAxis.
*/
public function setChartAxisY(?Axis $axis): self
{
$this->yAxis = $axis ?? new Axis();
return $this;
}
public function getChartAxisX(): Axis
{
return $this->xAxis;
}
/**
* Set xAxis.
*/
public function setChartAxisX(?Axis $axis): self
{
$this->xAxis = $axis ?? new Axis();
return $this;
}
/**
* Set the Top Left position for the chart.
*
* @return $this
*/
public function setTopLeftPosition(string $cellAddress, ?int $xOffset = null, ?int $yOffset = null): static
{
$this->topLeftCellRef = $cellAddress;
if ($xOffset !== null) {
$this->setTopLeftXOffset($xOffset);
}
if ($yOffset !== null) {
$this->setTopLeftYOffset($yOffset);
}
return $this;
}
/**
* Get the top left position of the chart.
*
* Returns ['cell' => string cell address, 'xOffset' => int, 'yOffset' => int].
*
* @return array{cell: string, xOffset: int, yOffset: int} an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell
*/
public function getTopLeftPosition(): array
{
return [
'cell' => $this->topLeftCellRef,
'xOffset' => $this->topLeftXOffset,
'yOffset' => $this->topLeftYOffset,
];
}
/**
* Get the cell address where the top left of the chart is fixed.
*/
public function getTopLeftCell(): string
{
return $this->topLeftCellRef;
}
/**
* Set the Top Left cell position for the chart.
*
* @return $this
*/
public function setTopLeftCell(string $cellAddress): static
{
$this->topLeftCellRef = $cellAddress;
return $this;
}
/**
* Set the offset position within the Top Left cell for the chart.
*
* @return $this
*/
public function setTopLeftOffset(?int $xOffset, ?int $yOffset): static
{
if ($xOffset !== null) {
$this->setTopLeftXOffset($xOffset);
}
if ($yOffset !== null) {
$this->setTopLeftYOffset($yOffset);
}
return $this;
}
/**
* Get the offset position within the Top Left cell for the chart.
*
* @return int[]
*/
public function getTopLeftOffset(): array
{
return [
'X' => $this->topLeftXOffset,
'Y' => $this->topLeftYOffset,
];
}
/**
* @return $this
*/
public function setTopLeftXOffset(int $xOffset): static
{
$this->topLeftXOffset = $xOffset;
return $this;
}
public function getTopLeftXOffset(): int
{
return $this->topLeftXOffset;
}
/**
* @return $this
*/
public function setTopLeftYOffset(int $yOffset): static
{
$this->topLeftYOffset = $yOffset;
return $this;
}
public function getTopLeftYOffset(): int
{
return $this->topLeftYOffset;
}
/**
* Set the Bottom Right position of the chart.
*
* @return $this
*/
public function setBottomRightPosition(string $cellAddress = '', ?int $xOffset = null, ?int $yOffset = null): static
{
$this->bottomRightCellRef = $cellAddress;
if ($xOffset !== null) {
$this->setBottomRightXOffset($xOffset);
}
if ($yOffset !== null) {
$this->setBottomRightYOffset($yOffset);
}
return $this;
}
/**
* Get the bottom right position of the chart.
*
* @return array{cell: string, xOffset: int, yOffset:int} an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell
*/
public function getBottomRightPosition(): array
{
return [
'cell' => $this->bottomRightCellRef,
'xOffset' => $this->bottomRightXOffset,
'yOffset' => $this->bottomRightYOffset,
];
}
/**
* Set the Bottom Right cell for the chart.
*
* @return $this
*/
public function setBottomRightCell(string $cellAddress = ''): static
{
$this->bottomRightCellRef = $cellAddress;
return $this;
}
/**
* Get the cell address where the bottom right of the chart is fixed.
*/
public function getBottomRightCell(): string
{
return $this->bottomRightCellRef;
}
/**
* Set the offset position within the Bottom Right cell for the chart.
*
* @return $this
*/
public function setBottomRightOffset(?int $xOffset, ?int $yOffset): static
{
if ($xOffset !== null) {
$this->setBottomRightXOffset($xOffset);
}
if ($yOffset !== null) {
$this->setBottomRightYOffset($yOffset);
}
return $this;
}
/**
* Get the offset position within the Bottom Right cell for the chart.
*
* @return int[]
*/
public function getBottomRightOffset(): array
{
return [
'X' => $this->bottomRightXOffset,
'Y' => $this->bottomRightYOffset,
];
}
/**
* @return $this
*/
public function setBottomRightXOffset(int $xOffset): static
{
$this->bottomRightXOffset = $xOffset;
return $this;
}
public function getBottomRightXOffset(): int
{
return $this->bottomRightXOffset;
}
/**
* @return $this
*/
public function setBottomRightYOffset(int $yOffset): static
{
$this->bottomRightYOffset = $yOffset;
return $this;
}
public function getBottomRightYOffset(): int
{
return $this->bottomRightYOffset;
}
public function refresh(): void
{
if ($this->worksheet !== null && $this->plotArea !== null) {
$this->plotArea->refresh($this->worksheet);
}
}
/**
* Render the chart to given file (or stream).
*
* @param ?string $outputDestination Name of the file render to
*
* @return bool true on success
*/
public function render(?string $outputDestination = null): bool
{
if ($outputDestination == 'php://output') {
$outputDestination = null;
}
$libraryName = Settings::getChartRenderer();
if ($libraryName === null) {
return false;
}
// Ensure that data series values are up-to-date before we render
$this->refresh();
$renderer = new $libraryName($this);
return $renderer->render($outputDestination);
}
public function getRotX(): ?int
{
return $this->rotX;
}
public function setRotX(?int $rotX): self
{
$this->rotX = $rotX;
return $this;
}
public function getRotY(): ?int
{
return $this->rotY;
}
public function setRotY(?int $rotY): self
{
$this->rotY = $rotY;
return $this;
}
public function getRAngAx(): ?int
{
return $this->rAngAx;
}
public function setRAngAx(?int $rAngAx): self
{
$this->rAngAx = $rAngAx;
return $this;
}
public function getPerspective(): ?int
{
return $this->perspective;
}
public function setPerspective(?int $perspective): self
{
$this->perspective = $perspective;
return $this;
}
public function getOneCellAnchor(): bool
{
return $this->oneCellAnchor;
}
public function setOneCellAnchor(bool $oneCellAnchor): self
{
$this->oneCellAnchor = $oneCellAnchor;
return $this;
}
public function getAutoTitleDeleted(): bool
{
return $this->autoTitleDeleted;
}
public function setAutoTitleDeleted(bool $autoTitleDeleted): self
{
$this->autoTitleDeleted = $autoTitleDeleted;
return $this;
}
public function getNoFill(): bool
{
return $this->noFill;
}
public function setNoFill(bool $noFill): self
{
$this->noFill = $noFill;
return $this;
}
public function getNoBorder(): bool
{
return $this->noBorder;
}
public function setNoBorder(bool $noBorder): self
{
$this->noBorder = $noBorder;
return $this;
}
public function getRoundedCorners(): bool
{
return $this->roundedCorners;
}
public function setRoundedCorners(?bool $roundedCorners): self
{
if ($roundedCorners !== null) {
$this->roundedCorners = $roundedCorners;
}
return $this;
}
public function getBorderLines(): GridLines
{
return $this->borderLines;
}
public function setBorderLines(GridLines $borderLines): self
{
$this->borderLines = $borderLines;
return $this;
}
public function getFillColor(): ChartColor
{
return $this->fillColor;
}
public function setRenderedWidth(?float $width): self
{
$this->renderedWidth = $width;
return $this;
}
public function getRenderedWidth(): ?float
{
return $this->renderedWidth;
}
public function setRenderedHeight(?float $height): self
{
$this->renderedHeight = $height;
return $this;
}
public function getRenderedHeight(): ?float
{
return $this->renderedHeight;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$this->worksheet = null;
$this->title = ($this->title === null) ? null : clone $this->title;
$this->legend = ($this->legend === null) ? null : clone $this->legend;
$this->xAxisLabel = ($this->xAxisLabel === null) ? null : clone $this->xAxisLabel;
$this->yAxisLabel = ($this->yAxisLabel === null) ? null : clone $this->yAxisLabel;
$this->plotArea = ($this->plotArea === null) ? null : clone $this->plotArea;
$this->xAxis = clone $this->xAxis;
$this->yAxis = clone $this->yAxis;
$this->borderLines = clone $this->borderLines;
$this->fillColor = clone $this->fillColor;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/PlotArea.php | src/PhpSpreadsheet/Chart/PlotArea.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class PlotArea
{
/**
* No fill in plot area (show Excel gridlines through chart).
*/
private bool $noFill = false;
/**
* PlotArea Gradient Stop list.
* Each entry is a 2-element array.
* First is position in %.
* Second is ChartColor.
*
* @var array<array{float, ChartColor}>
*/
private array $gradientFillStops = [];
/**
* PlotArea Gradient Angle.
*/
private ?float $gradientFillAngle = null;
/**
* PlotArea Layout.
*/
private ?Layout $layout;
/**
* Plot Series.
*
* @var DataSeries[]
*/
private array $plotSeries;
/**
* Create a new PlotArea.
*
* @param DataSeries[] $plotSeries
*/
public function __construct(?Layout $layout = null, array $plotSeries = [])
{
$this->layout = $layout;
$this->plotSeries = $plotSeries;
}
public function getLayout(): ?Layout
{
return $this->layout;
}
/**
* Get Number of Plot Groups.
*/
public function getPlotGroupCount(): int
{
return count($this->plotSeries);
}
/**
* Get Number of Plot Series.
*/
public function getPlotSeriesCount(): int|float
{
$seriesCount = 0;
foreach ($this->plotSeries as $plot) {
$seriesCount += $plot->getPlotSeriesCount();
}
return $seriesCount;
}
/**
* Get Plot Series.
*
* @return DataSeries[]
*/
public function getPlotGroup(): array
{
return $this->plotSeries;
}
/**
* Get Plot Series by Index.
*/
public function getPlotGroupByIndex(int $index): DataSeries
{
return $this->plotSeries[$index];
}
/**
* Set Plot Series.
*
* @param DataSeries[] $plotSeries
*
* @return $this
*/
public function setPlotSeries(array $plotSeries): static
{
$this->plotSeries = $plotSeries;
return $this;
}
public function refresh(Worksheet $worksheet): void
{
foreach ($this->plotSeries as $plotSeries) {
$plotSeries->refresh($worksheet);
}
}
public function setNoFill(bool $noFill): self
{
$this->noFill = $noFill;
return $this;
}
public function getNoFill(): bool
{
return $this->noFill;
}
/** @param array<array{float, ChartColor}> $gradientFillStops */
public function setGradientFillProperties(array $gradientFillStops, ?float $gradientFillAngle): self
{
$this->gradientFillStops = $gradientFillStops;
$this->gradientFillAngle = $gradientFillAngle;
return $this;
}
/**
* Get gradientFillAngle.
*/
public function getGradientFillAngle(): ?float
{
return $this->gradientFillAngle;
}
/**
* Get gradientFillStops.
*
* @return array<array{float, ChartColor}>
*/
public function getGradientFillStops(): array
{
return $this->gradientFillStops;
}
private ?int $gapWidth = null;
private bool $useUpBars = false;
private bool $useDownBars = false;
public function getGapWidth(): ?int
{
return $this->gapWidth;
}
public function setGapWidth(?int $gapWidth): self
{
$this->gapWidth = $gapWidth;
return $this;
}
public function getUseUpBars(): bool
{
return $this->useUpBars;
}
public function setUseUpBars(bool $useUpBars): self
{
$this->useUpBars = $useUpBars;
return $this;
}
public function getUseDownBars(): bool
{
return $this->useDownBars;
}
public function setUseDownBars(bool $useDownBars): self
{
$this->useDownBars = $useDownBars;
return $this;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$this->layout = ($this->layout === null) ? null : clone $this->layout;
$plotSeries = $this->plotSeries;
$this->plotSeries = [];
foreach ($plotSeries as $series) {
$this->plotSeries[] = clone $series;
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/GridLines.php | src/PhpSpreadsheet/Chart/GridLines.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
/**
* Created by PhpStorm.
* User: Wiktor Trzonkowski
* Date: 7/2/14
* Time: 2:36 PM.
*/
class GridLines extends Properties
{
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/TrendLine.php | src/PhpSpreadsheet/Chart/TrendLine.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart;
class TrendLine extends Properties
{
const TRENDLINE_EXPONENTIAL = 'exp';
const TRENDLINE_LINEAR = 'linear';
const TRENDLINE_LOGARITHMIC = 'log';
const TRENDLINE_POLYNOMIAL = 'poly'; // + 'order'
const TRENDLINE_POWER = 'power';
const TRENDLINE_MOVING_AVG = 'movingAvg'; // + 'period'
const TRENDLINE_TYPES = [
self::TRENDLINE_EXPONENTIAL,
self::TRENDLINE_LINEAR,
self::TRENDLINE_LOGARITHMIC,
self::TRENDLINE_POLYNOMIAL,
self::TRENDLINE_POWER,
self::TRENDLINE_MOVING_AVG,
];
private string $trendLineType = 'linear'; // TRENDLINE_LINEAR
private int $order = 2;
private int $period = 3;
private bool $dispRSqr = false;
private bool $dispEq = false;
private string $name = '';
private float $backward = 0.0;
private float $forward = 0.0;
private float $intercept = 0.0;
/**
* Create a new TrendLine object.
*/
public function __construct(
string $trendLineType = '',
?int $order = null,
?int $period = null,
bool $dispRSqr = false,
bool $dispEq = false,
?float $backward = null,
?float $forward = null,
?float $intercept = null,
?string $name = null
) {
parent::__construct();
$this->setTrendLineProperties(
$trendLineType,
$order,
$period,
$dispRSqr,
$dispEq,
$backward,
$forward,
$intercept,
$name
);
}
public function getTrendLineType(): string
{
return $this->trendLineType;
}
public function setTrendLineType(string $trendLineType): self
{
$this->trendLineType = $trendLineType;
return $this;
}
public function getOrder(): int
{
return $this->order;
}
public function setOrder(int $order): self
{
$this->order = $order;
return $this;
}
public function getPeriod(): int
{
return $this->period;
}
public function setPeriod(int $period): self
{
$this->period = $period;
return $this;
}
public function getDispRSqr(): bool
{
return $this->dispRSqr;
}
public function setDispRSqr(bool $dispRSqr): self
{
$this->dispRSqr = $dispRSqr;
return $this;
}
public function getDispEq(): bool
{
return $this->dispEq;
}
public function setDispEq(bool $dispEq): self
{
$this->dispEq = $dispEq;
return $this;
}
public function getName(): string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getBackward(): float
{
return $this->backward;
}
public function setBackward(float $backward): self
{
$this->backward = $backward;
return $this;
}
public function getForward(): float
{
return $this->forward;
}
public function setForward(float $forward): self
{
$this->forward = $forward;
return $this;
}
public function getIntercept(): float
{
return $this->intercept;
}
public function setIntercept(float $intercept): self
{
$this->intercept = $intercept;
return $this;
}
public function setTrendLineProperties(
?string $trendLineType = null,
?int $order = 0,
?int $period = 0,
?bool $dispRSqr = false,
?bool $dispEq = false,
?float $backward = null,
?float $forward = null,
?float $intercept = null,
?string $name = null
): self {
if (!empty($trendLineType)) {
$this->setTrendLineType($trendLineType);
}
if ($order !== null) {
$this->setOrder($order);
}
if ($period !== null) {
$this->setPeriod($period);
}
if ($dispRSqr !== null) {
$this->setDispRSqr($dispRSqr);
}
if ($dispEq !== null) {
$this->setDispEq($dispEq);
}
if ($backward !== null) {
$this->setBackward($backward);
}
if ($forward !== null) {
$this->setForward($forward);
}
if ($intercept !== null) {
$this->setIntercept($intercept);
}
if ($name !== null) {
$this->setName($name);
}
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/Renderer/JpGraphRendererBase.php | src/PhpSpreadsheet/Chart/Renderer/JpGraphRendererBase.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart\Renderer;
use AccBarPlot;
use AccLinePlot;
use BarPlot;
use ContourPlot;
use Graph;
use GroupBarPlot;
use LinePlot;
use PhpOffice\PhpSpreadsheet\Chart\Chart;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PieGraph;
use PiePlot;
use PiePlot3D;
use PiePlotC;
use RadarGraph;
use RadarPlot;
use ScatterPlot;
use Spline;
use StockPlot;
/**
* Base class for different Jpgraph implementations as charts renderer.
*/
abstract class JpGraphRendererBase implements IRenderer
{
private const DEFAULT_WIDTH = 640.0;
private const DEFAULT_HEIGHT = 480.0;
private static $colourSet = [
'mediumpurple1', 'palegreen3', 'gold1', 'cadetblue1',
'darkmagenta', 'coral', 'dodgerblue3', 'eggplant',
'mediumblue', 'magenta', 'sandybrown', 'cyan',
'firebrick1', 'forestgreen', 'deeppink4', 'darkolivegreen',
'goldenrod2',
];
private static array $markSet;
private Chart $chart;
private $graph;
private static $plotColour = 0;
private static $plotMark = 0;
/**
* Create a new jpgraph.
*/
public function __construct(Chart $chart)
{
static::init();
$this->graph = null;
$this->chart = $chart;
self::$markSet = [
'diamond' => MARK_DIAMOND,
'square' => MARK_SQUARE,
'triangle' => MARK_UTRIANGLE,
'x' => MARK_X,
'star' => MARK_STAR,
'dot' => MARK_FILLEDCIRCLE,
'dash' => MARK_DTRIANGLE,
'circle' => MARK_CIRCLE,
'plus' => MARK_CROSS,
];
}
private function getGraphWidth(): float
{
return $this->chart->getRenderedWidth() ?? self::DEFAULT_WIDTH;
}
private function getGraphHeight(): float
{
return $this->chart->getRenderedHeight() ?? self::DEFAULT_HEIGHT;
}
/**
* This method should be overridden in descendants to do real JpGraph library initialization.
*/
abstract protected static function init(): void;
private function formatPointMarker($seriesPlot, $markerID)
{
$plotMarkKeys = array_keys(self::$markSet);
if ($markerID === null) {
// Use default plot marker (next marker in the series)
self::$plotMark %= count(self::$markSet);
$seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$plotMark++]]);
} elseif ($markerID !== 'none') {
// Use specified plot marker (if it exists)
if (isset(self::$markSet[$markerID])) {
$seriesPlot->mark->SetType(self::$markSet[$markerID]);
} else {
// If the specified plot marker doesn't exist, use default plot marker (next marker in the series)
self::$plotMark %= count(self::$markSet);
$seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$plotMark++]]);
}
} else {
// Hide plot marker
$seriesPlot->mark->Hide();
}
$seriesPlot->mark->SetColor(self::$colourSet[self::$plotColour]);
$seriesPlot->mark->SetFillColor(self::$colourSet[self::$plotColour]);
$seriesPlot->SetColor(self::$colourSet[self::$plotColour++]);
return $seriesPlot;
}
private function formatDataSetLabels(int $groupID, array $datasetLabels, $rotation = '')
{
$datasetLabelFormatCode = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getFormatCode() ?? '';
// Retrieve any label formatting code
$datasetLabelFormatCode = stripslashes($datasetLabelFormatCode);
$testCurrentIndex = 0;
foreach ($datasetLabels as $i => $datasetLabel) {
if (is_array($datasetLabel)) {
if ($rotation == 'bar') {
$datasetLabels[$i] = implode(' ', $datasetLabel);
} else {
$datasetLabel = array_reverse($datasetLabel);
$datasetLabels[$i] = implode("\n", $datasetLabel);
}
} else {
// Format labels according to any formatting code
if ($datasetLabelFormatCode !== null) {
$datasetLabels[$i] = NumberFormat::toFormattedString($datasetLabel, $datasetLabelFormatCode);
}
}
++$testCurrentIndex;
}
return $datasetLabels;
}
private function percentageSumCalculation(int $groupID, $seriesCount)
{
$sumValues = [];
// Adjust our values to a percentage value across all series in the group
for ($i = 0; $i < $seriesCount; ++$i) {
if ($i == 0) {
$sumValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues();
} else {
$nextValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues();
foreach ($nextValues as $k => $value) {
if (isset($sumValues[$k])) {
$sumValues[$k] += $value;
} else {
$sumValues[$k] = $value;
}
}
}
}
return $sumValues;
}
private function percentageAdjustValues(array $dataValues, array $sumValues)
{
foreach ($dataValues as $k => $dataValue) {
$dataValues[$k] = $dataValue / $sumValues[$k] * 100;
}
return $dataValues;
}
private function getCaption($captionElement)
{
// Read any caption
$caption = ($captionElement !== null) ? $captionElement->getCaption() : null;
// Test if we have a title caption to display
if ($caption !== null) {
// If we do, it could be a plain string or an array
if (is_array($caption)) {
// Implode an array to a plain string
$caption = implode('', $caption);
}
}
return $caption;
}
private function renderTitle(): void
{
$title = $this->getCaption($this->chart->getTitle());
if ($title !== null) {
$this->graph->title->Set($title);
}
}
private function renderLegend(): void
{
$legend = $this->chart->getLegend();
if ($legend !== null) {
$legendPosition = $legend->getPosition();
switch ($legendPosition) {
case 'r':
$this->graph->legend->SetPos(0.01, 0.5, 'right', 'center'); // right
$this->graph->legend->SetColumns(1);
break;
case 'l':
$this->graph->legend->SetPos(0.01, 0.5, 'left', 'center'); // left
$this->graph->legend->SetColumns(1);
break;
case 't':
$this->graph->legend->SetPos(0.5, 0.01, 'center', 'top'); // top
break;
case 'b':
$this->graph->legend->SetPos(0.5, 0.99, 'center', 'bottom'); // bottom
break;
default:
$this->graph->legend->SetPos(0.01, 0.01, 'right', 'top'); // top-right
$this->graph->legend->SetColumns(1);
break;
}
} else {
$this->graph->legend->Hide();
}
}
private function renderCartesianPlotArea(string $type = 'textlin'): void
{
$this->graph = new Graph($this->getGraphWidth(), $this->getGraphHeight());
$this->graph->SetScale($type);
$this->renderTitle();
// Rotate for bar rather than column chart
$rotation = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotDirection();
$reverse = $rotation == 'bar';
$xAxisLabel = $this->chart->getXAxisLabel();
if ($xAxisLabel !== null) {
$title = $this->getCaption($xAxisLabel);
if ($title !== null) {
$this->graph->xaxis->SetTitle($title, 'center');
$this->graph->xaxis->title->SetMargin(35);
if ($reverse) {
$this->graph->xaxis->title->SetAngle(90);
$this->graph->xaxis->title->SetMargin(90);
}
}
}
$yAxisLabel = $this->chart->getYAxisLabel();
if ($yAxisLabel !== null) {
$title = $this->getCaption($yAxisLabel);
if ($title !== null) {
$this->graph->yaxis->SetTitle($title, 'center');
if ($reverse) {
$this->graph->yaxis->title->SetAngle(0);
$this->graph->yaxis->title->SetMargin(-55);
}
}
}
}
private function renderPiePlotArea(): void
{
$this->graph = new PieGraph($this->getGraphWidth(), $this->getGraphHeight());
$this->renderTitle();
}
private function renderRadarPlotArea(): void
{
$this->graph = new RadarGraph($this->getGraphWidth(), $this->getGraphHeight());
$this->graph->SetScale('lin');
$this->renderTitle();
}
private function getDataLabel(int $groupId, int $index): mixed
{
$plotLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupId)->getPlotLabelByIndex($index);
if (!$plotLabel) {
return '';
}
return $plotLabel->getDataValue();
}
private function renderPlotLine(int $groupID, bool $filled = false, bool $combination = false): void
{
$grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping();
$index = array_keys($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder())[0];
$labelCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getPointCount();
if ($labelCount > 0) {
$datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues();
$datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels);
$this->graph->xaxis->SetTickLabels($datasetLabels);
}
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
$seriesPlots = [];
if ($grouping == 'percentStacked') {
$sumValues = $this->percentageSumCalculation($groupID, $seriesCount);
} else {
$sumValues = [];
}
// Loop through each data series in turn
for ($i = 0; $i < $seriesCount; ++$i) {
$index = array_keys($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder())[$i];
$dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getDataValues();
$marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getPointMarker();
if ($grouping == 'percentStacked') {
$dataValues = $this->percentageAdjustValues($dataValues, $sumValues);
}
// Fill in any missing values in the $dataValues array
$testCurrentIndex = 0;
foreach ($dataValues as $k => $dataValue) {
while ($k != $testCurrentIndex) {
$dataValues[$testCurrentIndex] = null;
++$testCurrentIndex;
}
++$testCurrentIndex;
}
$seriesPlot = new LinePlot($dataValues);
if ($combination) {
$seriesPlot->SetBarCenter();
}
if ($filled) {
$seriesPlot->SetFilled(true);
$seriesPlot->SetColor('black');
$seriesPlot->SetFillColor(self::$colourSet[self::$plotColour++]);
} else {
// Set the appropriate plot marker
$this->formatPointMarker($seriesPlot, $marker);
}
$seriesPlot->SetLegend($this->getDataLabel($groupID, $index));
$seriesPlots[] = $seriesPlot;
}
if ($grouping == 'standard') {
$groupPlot = $seriesPlots;
} else {
$groupPlot = new AccLinePlot($seriesPlots);
}
$this->graph->Add($groupPlot);
}
private function renderPlotBar(int $groupID, ?string $dimensions = '2d'): void
{
$rotation = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotDirection();
// Rotate for bar rather than column chart
if (($groupID == 0) && ($rotation == 'bar')) {
$this->graph->Set90AndMargin();
}
$grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping();
$index = array_keys($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder())[0];
$labelCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getPointCount();
if ($labelCount > 0) {
$datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues();
$datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $rotation);
// Rotate for bar rather than column chart
if ($rotation == 'bar') {
$datasetLabels = array_reverse($datasetLabels);
$this->graph->yaxis->SetPos('max');
$this->graph->yaxis->SetLabelAlign('center', 'top');
$this->graph->yaxis->SetLabelSide(SIDE_RIGHT);
}
$this->graph->xaxis->SetTickLabels($datasetLabels);
}
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
$seriesPlots = [];
if ($grouping == 'percentStacked') {
$sumValues = $this->percentageSumCalculation($groupID, $seriesCount);
} else {
$sumValues = [];
}
// Loop through each data series in turn
for ($j = 0; $j < $seriesCount; ++$j) {
$index = array_keys($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder())[$j];
$dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($index)->getDataValues();
if ($grouping == 'percentStacked') {
$dataValues = $this->percentageAdjustValues($dataValues, $sumValues);
}
// Fill in any missing values in the $dataValues array
$testCurrentIndex = 0;
foreach ($dataValues as $k => $dataValue) {
while ($k != $testCurrentIndex) {
$dataValues[$testCurrentIndex] = null;
++$testCurrentIndex;
}
++$testCurrentIndex;
}
// Reverse the $dataValues order for bar rather than column chart
if ($rotation == 'bar') {
$dataValues = array_reverse($dataValues);
}
$seriesPlot = new BarPlot($dataValues);
$seriesPlot->SetColor('black');
$seriesPlot->SetFillColor(self::$colourSet[self::$plotColour++]);
if ($dimensions == '3d') {
$seriesPlot->SetShadow();
}
$seriesPlot->SetLegend($this->getDataLabel($groupID, $j));
$seriesPlots[] = $seriesPlot;
}
// Reverse the plot order for bar rather than column chart
if (($rotation == 'bar') && ($grouping != 'percentStacked')) {
$seriesPlots = array_reverse($seriesPlots);
}
if ($grouping == 'clustered') {
$groupPlot = new GroupBarPlot($seriesPlots);
} elseif ($grouping == 'standard') {
$groupPlot = new GroupBarPlot($seriesPlots);
} else {
$groupPlot = new AccBarPlot($seriesPlots);
if ($dimensions == '3d') {
$groupPlot->SetShadow();
}
}
$this->graph->Add($groupPlot);
}
private function renderPlotScatter(int $groupID, bool $bubble): void
{
$scatterStyle = $bubbleSize = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle();
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
// Loop through each data series in turn
for ($i = 0; $i < $seriesCount; ++$i) {
$plotCategoryByIndex = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i);
if ($plotCategoryByIndex === false) {
$plotCategoryByIndex = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0);
}
$dataValuesY = $plotCategoryByIndex->getDataValues();
$dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues();
$redoDataValuesY = true;
if ($bubble) {
if (!$bubbleSize) {
$bubbleSize = '10';
}
$redoDataValuesY = false;
foreach ($dataValuesY as $dataValueY) {
if (!is_int($dataValueY) && !is_float($dataValueY)) {
$redoDataValuesY = true;
break;
}
}
}
if ($redoDataValuesY) {
foreach ($dataValuesY as $k => $dataValueY) {
$dataValuesY[$k] = $k;
}
}
$seriesPlot = new ScatterPlot($dataValuesX, $dataValuesY);
if ($scatterStyle == 'lineMarker') {
$seriesPlot->SetLinkPoints();
$seriesPlot->link->SetColor(self::$colourSet[self::$plotColour]);
} elseif ($scatterStyle == 'smoothMarker') {
$spline = new Spline($dataValuesY, $dataValuesX);
[$splineDataY, $splineDataX] = $spline->Get(count($dataValuesX) * $this->getGraphWidth() / 20);
$lplot = new LinePlot($splineDataX, $splineDataY);
$lplot->SetColor(self::$colourSet[self::$plotColour]);
$this->graph->Add($lplot);
}
if ($bubble) {
$this->formatPointMarker($seriesPlot, 'dot');
$seriesPlot->mark->SetColor('black');
$seriesPlot->mark->SetSize($bubbleSize);
} else {
$marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker();
$this->formatPointMarker($seriesPlot, $marker);
}
$seriesPlot->SetLegend($this->getDataLabel($groupID, $i));
$this->graph->Add($seriesPlot);
}
}
private function renderPlotRadar(int $groupID): void
{
$radarStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle();
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
// Loop through each data series in turn
for ($i = 0; $i < $seriesCount; ++$i) {
$dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues();
$dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues();
$marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker();
$dataValues = [];
foreach ($dataValuesY as $k => $dataValueY) {
$dataValues[$k] = is_array($dataValueY) ? implode(' ', array_reverse($dataValueY)) : $dataValueY;
}
$tmp = array_shift($dataValues);
$dataValues[] = $tmp;
$tmp = array_shift($dataValuesX);
$dataValuesX[] = $tmp;
$this->graph->SetTitles(array_reverse($dataValues));
$seriesPlot = new RadarPlot(array_reverse($dataValuesX));
$seriesPlot->SetColor(self::$colourSet[self::$plotColour++]);
if ($radarStyle == 'filled') {
$seriesPlot->SetFillColor(self::$colourSet[self::$plotColour]);
}
$this->formatPointMarker($seriesPlot, $marker);
$seriesPlot->SetLegend($this->getDataLabel($groupID, $i));
$this->graph->Add($seriesPlot);
}
}
private function renderPlotContour(int $groupID): void
{
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
$dataValues = [];
// Loop through each data series in turn
for ($i = 0; $i < $seriesCount; ++$i) {
$dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues();
$dataValues[$i] = $dataValuesX;
}
$seriesPlot = new ContourPlot($dataValues);
$this->graph->Add($seriesPlot);
}
private function renderPlotStock(int $groupID): void
{
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
$plotOrder = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder();
$dataValues = [];
// Loop through each data series in turn and build the plot arrays
foreach ($plotOrder as $i => $v) {
$dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v);
if ($dataValuesX === false) {
continue;
}
$dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v)->getDataValues();
foreach ($dataValuesX as $j => $dataValueX) {
$dataValues[$plotOrder[$i]][$j] = $dataValueX;
}
}
if (empty($dataValues)) {
return;
}
$dataValuesPlot = [];
// Flatten the plot arrays to a single dimensional array to work with jpgraph
$jMax = count($dataValues[0]);
for ($j = 0; $j < $jMax; ++$j) {
for ($i = 0; $i < $seriesCount; ++$i) {
$dataValuesPlot[] = $dataValues[$i][$j] ?? null;
}
}
// Set the x-axis labels
$labelCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount();
if ($labelCount > 0) {
$datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues();
$datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels);
$this->graph->xaxis->SetTickLabels($datasetLabels);
}
$seriesPlot = new StockPlot($dataValuesPlot);
$seriesPlot->SetWidth(20);
$this->graph->Add($seriesPlot);
}
private function renderAreaChart($groupCount): void
{
$this->renderCartesianPlotArea();
for ($i = 0; $i < $groupCount; ++$i) {
$this->renderPlotLine($i, true, false);
}
}
private function renderLineChart($groupCount): void
{
$this->renderCartesianPlotArea();
for ($i = 0; $i < $groupCount; ++$i) {
$this->renderPlotLine($i, false, false);
}
}
private function renderBarChart($groupCount, ?string $dimensions = '2d'): void
{
$this->renderCartesianPlotArea();
for ($i = 0; $i < $groupCount; ++$i) {
$this->renderPlotBar($i, $dimensions);
}
}
private function renderScatterChart($groupCount): void
{
$this->renderCartesianPlotArea('linlin');
for ($i = 0; $i < $groupCount; ++$i) {
$this->renderPlotScatter($i, false);
}
}
private function renderBubbleChart($groupCount): void
{
$this->renderCartesianPlotArea('linlin');
for ($i = 0; $i < $groupCount; ++$i) {
$this->renderPlotScatter($i, true);
}
}
private function renderPieChart($groupCount, ?string $dimensions = '2d', bool $doughnut = false, bool $multiplePlots = false): void
{
$this->renderPiePlotArea();
$iLimit = ($multiplePlots) ? $groupCount : 1;
for ($groupID = 0; $groupID < $iLimit; ++$groupID) {
$exploded = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle();
$datasetLabels = [];
if ($groupID == 0) {
$labelCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount();
if ($labelCount > 0) {
$datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues();
$datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels);
}
}
$seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount();
// For pie charts, we only display the first series: doughnut charts generally display all series
$jLimit = ($multiplePlots) ? $seriesCount : 1;
// Loop through each data series in turn
for ($j = 0; $j < $jLimit; ++$j) {
$dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues();
// Fill in any missing values in the $dataValues array
$testCurrentIndex = 0;
foreach ($dataValues as $k => $dataValue) {
while ($k != $testCurrentIndex) {
$dataValues[$testCurrentIndex] = null;
++$testCurrentIndex;
}
++$testCurrentIndex;
}
if ($dimensions == '3d') {
$seriesPlot = new PiePlot3D($dataValues);
} else {
if ($doughnut) {
$seriesPlot = new PiePlotC($dataValues);
} else {
$seriesPlot = new PiePlot($dataValues);
}
}
if ($multiplePlots) {
$seriesPlot->SetSize(($jLimit - $j) / ($jLimit * 4));
}
if ($doughnut && method_exists($seriesPlot, 'SetMidColor')) {
$seriesPlot->SetMidColor('white');
}
$seriesPlot->SetColor(self::$colourSet[self::$plotColour++]);
if (count($datasetLabels) > 0) {
$seriesPlot->SetLabels(array_fill(0, count($datasetLabels), ''));
}
if ($dimensions != '3d') {
$seriesPlot->SetGuideLines(false);
}
if ($j == 0) {
if ($exploded) {
$seriesPlot->ExplodeAll();
}
$seriesPlot->SetLegends($datasetLabels);
}
$this->graph->Add($seriesPlot);
}
}
}
private function renderRadarChart($groupCount): void
{
$this->renderRadarPlotArea();
for ($groupID = 0; $groupID < $groupCount; ++$groupID) {
$this->renderPlotRadar($groupID);
}
}
private function renderStockChart($groupCount): void
{
$this->renderCartesianPlotArea('intint');
for ($groupID = 0; $groupID < $groupCount; ++$groupID) {
$this->renderPlotStock($groupID);
}
}
private function renderContourChart($groupCount): void
{
$this->renderCartesianPlotArea('intint');
for ($i = 0; $i < $groupCount; ++$i) {
$this->renderPlotContour($i);
}
}
private function renderCombinationChart($groupCount, $outputDestination): bool
{
$this->renderCartesianPlotArea();
for ($i = 0; $i < $groupCount; ++$i) {
$dimensions = null;
$chartType = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType();
switch ($chartType) {
case 'area3DChart':
case 'areaChart':
$this->renderPlotLine($i, true, true);
break;
case 'bar3DChart':
$dimensions = '3d';
// no break
case 'barChart':
$this->renderPlotBar($i, $dimensions);
break;
case 'line3DChart':
case 'lineChart':
$this->renderPlotLine($i, false, true);
break;
case 'scatterChart':
$this->renderPlotScatter($i, false);
break;
case 'bubbleChart':
$this->renderPlotScatter($i, true);
break;
default:
$this->graph = null;
return false;
}
}
$this->renderLegend();
$this->graph->Stroke($outputDestination);
return true;
}
public function render(?string $outputDestination): bool
{
self::$plotColour = 0;
$groupCount = $this->chart->getPlotArea()->getPlotGroupCount();
$dimensions = null;
if ($groupCount == 1) {
$chartType = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType();
} else {
$chartTypes = [];
for ($i = 0; $i < $groupCount; ++$i) {
$chartTypes[] = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType();
}
$chartTypes = array_unique($chartTypes);
if (count($chartTypes) == 1) {
$chartType = array_pop($chartTypes);
} elseif (count($chartTypes) == 0) {
echo 'Chart is not yet implemented<br />';
return false;
} else {
return $this->renderCombinationChart($groupCount, $outputDestination);
}
}
switch ($chartType) {
case 'area3DChart':
$dimensions = '3d';
// no break
case 'areaChart':
$this->renderAreaChart($groupCount);
break;
case 'bar3DChart':
$dimensions = '3d';
// no break
case 'barChart':
$this->renderBarChart($groupCount, $dimensions);
break;
case 'line3DChart':
$dimensions = '3d';
// no break
case 'lineChart':
$this->renderLineChart($groupCount);
break;
case 'pie3DChart':
$dimensions = '3d';
// no break
case 'pieChart':
$this->renderPieChart($groupCount, $dimensions, false, false);
break;
case 'doughnut3DChart':
$dimensions = '3d';
// no break
case 'doughnutChart':
$this->renderPieChart($groupCount, $dimensions, true, true);
break;
case 'scatterChart':
$this->renderScatterChart($groupCount);
break;
case 'bubbleChart':
$this->renderBubbleChart($groupCount);
break;
case 'radarChart':
$this->renderRadarChart($groupCount);
break;
case 'surface3DChart':
case 'surfaceChart':
$this->renderContourChart($groupCount);
break;
case 'stockChart':
$this->renderStockChart($groupCount);
break;
default:
echo $chartType . ' is not yet implemented<br />';
return false;
}
$this->renderLegend();
$this->graph->Stroke($outputDestination);
return true;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php | src/PhpSpreadsheet/Chart/Renderer/JpGraph.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart\Renderer;
/**
* Jpgraph is not officially maintained in Composer, so the version there
* could be out of date. For that reason, all unit test requiring Jpgraph
* are skipped. So, do not measure code coverage for this class till that
* is fixed.
*
* This implementation uses abandoned package
* https://packagist.org/packages/jpgraph/jpgraph
*
* @codeCoverageIgnore
*/
class JpGraph extends JpGraphRendererBase
{
protected static function init(): void
{
static $loaded = false;
if ($loaded) {
return;
}
// JpGraph is no longer included with distribution, but user may install it.
// So Scrutinizer's complaint that it can't find it is reasonable, but unfixable.
\JpGraph\JpGraph::load();
\JpGraph\JpGraph::module('bar');
\JpGraph\JpGraph::module('contour');
\JpGraph\JpGraph::module('line');
\JpGraph\JpGraph::module('pie');
\JpGraph\JpGraph::module('pie3d');
\JpGraph\JpGraph::module('radar');
\JpGraph\JpGraph::module('regstat');
\JpGraph\JpGraph::module('scatter');
\JpGraph\JpGraph::module('stock');
$loaded = true;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/Renderer/IRenderer.php | src/PhpSpreadsheet/Chart/Renderer/IRenderer.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart\Renderer;
use PhpOffice\PhpSpreadsheet\Chart\Chart;
interface IRenderer
{
/**
* IRenderer constructor.
*/
public function __construct(Chart $chart);
/**
* Render the chart to given file (or stream).
*
* @param ?string $filename Name of the file render to
*
* @return bool true on success
*/
public function render(?string $filename): bool;
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Chart/Renderer/MtJpGraphRenderer.php | src/PhpSpreadsheet/Chart/Renderer/MtJpGraphRenderer.php | <?php
namespace PhpOffice\PhpSpreadsheet\Chart\Renderer;
use mitoteam\jpgraph\MtJpGraph;
/**
* Jpgraph is not officially maintained by Composer at packagist.org.
*
* This renderer implementation uses package
* https://packagist.org/packages/mitoteam/jpgraph
*
* This package is up to date for June 2023 and has PHP 8.2 support.
*/
class MtJpGraphRenderer extends JpGraphRendererBase
{
protected static function init(): void
{
static $loaded = false;
if ($loaded) {
return;
}
MtJpGraph::load([
'bar',
'contour',
'line',
'pie',
'pie3d',
'radar',
'regstat',
'scatter',
'stock',
], true); // enable Extended mode
$loaded = true;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/CodePage.php | src/PhpSpreadsheet/Shared/CodePage.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
class CodePage
{
public const DEFAULT_CODE_PAGE = 'CP1252';
/** @var array<int, array<int, string>|string> */
private static array $pageArray = [
0 => 'CP1252', // CodePage is not always correctly set when the xls file was saved by Apple's Numbers program
367 => 'ASCII', // ASCII
437 => 'CP437', // OEM US
//720 => 'notsupported', // OEM Arabic
737 => 'CP737', // OEM Greek
775 => 'CP775', // OEM Baltic
850 => 'CP850', // OEM Latin I
852 => 'CP852', // OEM Latin II (Central European)
855 => 'CP855', // OEM Cyrillic
857 => 'CP857', // OEM Turkish
858 => 'CP858', // OEM Multilingual Latin I with Euro
860 => 'CP860', // OEM Portugese
861 => 'CP861', // OEM Icelandic
862 => 'CP862', // OEM Hebrew
863 => 'CP863', // OEM Canadian (French)
864 => 'CP864', // OEM Arabic
865 => 'CP865', // OEM Nordic
866 => 'CP866', // OEM Cyrillic (Russian)
869 => 'CP869', // OEM Greek (Modern)
874 => 'CP874', // ANSI Thai
932 => 'CP932', // ANSI Japanese Shift-JIS
936 => 'CP936', // ANSI Chinese Simplified GBK
949 => 'CP949', // ANSI Korean (Wansung)
950 => 'CP950', // ANSI Chinese Traditional BIG5
1200 => 'UTF-16LE', // UTF-16 (BIFF8)
1250 => 'CP1250', // ANSI Latin II (Central European)
1251 => 'CP1251', // ANSI Cyrillic
1252 => 'CP1252', // ANSI Latin I (BIFF4-BIFF7)
1253 => 'CP1253', // ANSI Greek
1254 => 'CP1254', // ANSI Turkish
1255 => 'CP1255', // ANSI Hebrew
1256 => 'CP1256', // ANSI Arabic
1257 => 'CP1257', // ANSI Baltic
1258 => 'CP1258', // ANSI Vietnamese
1361 => 'CP1361', // ANSI Korean (Johab)
10000 => 'MAC', // Apple Roman
10001 => 'CP932', // Macintosh Japanese
10002 => 'CP950', // Macintosh Chinese Traditional
10003 => 'CP1361', // Macintosh Korean
10004 => 'MACARABIC', // Apple Arabic
10005 => 'MACHEBREW', // Apple Hebrew
10006 => 'MACGREEK', // Macintosh Greek
10007 => 'MACCYRILLIC', // Macintosh Cyrillic
10008 => 'CP936', // Macintosh - Simplified Chinese (GB 2312)
10010 => 'MACROMANIA', // Macintosh Romania
10017 => 'MACUKRAINE', // Macintosh Ukraine
10021 => 'MACTHAI', // Macintosh Thai
10029 => ['MACCENTRALEUROPE', 'MAC-CENTRALEUROPE'], // Macintosh Central Europe
10079 => 'MACICELAND', // Macintosh Icelandic
10081 => 'MACTURKISH', // Macintosh Turkish
10082 => 'MACCROATIAN', // Macintosh Croatian
21010 => 'UTF-16LE', // UTF-16 (BIFF8) This isn't correct, but some Excel writer libraries erroneously use Codepage 21010 for UTF-16LE
32768 => 'MAC', // Apple Roman
//32769 => 'unsupported', // ANSI Latin I (BIFF2-BIFF3)
65000 => 'UTF-7', // Unicode (UTF-7)
65001 => 'UTF-8', // Unicode (UTF-8)
99999 => ['unsupported'], // Unicode (UTF-8)
];
public static function validate(string $codePage): bool
{
return in_array($codePage, self::$pageArray, true);
}
/**
* Convert Microsoft Code Page Identifier to Code Page Name which iconv
* and mbstring understands.
*
* @param int $codePage Microsoft Code Page Identifier
*
* @return string Code Page Name
*/
public static function numberToName(int $codePage): string
{
if (array_key_exists($codePage, self::$pageArray)) {
$value = self::$pageArray[$codePage];
if (is_array($value)) {
foreach ($value as $encoding) {
if (@iconv('UTF-8', $encoding, ' ') !== false) {
self::$pageArray[$codePage] = $encoding;
return $encoding;
}
}
throw new PhpSpreadsheetException("Code page $codePage not implemented on this system.");
} else {
return $value;
}
}
if ($codePage == 720 || $codePage == 32769) {
throw new PhpSpreadsheetException("Code page $codePage not supported."); // OEM Arabic
}
throw new PhpSpreadsheetException('Unknown codepage: ' . $codePage);
}
/** @return array<int, array<int, string>|string> */
public static function getEncodings(): array
{
return self::$pageArray;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Font.php | src/PhpSpreadsheet/Shared/Font.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Font as FontStyle;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class Font
{
// Methods for resolving autosize value
const AUTOSIZE_METHOD_APPROX = 'approx';
const AUTOSIZE_METHOD_EXACT = 'exact';
private const AUTOSIZE_METHODS = [
self::AUTOSIZE_METHOD_APPROX,
self::AUTOSIZE_METHOD_EXACT,
];
/** Character set codes used by BIFF5-8 in Font records */
const CHARSET_ANSI_LATIN = 0x00;
const CHARSET_SYSTEM_DEFAULT = 0x01;
const CHARSET_SYMBOL = 0x02;
const CHARSET_APPLE_ROMAN = 0x4D;
const CHARSET_ANSI_JAPANESE_SHIFTJIS = 0x80;
const CHARSET_ANSI_KOREAN_HANGUL = 0x81;
const CHARSET_ANSI_KOREAN_JOHAB = 0x82;
const CHARSET_ANSI_CHINESE_SIMIPLIFIED = 0x86; // gb2312
const CHARSET_ANSI_CHINESE_TRADITIONAL = 0x88; // big5
const CHARSET_ANSI_GREEK = 0xA1;
const CHARSET_ANSI_TURKISH = 0xA2;
const CHARSET_ANSI_VIETNAMESE = 0xA3;
const CHARSET_ANSI_HEBREW = 0xB1;
const CHARSET_ANSI_ARABIC = 0xB2;
const CHARSET_ANSI_BALTIC = 0xBA;
const CHARSET_ANSI_CYRILLIC = 0xCC;
const CHARSET_ANSI_THAI = 0xDD;
const CHARSET_ANSI_LATIN_II = 0xEE;
const CHARSET_OEM_LATIN_I = 0xFF;
// XXX: Constants created!
/** Font filenames */
const ARIAL = 'arial.ttf';
const ARIAL_BOLD = 'arialbd.ttf';
const ARIAL_ITALIC = 'ariali.ttf';
const ARIAL_BOLD_ITALIC = 'arialbi.ttf';
const CALIBRI = 'calibri.ttf';
const CALIBRI_BOLD = 'calibrib.ttf';
const CALIBRI_ITALIC = 'calibrii.ttf';
const CALIBRI_BOLD_ITALIC = 'calibriz.ttf';
const COMIC_SANS_MS = 'comic.ttf';
const COMIC_SANS_MS_BOLD = 'comicbd.ttf';
const COURIER_NEW = 'cour.ttf';
const COURIER_NEW_BOLD = 'courbd.ttf';
const COURIER_NEW_ITALIC = 'couri.ttf';
const COURIER_NEW_BOLD_ITALIC = 'courbi.ttf';
const GEORGIA = 'georgia.ttf';
const GEORGIA_BOLD = 'georgiab.ttf';
const GEORGIA_ITALIC = 'georgiai.ttf';
const GEORGIA_BOLD_ITALIC = 'georgiaz.ttf';
const IMPACT = 'impact.ttf';
const LIBERATION_SANS = 'LiberationSans-Regular.ttf';
const LIBERATION_SANS_BOLD = 'LiberationSans-Bold.ttf';
const LIBERATION_SANS_ITALIC = 'LiberationSans-Italic.ttf';
const LIBERATION_SANS_BOLD_ITALIC = 'LiberationSans-BoldItalic.ttf';
const LUCIDA_CONSOLE = 'lucon.ttf';
const LUCIDA_SANS_UNICODE = 'l_10646.ttf';
const MICROSOFT_SANS_SERIF = 'micross.ttf';
const PALATINO_LINOTYPE = 'pala.ttf';
const PALATINO_LINOTYPE_BOLD = 'palab.ttf';
const PALATINO_LINOTYPE_ITALIC = 'palai.ttf';
const PALATINO_LINOTYPE_BOLD_ITALIC = 'palabi.ttf';
const SYMBOL = 'symbol.ttf';
const TAHOMA = 'tahoma.ttf';
const TAHOMA_BOLD = 'tahomabd.ttf';
const TIMES_NEW_ROMAN = 'times.ttf';
const TIMES_NEW_ROMAN_BOLD = 'timesbd.ttf';
const TIMES_NEW_ROMAN_ITALIC = 'timesi.ttf';
const TIMES_NEW_ROMAN_BOLD_ITALIC = 'timesbi.ttf';
const TREBUCHET_MS = 'trebuc.ttf';
const TREBUCHET_MS_BOLD = 'trebucbd.ttf';
const TREBUCHET_MS_ITALIC = 'trebucit.ttf';
const TREBUCHET_MS_BOLD_ITALIC = 'trebucbi.ttf';
const VERDANA = 'verdana.ttf';
const VERDANA_BOLD = 'verdanab.ttf';
const VERDANA_ITALIC = 'verdanai.ttf';
const VERDANA_BOLD_ITALIC = 'verdanaz.ttf';
const FONT_FILE_NAMES = [
'Arial' => [
'x' => self::ARIAL,
'xb' => self::ARIAL_BOLD,
'xi' => self::ARIAL_ITALIC,
'xbi' => self::ARIAL_BOLD_ITALIC,
],
'Calibri' => [
'x' => self::CALIBRI,
'xb' => self::CALIBRI_BOLD,
'xi' => self::CALIBRI_ITALIC,
'xbi' => self::CALIBRI_BOLD_ITALIC,
],
'Comic Sans MS' => [
'x' => self::COMIC_SANS_MS,
'xb' => self::COMIC_SANS_MS_BOLD,
'xi' => self::COMIC_SANS_MS,
'xbi' => self::COMIC_SANS_MS_BOLD,
],
'Courier New' => [
'x' => self::COURIER_NEW,
'xb' => self::COURIER_NEW_BOLD,
'xi' => self::COURIER_NEW_ITALIC,
'xbi' => self::COURIER_NEW_BOLD_ITALIC,
],
'Georgia' => [
'x' => self::GEORGIA,
'xb' => self::GEORGIA_BOLD,
'xi' => self::GEORGIA_ITALIC,
'xbi' => self::GEORGIA_BOLD_ITALIC,
],
'Impact' => [
'x' => self::IMPACT,
'xb' => self::IMPACT,
'xi' => self::IMPACT,
'xbi' => self::IMPACT,
],
'Liberation Sans' => [
'x' => self::LIBERATION_SANS,
'xb' => self::LIBERATION_SANS_BOLD,
'xi' => self::LIBERATION_SANS_ITALIC,
'xbi' => self::LIBERATION_SANS_BOLD_ITALIC,
],
'Lucida Console' => [
'x' => self::LUCIDA_CONSOLE,
'xb' => self::LUCIDA_CONSOLE,
'xi' => self::LUCIDA_CONSOLE,
'xbi' => self::LUCIDA_CONSOLE,
],
'Lucida Sans Unicode' => [
'x' => self::LUCIDA_SANS_UNICODE,
'xb' => self::LUCIDA_SANS_UNICODE,
'xi' => self::LUCIDA_SANS_UNICODE,
'xbi' => self::LUCIDA_SANS_UNICODE,
],
'Microsoft Sans Serif' => [
'x' => self::MICROSOFT_SANS_SERIF,
'xb' => self::MICROSOFT_SANS_SERIF,
'xi' => self::MICROSOFT_SANS_SERIF,
'xbi' => self::MICROSOFT_SANS_SERIF,
],
'Palatino Linotype' => [
'x' => self::PALATINO_LINOTYPE,
'xb' => self::PALATINO_LINOTYPE_BOLD,
'xi' => self::PALATINO_LINOTYPE_ITALIC,
'xbi' => self::PALATINO_LINOTYPE_BOLD_ITALIC,
],
'Symbol' => [
'x' => self::SYMBOL,
'xb' => self::SYMBOL,
'xi' => self::SYMBOL,
'xbi' => self::SYMBOL,
],
'Tahoma' => [
'x' => self::TAHOMA,
'xb' => self::TAHOMA_BOLD,
'xi' => self::TAHOMA,
'xbi' => self::TAHOMA_BOLD,
],
'Times New Roman' => [
'x' => self::TIMES_NEW_ROMAN,
'xb' => self::TIMES_NEW_ROMAN_BOLD,
'xi' => self::TIMES_NEW_ROMAN_ITALIC,
'xbi' => self::TIMES_NEW_ROMAN_BOLD_ITALIC,
],
'Trebuchet MS' => [
'x' => self::TREBUCHET_MS,
'xb' => self::TREBUCHET_MS_BOLD,
'xi' => self::TREBUCHET_MS_ITALIC,
'xbi' => self::TREBUCHET_MS_BOLD_ITALIC,
],
'Verdana' => [
'x' => self::VERDANA,
'xb' => self::VERDANA_BOLD,
'xi' => self::VERDANA_ITALIC,
'xbi' => self::VERDANA_BOLD_ITALIC,
],
];
/**
* Array that can be used to supplement FONT_FILE_NAMES for calculating exact width.
*
* @var array<string, array<string, string>>
*/
private static array $extraFontArray = [];
/** @param array<string, array<string, string>> $extraFontArray */
public static function setExtraFontArray(array $extraFontArray): void
{
self::$extraFontArray = $extraFontArray;
}
/** @return array<string, array<string, string>> */
public static function getExtraFontArray(): array
{
return self::$extraFontArray;
}
/**
* AutoSize method.
*/
private static string $autoSizeMethod = self::AUTOSIZE_METHOD_APPROX;
/**
* Path to folder containing TrueType font .ttf files.
*/
private static string $trueTypeFontPath = '';
/**
* How wide is a default column for a given default font and size?
* Empirical data found by inspecting real Excel files and reading off the pixel width
* in Microsoft Office Excel 2007.
* Added height in points.
*/
public const DEFAULT_COLUMN_WIDTHS = [
'Arial' => [
1 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25],
2 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25],
3 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.0],
4 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.75],
5 => ['px' => 40, 'width' => 10.00000000, 'height' => 8.25],
6 => ['px' => 48, 'width' => 9.59765625, 'height' => 8.25],
7 => ['px' => 48, 'width' => 9.59765625, 'height' => 9.0],
8 => ['px' => 56, 'width' => 9.33203125, 'height' => 11.25],
9 => ['px' => 64, 'width' => 9.14062500, 'height' => 12.0],
10 => ['px' => 64, 'width' => 9.14062500, 'height' => 12.75],
],
'Calibri' => [
1 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25],
2 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25],
3 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.00],
4 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.75],
5 => ['px' => 40, 'width' => 10.00000000, 'height' => 8.25],
6 => ['px' => 48, 'width' => 9.59765625, 'height' => 8.25],
7 => ['px' => 48, 'width' => 9.59765625, 'height' => 9.0],
8 => ['px' => 56, 'width' => 9.33203125, 'height' => 11.25],
9 => ['px' => 56, 'width' => 9.33203125, 'height' => 12.0],
10 => ['px' => 64, 'width' => 9.14062500, 'height' => 12.75],
11 => ['px' => 64, 'width' => 9.14062500, 'height' => 15.0],
],
'Verdana' => [
1 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25],
2 => ['px' => 24, 'width' => 12.00000000, 'height' => 5.25],
3 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.0],
4 => ['px' => 32, 'width' => 10.66406250, 'height' => 6.75],
5 => ['px' => 40, 'width' => 10.00000000, 'height' => 8.25],
6 => ['px' => 48, 'width' => 9.59765625, 'height' => 8.25],
7 => ['px' => 48, 'width' => 9.59765625, 'height' => 9.0],
8 => ['px' => 64, 'width' => 9.14062500, 'height' => 10.5],
9 => ['px' => 72, 'width' => 9.00000000, 'height' => 11.25],
10 => ['px' => 72, 'width' => 9.00000000, 'height' => 12.75],
],
];
/**
* Set autoSize method.
*
* @param string $method see self::AUTOSIZE_METHOD_*
*
* @return bool Success or failure
*/
public static function setAutoSizeMethod(string $method): bool
{
if (!in_array($method, self::AUTOSIZE_METHODS)) {
return false;
}
self::$autoSizeMethod = $method;
return true;
}
/**
* Get autoSize method.
*/
public static function getAutoSizeMethod(): string
{
return self::$autoSizeMethod;
}
/**
* Set the path to the folder containing .ttf files. There should be a trailing slash.
* Path will be recursively searched for font file.
* Typical locations on various platforms:
* <ul>
* <li>C:/Windows/Fonts/</li>
* <li>/usr/share/fonts/truetype/</li>
* <li>~/.fonts/</li>
* </ul>.
*/
public static function setTrueTypeFontPath(string $folderPath): void
{
self::$trueTypeFontPath = $folderPath;
}
/**
* Get the path to the folder containing .ttf files.
*/
public static function getTrueTypeFontPath(): string
{
return self::$trueTypeFontPath;
}
/**
* Pad amount for exact in pixels; use best guess if null.
*/
private static null|float|int $paddingAmountExact = null;
/**
* Set pad amount for exact in pixels; use best guess if null.
*/
public static function setPaddingAmountExact(null|float|int $paddingAmountExact): void
{
self::$paddingAmountExact = $paddingAmountExact;
}
/**
* Get pad amount for exact in pixels; or null if using best guess.
*/
public static function getPaddingAmountExact(): null|float|int
{
return self::$paddingAmountExact;
}
/**
* Calculate an (approximate) OpenXML column width, based on font size and text contained.
*
* @param FontStyle $font Font object
* @param null|RichText|string $cellText Text to calculate width
* @param int $rotation Rotation angle
* @param null|FontStyle $defaultFont Font object
* @param bool $filterAdjustment Add space for Autofilter or Table dropdown
*/
public static function calculateColumnWidth(
FontStyle $font,
$cellText = '',
int $rotation = 0,
?FontStyle $defaultFont = null,
bool $filterAdjustment = false,
int $indentAdjustment = 0
): float {
// If it is rich text, use plain text
if ($cellText instanceof RichText) {
$cellText = $cellText->getPlainText();
}
// Special case if there are one or more newline characters ("\n")
$cellText = (string) $cellText;
if (str_contains($cellText, "\n")) {
$lineTexts = explode("\n", $cellText);
$lineWidths = [];
foreach ($lineTexts as $lineText) {
$lineWidths[] = self::calculateColumnWidth($font, $lineText, $rotation = 0, $defaultFont, $filterAdjustment);
}
return max($lineWidths); // width of longest line in cell
}
// Try to get the exact text width in pixels
$approximate = self::$autoSizeMethod === self::AUTOSIZE_METHOD_APPROX;
$columnWidth = 0;
if (!$approximate) {
try {
$columnWidthAdjust = ceil(
self::getTextWidthPixelsExact(
str_repeat('n', 1 * (($filterAdjustment ? 3 : 1) + ($indentAdjustment * 2))),
$font,
0
) * 1.07
);
// Width of text in pixels excl. padding
// and addition because Excel adds some padding, just use approx width of 'n' glyph
$columnWidth = self::getTextWidthPixelsExact($cellText, $font, $rotation) + (self::$paddingAmountExact ?? $columnWidthAdjust);
} catch (PhpSpreadsheetException) {
$approximate = true;
}
}
if ($approximate) {
$columnWidthAdjust = self::getTextWidthPixelsApprox(
str_repeat('n', 1 * (($filterAdjustment ? 3 : 1) + ($indentAdjustment * 2))),
$font,
0
);
// Width of text in pixels excl. padding, approximation
// and addition because Excel adds some padding, just use approx width of 'n' glyph
$columnWidth = self::getTextWidthPixelsApprox($cellText, $font, $rotation) + $columnWidthAdjust;
}
// Convert from pixel width to column width
$columnWidth = Drawing::pixelsToCellDimension((int) $columnWidth, $defaultFont ?? new FontStyle());
// Return
return round($columnWidth, 4);
}
/**
* Get GD text width in pixels for a string of text in a certain font at a certain rotation angle.
*/
public static function getTextWidthPixelsExact(string $text, FontStyle $font, int $rotation = 0): float
{
// font size should really be supplied in pixels in GD2,
// but since GD2 seems to assume 72dpi, pixels and points are the same
$fontFile = self::getTrueTypeFontFileFromFont($font);
$textBox = imagettfbbox($font->getSize() ?? 10.0, $rotation, $fontFile, $text);
if ($textBox === false) {
// @codeCoverageIgnoreStart
throw new PhpSpreadsheetException('imagettfbbox failed');
// @codeCoverageIgnoreEnd
}
// Get corners positions
/** @var int[] $textBox */
$lowerLeftCornerX = $textBox[0];
$lowerRightCornerX = $textBox[2];
$upperRightCornerX = $textBox[4];
$upperLeftCornerX = $textBox[6];
// Consider the rotation when calculating the width
return round(max($lowerRightCornerX - $upperLeftCornerX, $upperRightCornerX - $lowerLeftCornerX), 4);
}
/**
* Get approximate width in pixels for a string of text in a certain font at a certain rotation angle.
*
* @return int Text width in pixels (no padding added)
*/
public static function getTextWidthPixelsApprox(string $columnText, FontStyle $font, int $rotation = 0): int
{
$fontName = $font->getName();
$fontSize = $font->getSize();
// Calculate column width in pixels.
// We assume fixed glyph width, but count double for "fullwidth" characters.
// Result varies with font name and size.
switch ($fontName) {
case 'Arial':
// value 8 was set because of experience in different exports at Arial 10 font.
$columnWidth = (int) (8 * StringHelper::countCharactersDbcs($columnText));
$columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size
break;
case 'Verdana':
// value 8 was found via interpolation by inspecting real Excel files with Verdana 10 font.
$columnWidth = (int) (8 * StringHelper::countCharactersDbcs($columnText));
$columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size
break;
default:
// just assume Calibri
// value 8.26 was found via interpolation by inspecting real Excel files with Calibri 11 font.
$columnWidth = (int) (8.26 * StringHelper::countCharactersDbcs($columnText));
$columnWidth = $columnWidth * $fontSize / 11; // extrapolate from font size
break;
}
// Calculate approximate rotated column width
if ($rotation !== 0) {
if ($rotation == Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) {
// stacked text
$columnWidth = 4; // approximation
} else {
// rotated text
$columnWidth = $columnWidth * cos(deg2rad($rotation))
+ $fontSize * abs(sin(deg2rad($rotation))) / 5; // approximation
}
}
// pixel width is an integer
return (int) $columnWidth;
}
/**
* Calculate an (approximate) pixel size, based on a font points size.
*
* @param float|int $fontSizeInPoints Font size (in points)
*
* @return int Font size (in pixels)
*/
public static function fontSizeToPixels(float|int $fontSizeInPoints): int
{
return (int) ((4 / 3) * $fontSizeInPoints);
}
/**
* Calculate an (approximate) pixel size, based on inch size.
*
* @param float|int $sizeInInch Font size (in inch)
*
* @return float|int Size (in pixels)
*/
public static function inchSizeToPixels(int|float $sizeInInch): int|float
{
return $sizeInInch * 96;
}
/**
* Calculate an (approximate) pixel size, based on centimeter size.
*
* @param float|int $sizeInCm Font size (in centimeters)
*
* @return float Size (in pixels)
*/
public static function centimeterSizeToPixels(int|float $sizeInCm): float
{
return $sizeInCm * 37.795275591;
}
/**
* Returns the font path given the font.
*
* @return string Path to TrueType font file
*/
public static function getTrueTypeFontFileFromFont(FontStyle $font, bool $checkPath = true): string
{
if ($checkPath && (!file_exists(self::$trueTypeFontPath) || !is_dir(self::$trueTypeFontPath))) {
throw new PhpSpreadsheetException('Valid directory to TrueType Font files not specified');
}
$name = $font->getName();
$fontArray = array_merge(self::FONT_FILE_NAMES, self::$extraFontArray);
if (!isset($fontArray[$name])) {
throw new PhpSpreadsheetException('Unknown font name "' . $name . '". Cannot map to TrueType font file');
}
$bold = $font->getBold();
$italic = $font->getItalic();
$index = 'x';
if ($bold) {
$index .= 'b';
}
if ($italic) {
$index .= 'i';
}
$fontFile = $fontArray[$name][$index];
$separator = '';
if (mb_strlen(self::$trueTypeFontPath) > 1 && mb_substr(self::$trueTypeFontPath, -1) !== '/' && mb_substr(self::$trueTypeFontPath, -1) !== '\\') {
$separator = DIRECTORY_SEPARATOR;
}
$fontFileAbsolute = preg_match('~^([A-Za-z]:)?[/\\\]~', $fontFile) === 1;
if (!$fontFileAbsolute) {
$fontFile = self::findFontFile(self::$trueTypeFontPath, $fontFile) ?? self::$trueTypeFontPath . $separator . $fontFile;
}
// Check if file actually exists
if ($checkPath && !file_exists($fontFile) && !$fontFileAbsolute) {
$alternateName = $name;
if ($index !== 'x' && $fontArray[$name][$index] !== $fontArray[$name]['x']) {
// Bold but no italic:
// Comic Sans
// Tahoma
// Neither bold nor italic:
// Impact
// Lucida Console
// Lucida Sans Unicode
// Microsoft Sans Serif
// Symbol
if ($index === 'xb') {
$alternateName .= ' Bold';
} elseif ($index === 'xi') {
$alternateName .= ' Italic';
} elseif ($fontArray[$name]['xb'] === $fontArray[$name]['xbi']) {
$alternateName .= ' Bold';
} else {
$alternateName .= ' Bold Italic';
}
}
$fontFile = self::$trueTypeFontPath . $separator . $alternateName . '.ttf';
if (!file_exists($fontFile)) {
throw new PhpSpreadsheetException('TrueType Font file not found');
}
}
return $fontFile;
}
public const CHARSET_FROM_FONT_NAME = [
'EucrosiaUPC' => self::CHARSET_ANSI_THAI,
'Wingdings' => self::CHARSET_SYMBOL,
'Wingdings 2' => self::CHARSET_SYMBOL,
'Wingdings 3' => self::CHARSET_SYMBOL,
];
/**
* Returns the associated charset for the font name.
*
* @param string $fontName Font name
*
* @return int Character set code
*/
public static function getCharsetFromFontName(string $fontName): int
{
return self::CHARSET_FROM_FONT_NAME[$fontName] ?? self::CHARSET_ANSI_LATIN;
}
/**
* Get the effective column width for columns without a column dimension or column with width -1
* For example, for Calibri 11 this is 9.140625 (64 px).
*
* @param FontStyle $font The workbooks default font
* @param bool $returnAsPixels true = return column width in pixels, false = return in OOXML units
*
* @return ($returnAsPixels is true ? int : float) Column width
*/
public static function getDefaultColumnWidthByFont(FontStyle $font, bool $returnAsPixels = false): float|int
{
$size = $font->getSize();
$sizex = ($size !== null && $size == (int) $size) ? ((int) $size) : "$size";
if (isset(self::DEFAULT_COLUMN_WIDTHS[$font->getName()][$sizex])) {
// Exact width can be determined
$columnWidth = $returnAsPixels
? self::DEFAULT_COLUMN_WIDTHS[$font->getName()][$sizex]['px']
: self::DEFAULT_COLUMN_WIDTHS[$font->getName()][$sizex]['width'];
} else {
// We don't have data for this particular font and size, use approximation by
// extrapolating from Calibri 11
$columnWidth = $returnAsPixels
? self::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['px']
: self::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['width'];
$columnWidth = $columnWidth * $font->getSize() / 11;
// Round pixels to closest integer
if ($returnAsPixels) {
$columnWidth = (int) round($columnWidth);
}
}
return $columnWidth;
}
/**
* Get the effective row height for rows without a row dimension or rows with height -1
* For example, for Calibri 11 this is 15 points.
*
* @param FontStyle $font The workbooks default font
*
* @return float Row height in points
*/
public static function getDefaultRowHeightByFont(FontStyle $font): float
{
$name = $font->getName();
$size = $font->getSize();
$sizex = ($size !== null && $size == (int) $size) ? ((int) $size) : "$size";
if (isset(self::DEFAULT_COLUMN_WIDTHS[$name][$sizex])) {
$rowHeight = self::DEFAULT_COLUMN_WIDTHS[$name][$sizex]['height'];
} elseif ($name === 'Arial' || $name === 'Verdana') {
$rowHeight = self::DEFAULT_COLUMN_WIDTHS[$name][10]['height'] * $size / 10.0;
} else {
$rowHeight = self::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['height'] * $size / 11.0;
}
return $rowHeight;
}
private static function findFontFile(string $startDirectory, string $desiredFont): ?string
{
$fontPath = null;
if ($startDirectory === '') {
return null;
}
if (file_exists("$startDirectory/$desiredFont")) {
$fontPath = "$startDirectory/$desiredFont";
} else {
$iterations = 0;
$it = new RecursiveDirectoryIterator(
$startDirectory,
RecursiveDirectoryIterator::SKIP_DOTS
| RecursiveDirectoryIterator::FOLLOW_SYMLINKS
);
foreach (
new RecursiveIteratorIterator(
$it,
RecursiveIteratorIterator::LEAVES_ONLY,
RecursiveIteratorIterator::CATCH_GET_CHILD
) as $filex
) {
/** @var string */
$file = $filex;
if (basename($file) === $desiredFont) {
$fontPath = $file;
break;
}
++$iterations;
if ($iterations > 5000) {
// @codeCoverageIgnoreStart
break;
// @codeCoverageIgnoreEnd
}
}
}
return $fontPath;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Drawing.php | src/PhpSpreadsheet/Shared/Drawing.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
use SimpleXMLElement;
class Drawing
{
/**
* Convert pixels to EMU.
*
* @param int $pixelValue Value in pixels
*
* @return float|int Value in EMU
*/
public static function pixelsToEMU(int $pixelValue): int|float
{
return $pixelValue * 9525;
}
/**
* Convert EMU to pixels.
*
* @param int|SimpleXMLElement $emuValue Value in EMU
*
* @return int Value in pixels
*/
public static function EMUToPixels($emuValue): int
{
$emuValue = (int) $emuValue;
if ($emuValue != 0) {
return (int) round($emuValue / 9525);
}
return 0;
}
/**
* Convert pixels to column width. Exact algorithm not known.
* By inspection of a real Excel file using Calibri 11, one finds 1000px ~ 142.85546875
* This gives a conversion factor of 7. Also, we assume that pixels and font size are proportional.
*
* @param int $pixelValue Value in pixels
*
* @return float|int Value in cell dimension
*/
public static function pixelsToCellDimension(int $pixelValue, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont): int|float
{
// Font name and size
$name = $defaultFont->getName();
$size = $defaultFont->getSize();
$sizex = ($size !== null && $size == (int) $size) ? ((int) $size) : "$size";
if (isset(Font::DEFAULT_COLUMN_WIDTHS[$name][$sizex])) {
// Exact width can be determined
return $pixelValue * Font::DEFAULT_COLUMN_WIDTHS[$name][$sizex]['width']
/ Font::DEFAULT_COLUMN_WIDTHS[$name][$sizex]['px'];
}
// We don't have data for this particular font and size, use approximation by
// extrapolating from Calibri 11
return $pixelValue * 11 * Font::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['width']
/ Font::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['px'] / $size;
}
/**
* Convert column width from (intrinsic) Excel units to pixels.
*
* @param float $cellWidth Value in cell dimension
* @param \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont Default font of the workbook
*
* @return int Value in pixels
*/
public static function cellDimensionToPixels(float $cellWidth, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont): int
{
// Font name and size
$name = $defaultFont->getName();
$size = $defaultFont->getSize();
$sizex = ($size !== null && $size == (int) $size) ? ((int) $size) : "$size";
if (isset(Font::DEFAULT_COLUMN_WIDTHS[$name][$sizex])) {
// Exact width can be determined
$colWidth = $cellWidth * Font::DEFAULT_COLUMN_WIDTHS[$name][$sizex]['px']
/ Font::DEFAULT_COLUMN_WIDTHS[$name][$sizex]['width'];
} else {
// We don't have data for this particular font and size, use approximation by
// extrapolating from Calibri 11
$colWidth = $cellWidth * $size * Font::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['px']
/ Font::DEFAULT_COLUMN_WIDTHS['Calibri'][11]['width'] / 11;
}
// Round pixels to closest integer
$colWidth = (int) round($colWidth);
return $colWidth;
}
/**
* Convert pixels to points.
*
* @param int $pixelValue Value in pixels
*
* @return float Value in points
*/
public static function pixelsToPoints(int $pixelValue): float
{
return $pixelValue * 0.75;
}
/**
* Convert points to pixels.
*
* @param float|int $pointValue Value in points
*
* @return int Value in pixels
*/
public static function pointsToPixels($pointValue): int
{
return (int) ceil($pointValue / 0.75);
}
/**
* Convert degrees to angle.
*
* @param int $degrees Degrees
*
* @return int Angle
*/
public static function degreesToAngle(int $degrees): int
{
return (int) round($degrees * 60000);
}
/**
* Convert angle to degrees.
*
* @param int|SimpleXMLElement $angle Angle
*
* @return int Degrees
*/
public static function angleToDegrees($angle): int
{
$angle = (int) $angle;
if ($angle != 0) {
return (int) round($angle / 60000);
}
return 0;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/XMLWriter.php | src/PhpSpreadsheet/Shared/XMLWriter.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
class XMLWriter extends \XMLWriter
{
public static bool $debugEnabled = false;
/** Temporary storage method */
const STORAGE_MEMORY = 1;
const STORAGE_DISK = 2;
/**
* Temporary filename.
*/
private string $tempFileName = '';
/**
* Create a new XMLWriter instance.
*
* @param int $temporaryStorage Temporary storage location
* @param ?string $temporaryStorageFolder Temporary storage folder
*/
public function __construct(int $temporaryStorage = self::STORAGE_MEMORY, ?string $temporaryStorageFolder = null)
{
// Open temporary storage
if ($temporaryStorage == self::STORAGE_MEMORY) {
$this->openMemory();
} else {
// Create temporary filename
if ($temporaryStorageFolder === null) {
$temporaryStorageFolder = File::sysGetTempDir();
}
$this->tempFileName = (string) @tempnam($temporaryStorageFolder, 'xml');
// Open storage
if (empty($this->tempFileName) || $this->openUri($this->tempFileName) === false) {
// Fallback to memory...
$this->openMemory();
if ($this->tempFileName != '') {
@unlink($this->tempFileName);
}
$this->tempFileName = '';
}
}
// Set default values
if (self::$debugEnabled) {
$this->setIndent(true);
}
}
/**
* Destructor.
*/
public function __destruct()
{
// Unlink temporary files
// There is nothing reasonable to do if unlink fails.
if ($this->tempFileName != '') {
@unlink($this->tempFileName);
}
}
/** @param mixed[] $data */
public function __unserialize(array $data): void
{
$this->tempFileName = '';
throw new SpreadsheetException('Unserialize not permitted');
}
/**
* Get written data.
*/
public function getData(): string
{
if ($this->tempFileName == '') {
return $this->outputMemory(true);
}
$this->flush();
return file_get_contents($this->tempFileName) ?: '';
}
/**
* Wrapper method for writeRaw.
*
* @param null|string|string[] $rawTextData
*/
public function writeRawData($rawTextData): bool
{
if (is_array($rawTextData)) {
$rawTextData = implode("\n", $rawTextData);
}
return $this->text($rawTextData ?? '');
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/TimeZone.php | src/PhpSpreadsheet/Shared/TimeZone.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
use DateTimeZone;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
class TimeZone
{
/**
* Default Timezone used for date/time conversions.
*/
protected static string $timezone = 'UTC';
/**
* Validate a Timezone name.
*
* @param string $timezoneName Time zone (e.g. 'Europe/London')
*
* @return bool Success or failure
*/
private static function validateTimeZone(string $timezoneName): bool
{
return in_array($timezoneName, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC), true);
}
/**
* Set the Default Timezone used for date/time conversions.
*
* @param string $timezoneName Time zone (e.g. 'Europe/London')
*
* @return bool Success or failure
*/
public static function setTimeZone(string $timezoneName): bool
{
if (self::validateTimeZone($timezoneName)) {
self::$timezone = $timezoneName;
return true;
}
return false;
}
/**
* Return the Default Timezone used for date/time conversions.
*
* @return string Timezone (e.g. 'Europe/London')
*/
public static function getTimeZone(): string
{
return self::$timezone;
}
/**
* Return the Timezone offset used for date/time conversions to/from UST
* This requires both the timezone and the calculated date/time to allow for local DST.
*
* @param ?string $timezoneName The timezone for finding the adjustment to UST
* @param float|int $timestamp PHP date/time value
*
* @return int Number of seconds for timezone adjustment
*/
public static function getTimeZoneAdjustment(?string $timezoneName, $timestamp): int
{
$timezoneName = $timezoneName ?? self::$timezone;
$dtobj = Date::dateTimeFromTimestamp("$timestamp");
if (!self::validateTimeZone($timezoneName)) {
throw new PhpSpreadsheetException("Invalid timezone $timezoneName");
}
$dtobj->setTimeZone(new DateTimeZone($timezoneName));
return $dtobj->getOffset();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/OLE.php | src/PhpSpreadsheet/Shared/OLE.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
// vim: set expandtab tabstop=4 shiftwidth=4:
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2002 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Xavier Noguer <xnoguer@php.net> |
// | Based on OLE::Storage_Lite by Kawai, Takanori |
// +----------------------------------------------------------------------+
//
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
use PhpOffice\PhpSpreadsheet\Shared\OLE\ChainedBlockStream;
use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\Root;
/*
* Array for storing OLE instances that are accessed from
* OLE_ChainedBlockStream::stream_open().
*
* @var array
*/
$GLOBALS['_OLE_INSTANCES'] = [];
/**
* OLE package base class.
*
* @author Xavier Noguer <xnoguer@php.net>
* @author Christian Schmidt <schmidt@php.net>
*/
class OLE
{
const OLE_PPS_TYPE_ROOT = 5;
const OLE_PPS_TYPE_DIR = 1;
const OLE_PPS_TYPE_FILE = 2;
const OLE_DATA_SIZE_SMALL = 0x1000;
const OLE_LONG_INT_SIZE = 4;
const OLE_PPS_SIZE = 0x80;
/**
* The file handle for reading an OLE container.
*
* @var resource
*/
public $_file_handle;
/**
* Array of PPS's found on the OLE container.
*
* @var array<OLE\PPS|OLE\PPS\File|Root>
*/
public array $_list = [];
/**
* Root directory of OLE container.
*/
public Root $root;
/**
* Big Block Allocation Table.
*
* @var mixed[] (blockId => nextBlockId)
*/
public array $bbat;
/**
* Short Block Allocation Table.
*
* @var mixed[] (blockId => nextBlockId)
*/
public array $sbat;
/**
* Size of big blocks. This is usually 512.
*
* @var int<1, max> number of octets per block
*/
public int $bigBlockSize;
/**
* Size of small blocks. This is usually 64.
*
* @var int number of octets per block
*/
public int $smallBlockSize;
/**
* Threshold for big blocks.
*/
public int $bigBlockThreshold;
/**
* Reads an OLE container from the contents of the file given.
*
* @acces public
*
* @return bool true on success, PEAR_Error on failure
*/
public function read(string $filename): bool
{
$fh = @fopen($filename, 'rb');
if ($fh === false) {
throw new ReaderException("Can't open file $filename");
}
$this->_file_handle = $fh;
$signature = fread($fh, 8);
if ("\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" != $signature) {
throw new ReaderException("File doesn't seem to be an OLE container.");
}
fseek($fh, 28);
if (fread($fh, 2) != "\xFE\xFF") {
// This shouldn't be a problem in practice
throw new ReaderException('Only Little-Endian encoding is supported.');
}
// Size of blocks and short blocks in bytes
/** @var int<1, max> */
$temp = 2 ** self::readInt2($fh);
$this->bigBlockSize = $temp;
$this->smallBlockSize = 2 ** self::readInt2($fh);
// Skip UID, revision number and version number
fseek($fh, 44);
// Number of blocks in Big Block Allocation Table
$bbatBlockCount = self::readInt4($fh);
// Root chain 1st block
$directoryFirstBlockId = self::readInt4($fh);
// Skip unused bytes
fseek($fh, 56);
// Streams shorter than this are stored using small blocks
$this->bigBlockThreshold = self::readInt4($fh);
// Block id of first sector in Short Block Allocation Table
$sbatFirstBlockId = self::readInt4($fh);
// Number of blocks in Short Block Allocation Table
$sbbatBlockCount = self::readInt4($fh);
// Block id of first sector in Master Block Allocation Table
$mbatFirstBlockId = self::readInt4($fh);
// Number of blocks in Master Block Allocation Table
$mbbatBlockCount = self::readInt4($fh);
$this->bbat = [];
// Remaining 4 * 109 bytes of current block is beginning of Master
// Block Allocation Table
$mbatBlocks = [];
for ($i = 0; $i < 109; ++$i) {
$mbatBlocks[] = self::readInt4($fh);
}
// Read rest of Master Block Allocation Table (if any is left)
$pos = $this->getBlockOffset($mbatFirstBlockId);
for ($i = 0; $i < $mbbatBlockCount; ++$i) {
fseek($fh, $pos);
for ($j = 0; $j < $this->bigBlockSize / 4 - 1; ++$j) {
$mbatBlocks[] = self::readInt4($fh);
}
// Last block id in each block points to next block
$pos = $this->getBlockOffset(self::readInt4($fh));
}
// Read Big Block Allocation Table according to chain specified by $mbatBlocks
for ($i = 0; $i < $bbatBlockCount; ++$i) {
$pos = $this->getBlockOffset($mbatBlocks[$i]);
fseek($fh, $pos);
for ($j = 0; $j < $this->bigBlockSize / 4; ++$j) {
$this->bbat[] = self::readInt4($fh);
}
}
// Read short block allocation table (SBAT)
$this->sbat = [];
$shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4;
$sbatFh = $this->getStream($sbatFirstBlockId);
for ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) {
$this->sbat[$blockId] = self::readInt4($sbatFh);
}
fclose($sbatFh);
$this->readPpsWks($directoryFirstBlockId);
return true;
}
/**
* @param int $blockId byte offset from beginning of file
*/
public function getBlockOffset(int $blockId): int
{
return 512 + $blockId * $this->bigBlockSize;
}
/**
* Returns a stream for use with fread() etc. External callers should
* use \PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\File::getStream().
*
* @param int|OLE\PPS $blockIdOrPps block id or PPS
*
* @return resource read-only stream
*/
public function getStream($blockIdOrPps)
{
static $isRegistered = false;
if (!$isRegistered) {
stream_wrapper_register('ole-chainedblockstream', ChainedBlockStream::class);
$isRegistered = true;
}
// Store current instance in global array, so that it can be accessed
// in OLE_ChainedBlockStream::stream_open().
// Object is removed from self::$instances in OLE_Stream::close().
$GLOBALS['_OLE_INSTANCES'][] = $this; //* @phpstan-ignore-line
$keys = array_keys($GLOBALS['_OLE_INSTANCES']); //* @phpstan-ignore-line
$instanceId = end($keys);
$path = 'ole-chainedblockstream://oleInstanceId=' . $instanceId;
if ($blockIdOrPps instanceof OLE\PPS) {
$path .= '&blockId=' . $blockIdOrPps->startBlock;
$path .= '&size=' . $blockIdOrPps->Size;
} else {
$path .= '&blockId=' . $blockIdOrPps;
}
$resource = fopen($path, 'rb') ?: throw new Exception("Unable to open stream $path");
return $resource;
}
/**
* Reads a signed char.
*
* @param resource $fileHandle file handle
*/
private static function readInt1($fileHandle): int
{
[, $tmp] = unpack('c', fread($fileHandle, 1) ?: '') ?: [0, 0];
/** @var int $tmp */
return $tmp;
}
/**
* Reads an unsigned short (2 octets).
*
* @param resource $fileHandle file handle
*/
private static function readInt2($fileHandle): int
{
[, $tmp] = unpack('v', fread($fileHandle, 2) ?: '') ?: [0, 0];
/** @var int $tmp */
return $tmp;
}
private const SIGNED_4OCTET_LIMIT = 2147483648;
private const SIGNED_4OCTET_SUBTRACT = 2 * self::SIGNED_4OCTET_LIMIT;
/**
* Reads long (4 octets), interpreted as if signed on 32-bit system.
*
* @param resource $fileHandle file handle
*/
private static function readInt4($fileHandle): int
{
[, $tmp] = unpack('V', fread($fileHandle, 4) ?: '') ?: [0, 0];
/** @var int $tmp */
if ($tmp >= self::SIGNED_4OCTET_LIMIT) {
$tmp -= self::SIGNED_4OCTET_SUBTRACT;
}
return $tmp;
}
/**
* Gets information about all PPS's on the OLE container from the PPS WK's
* creates an OLE_PPS object for each one.
*
* @param int $blockId the block id of the first block
*
* @return bool true on success, PEAR_Error on failure
*/
public function readPpsWks(int $blockId): bool
{
$fh = $this->getStream($blockId);
for ($pos = 0; true; $pos += 128) {
fseek($fh, $pos, SEEK_SET);
$nameUtf16 = (string) fread($fh, 64);
$nameLength = self::readInt2($fh);
$nameUtf16 = substr($nameUtf16, 0, $nameLength - 2);
// Simple conversion from UTF-16LE to ISO-8859-1
$name = str_replace("\x00", '', $nameUtf16);
$type = self::readInt1($fh);
switch ($type) {
case self::OLE_PPS_TYPE_ROOT:
$pps = new Root(null, null, []);
$this->root = $pps;
break;
case self::OLE_PPS_TYPE_DIR:
$pps = new OLE\PPS(null, null, null, null, null, null, null, null, null, []);
break;
case self::OLE_PPS_TYPE_FILE:
$pps = new OLE\PPS\File($name);
break;
default:
throw new Exception('Unsupported PPS type');
}
fseek($fh, 1, SEEK_CUR);
$pps->Type = $type;
$pps->Name = $name;
$pps->PrevPps = self::readInt4($fh);
$pps->NextPps = self::readInt4($fh);
$pps->DirPps = self::readInt4($fh);
fseek($fh, 20, SEEK_CUR);
$pps->Time1st = self::OLE2LocalDate((string) fread($fh, 8));
$pps->Time2nd = self::OLE2LocalDate((string) fread($fh, 8));
$pps->startBlock = self::readInt4($fh);
$pps->Size = self::readInt4($fh);
$pps->No = count($this->_list);
$this->_list[] = $pps;
// check if the PPS tree (starting from root) is complete
if (isset($this->root) && $this->ppsTreeComplete($this->root->No)) {
break;
}
}
fclose($fh);
// Initialize $pps->children on directories
foreach ($this->_list as $pps) {
if ($pps->Type == self::OLE_PPS_TYPE_DIR || $pps->Type == self::OLE_PPS_TYPE_ROOT) {
$nos = [$pps->DirPps];
$pps->children = [];
while (!empty($nos)) {
$no = array_pop($nos);
if ($no != -1) {
$childPps = $this->_list[$no];
$nos[] = $childPps->PrevPps;
$nos[] = $childPps->NextPps;
$pps->children[] = $childPps;
}
}
}
}
return true;
}
/**
* It checks whether the PPS tree is complete (all PPS's read)
* starting with the given PPS (not necessarily root).
*
* @param int $index The index of the PPS from which we are checking
*
* @return bool Whether the PPS tree for the given PPS is complete
*/
private function ppsTreeComplete(int $index): bool
{
if (!isset($this->_list[$index])) {
return false;
}
$pps = $this->_list[$index];
return
($pps->PrevPps == -1
|| $this->ppsTreeComplete($pps->PrevPps))
&& ($pps->NextPps == -1
|| $this->ppsTreeComplete($pps->NextPps))
&& ($pps->DirPps == -1
|| $this->ppsTreeComplete($pps->DirPps));
}
/**
* Checks whether a PPS is a File PPS or not.
* If there is no PPS for the index given, it will return false.
*
* @param int $index The index for the PPS
*
* @return bool true if it's a File PPS, false otherwise
*/
public function isFile(int $index): bool
{
if (isset($this->_list[$index])) {
return $this->_list[$index]->Type == self::OLE_PPS_TYPE_FILE;
}
return false;
}
/**
* Checks whether a PPS is a Root PPS or not.
* If there is no PPS for the index given, it will return false.
*
* @param int $index the index for the PPS
*
* @return bool true if it's a Root PPS, false otherwise
*/
public function isRoot(int $index): bool
{
if (isset($this->_list[$index])) {
return $this->_list[$index]->Type == self::OLE_PPS_TYPE_ROOT;
}
return false;
}
/**
* Gives the total number of PPS's found in the OLE container.
*
* @return int The total number of PPS's found in the OLE container
*/
public function ppsTotal(): int
{
return count($this->_list);
}
/**
* Gets data from a PPS
* If there is no PPS for the index given, it will return an empty string.
*
* @param int $index The index for the PPS
* @param int $position The position from which to start reading
* (relative to the PPS)
* @param int $length The amount of bytes to read (at most)
*
* @return string The binary string containing the data requested
*
* @see OLE_PPS_File::getStream()
*/
public function getData(int $index, int $position, int $length): string
{
// if position is not valid return empty string
if (!isset($this->_list[$index]) || ($position >= $this->_list[$index]->Size) || ($position < 0)) {
return '';
}
$fh = $this->getStream($this->_list[$index]);
$data = (string) stream_get_contents($fh, $length, $position);
fclose($fh);
return $data;
}
/**
* Gets the data length from a PPS
* If there is no PPS for the index given, it will return 0.
*
* @param int $index The index for the PPS
*
* @return int The amount of bytes in data the PPS has
*/
public function getDataLength(int $index): int
{
if (isset($this->_list[$index])) {
return $this->_list[$index]->Size;
}
return 0;
}
/**
* Utility function to transform ASCII text to Unicode.
*
* @param string $ascii The ASCII string to transform
*
* @return string The string in Unicode
*/
public static function ascToUcs(string $ascii): string
{
$rawname = '';
$iMax = strlen($ascii);
for ($i = 0; $i < $iMax; ++$i) {
$rawname .= $ascii[$i]
. "\x00";
}
return $rawname;
}
/**
* Utility function
* Returns a string for the OLE container with the date given.
*
* @param float|int $date A timestamp
*
* @return string The string for the OLE container
*/
public static function localDateToOLE($date): string
{
if (!$date) {
return "\x00\x00\x00\x00\x00\x00\x00\x00";
}
$dateTime = Date::dateTimeFromTimestamp("$date");
// days from 1-1-1601 until the beginning of UNIX era
$days = 134774;
// calculate seconds
$big_date = $days * 24 * 3600 + (float) $dateTime->format('U');
// multiply just to make MS happy
$big_date *= 10000000;
// Make HEX string
$res = '';
$factor = 2 ** 56;
while ($factor >= 1) {
$hex = (int) floor($big_date / $factor);
$res = pack('c', $hex) . $res;
$big_date = fmod($big_date, $factor);
$factor /= 256;
}
return $res;
}
/**
* Returns a timestamp from an OLE container's date.
*
* @param string $oleTimestamp A binary string with the encoded date
*
* @return float|int The Unix timestamp corresponding to the string
*/
public static function OLE2LocalDate(string $oleTimestamp)
{
if (strlen($oleTimestamp) != 8) {
throw new ReaderException('Expecting 8 byte string');
}
// convert to units of 100 ns since 1601:
/** @var int[] */
$unpackedTimestamp = unpack('v4', $oleTimestamp) ?: [];
$timestampHigh = (float) $unpackedTimestamp[4] * 65536 + (float) $unpackedTimestamp[3];
$timestampLow = (float) $unpackedTimestamp[2] * 65536 + (float) $unpackedTimestamp[1];
// translate to seconds since 1601:
$timestampHigh /= 10000000;
$timestampLow /= 10000000;
// days from 1601 to 1970:
$days = 134774;
// translate to seconds since 1970:
$unixTimestamp = floor(65536.0 * 65536.0 * $timestampHigh + $timestampLow - $days * 24 * 3600 + 0.5);
return IntOrFloat::evaluate($unixTimestamp);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Escher.php | src/PhpSpreadsheet/Shared/Escher.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
class Escher
{
/**
* Drawing Group Container.
*/
private ?Escher\DggContainer $dggContainer = null;
/**
* Drawing Container.
*/
private ?Escher\DgContainer $dgContainer = null;
/**
* Get Drawing Group Container.
*/
public function getDggContainer(): ?Escher\DggContainer
{
return $this->dggContainer;
}
/**
* Get Drawing Group Container.
*/
public function getDggContainerOrThrow(): Escher\DggContainer
{
return $this->dggContainer ?? throw new SpreadsheetException('dggContainer is unexpectedly null');
}
/**
* Set Drawing Group Container.
*/
public function setDggContainer(Escher\DggContainer $dggContainer): Escher\DggContainer
{
return $this->dggContainer = $dggContainer;
}
/**
* Get Drawing Container.
*/
public function getDgContainer(): ?Escher\DgContainer
{
return $this->dgContainer;
}
/**
* Get Drawing Container.
*/
public function getDgContainerOrThrow(): Escher\DgContainer
{
return $this->dgContainer ?? throw new SpreadsheetException('dgContainer is unexpectedly null');
}
/**
* Set Drawing Container.
*/
public function setDgContainer(Escher\DgContainer $dgContainer): Escher\DgContainer
{
return $this->dgContainer = $dgContainer;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Date.php | src/PhpSpreadsheet/Shared/Date.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
use DateTime;
use DateTimeInterface;
use DateTimeZone;
use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Throwable;
class Date
{
/** constants */
const CALENDAR_WINDOWS_1900 = 1900; // Base date of 1st Jan 1900 = 1.0
const CALENDAR_MAC_1904 = 1904; // Base date of 2nd Jan 1904 = 1.0
/**
* Names of the months of the year, indexed by shortname
* Planned usage for locale settings.
*
* @var string[]
*/
public static array $monthNames = [
'Jan' => 'January',
'Feb' => 'February',
'Mar' => 'March',
'Apr' => 'April',
'May' => 'May',
'Jun' => 'June',
'Jul' => 'July',
'Aug' => 'August',
'Sep' => 'September',
'Oct' => 'October',
'Nov' => 'November',
'Dec' => 'December',
];
/**
* @var string[]
*/
public static array $numberSuffixes = [
'st',
'nd',
'rd',
'th',
];
/**
* Base calendar year to use for calculations
* Value is either CALENDAR_WINDOWS_1900 (1900) or CALENDAR_MAC_1904 (1904).
*/
protected static int $excelCalendar = self::CALENDAR_WINDOWS_1900;
/**
* Default timezone to use for DateTime objects.
*/
protected static ?DateTimeZone $defaultTimeZone = null;
/**
* Set the Excel calendar (Windows 1900 or Mac 1904).
*
* @param ?int $baseYear Excel base date (1900 or 1904)
*
* @return bool Success or failure
*/
public static function setExcelCalendar(?int $baseYear): bool
{
if (
($baseYear === self::CALENDAR_WINDOWS_1900)
|| ($baseYear === self::CALENDAR_MAC_1904)
) {
self::$excelCalendar = $baseYear;
return true;
}
return false;
}
/**
* Return the Excel calendar (Windows 1900 or Mac 1904).
*
* @return int Excel base date (1900 or 1904)
*/
public static function getExcelCalendar(): int
{
return self::$excelCalendar;
}
/**
* Set the Default timezone to use for dates.
*
* @param null|DateTimeZone|string $timeZone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions
*
* @return bool Success or failure
*/
public static function setDefaultTimezone($timeZone): bool
{
try {
$timeZone = self::validateTimeZone($timeZone);
self::$defaultTimeZone = $timeZone;
$retval = true;
} catch (PhpSpreadsheetException) {
$retval = false;
}
return $retval;
}
/**
* Return the Default timezone, or UTC if default not set.
*/
public static function getDefaultTimezone(): DateTimeZone
{
return self::$defaultTimeZone ?? new DateTimeZone('UTC');
}
/**
* Return the Default timezone, or local timezone if default is not set.
*/
public static function getDefaultOrLocalTimezone(): DateTimeZone
{
return self::$defaultTimeZone ?? new DateTimeZone(date_default_timezone_get());
}
/**
* Return the Default timezone even if null.
*/
public static function getDefaultTimezoneOrNull(): ?DateTimeZone
{
return self::$defaultTimeZone;
}
/**
* Validate a timezone.
*
* @param null|DateTimeZone|string $timeZone The timezone to validate, either as a timezone string or object
*
* @return ?DateTimeZone The timezone as a timezone object
*/
private static function validateTimeZone($timeZone): ?DateTimeZone
{
if ($timeZone instanceof DateTimeZone || $timeZone === null) {
return $timeZone;
}
if (in_array($timeZone, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC))) {
return new DateTimeZone($timeZone);
}
throw new PhpSpreadsheetException('Invalid timezone');
}
/**
* @param mixed $value Converts a date/time in ISO-8601 standard format date string to an Excel
* serialized timestamp.
* See https://en.wikipedia.org/wiki/ISO_8601 for details of the ISO-8601 standard format.
*/
public static function convertIsoDate(mixed $value): float|int
{
if (!is_string($value)) {
throw new Exception('Non-string value supplied for Iso Date conversion');
}
$date = new DateTime($value);
$dateErrors = DateTime::getLastErrors();
if (is_array($dateErrors) && ($dateErrors['warning_count'] > 0 || $dateErrors['error_count'] > 0)) {
throw new Exception("Invalid string $value supplied for datatype Date");
}
$newValue = self::dateTimeToExcel($date);
if (preg_match('/^\s*\d?\d:\d\d(:\d\d([.]\d+)?)?\s*(am|pm)?\s*$/i', $value) == 1) {
$newValue = fmod($newValue, 1.0);
}
return $newValue;
}
/**
* Convert a MS serialized datetime value from Excel to a PHP Date/Time object.
*
* @param float|int $excelTimestamp MS Excel serialized date/time value
* @param null|DateTimeZone|string $timeZone The timezone to assume for the Excel timestamp,
* if you don't want to treat it as a UTC value
* Use the default (UTC) unless you absolutely need a conversion
*
* @return DateTime PHP date/time object
*/
public static function excelToDateTimeObject(float|int $excelTimestamp, null|DateTimeZone|string $timeZone = null): DateTime
{
$timeZone = ($timeZone === null) ? self::getDefaultTimezone() : self::validateTimeZone($timeZone);
if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) {
if ($excelTimestamp < 1 && self::$excelCalendar === self::CALENDAR_WINDOWS_1900) {
// Unix timestamp base date
$baseDate = new DateTime('1970-01-01', $timeZone);
} else {
// MS Excel calendar base dates
if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) {
// Allow adjustment for 1900 Leap Year in MS Excel
$baseDate = ($excelTimestamp < 60) ? new DateTime('1899-12-31', $timeZone) : new DateTime('1899-12-30', $timeZone);
} else {
$baseDate = new DateTime('1904-01-01', $timeZone);
}
}
} else {
$baseDate = new DateTime('1899-12-30', $timeZone);
}
if (is_int($excelTimestamp)) {
if ($excelTimestamp >= 0) {
return $baseDate->modify("+ $excelTimestamp days");
}
return $baseDate->modify("$excelTimestamp days");
}
$days = floor($excelTimestamp);
$partDay = $excelTimestamp - $days;
$hms = 86400 * $partDay;
$microseconds = (int) round(fmod($hms, 1) * 1000000);
$hms = (int) floor($hms);
$hours = intdiv($hms, 3600);
$hms -= $hours * 3600;
$minutes = intdiv($hms, 60);
$seconds = $hms % 60;
if ($days >= 0) {
$days = '+' . $days;
}
$interval = $days . ' days';
return $baseDate->modify($interval)
->setTime($hours, $minutes, $seconds, $microseconds);
}
/**
* Convert a MS serialized datetime value from Excel to a unix timestamp.
* The use of Unix timestamps, and therefore this function, is discouraged.
* They are not Y2038-safe on a 32-bit system, and have no timezone info.
*
* @param float|int $excelTimestamp MS Excel serialized date/time value
* @param null|DateTimeZone|string $timeZone The timezone to assume for the Excel timestamp,
* if you don't want to treat it as a UTC value
* Use the default (UTC) unless you absolutely need a conversion
*
* @return int Unix timetamp for this date/time
*/
public static function excelToTimestamp($excelTimestamp, $timeZone = null): int
{
$dto = self::excelToDateTimeObject($excelTimestamp, $timeZone);
self::roundMicroseconds($dto);
return (int) $dto->format('U');
}
/**
* Convert a date from PHP to an MS Excel serialized date/time value.
*
* @param mixed $dateValue PHP DateTime object or a string - Unix timestamp is also permitted, but discouraged;
* not Y2038-safe on a 32-bit system, and no timezone info
*
* @return false|float Excel date/time value
* or boolean FALSE on failure
*/
public static function PHPToExcel(mixed $dateValue)
{
if ((is_object($dateValue)) && ($dateValue instanceof DateTimeInterface)) {
return self::dateTimeToExcel($dateValue);
} elseif (is_numeric($dateValue)) {
return self::timestampToExcel($dateValue);
} elseif (is_string($dateValue)) {
return self::stringToExcel($dateValue);
}
return false;
}
/**
* Convert a PHP DateTime object to an MS Excel serialized date/time value.
*
* @param DateTimeInterface $dateValue PHP DateTime object
*
* @return float MS Excel serialized date/time value
*/
public static function dateTimeToExcel(DateTimeInterface $dateValue): float
{
$seconds = (float) sprintf('%d.%06d', $dateValue->format('s'), $dateValue->format('u'));
return self::formattedPHPToExcel(
(int) $dateValue->format('Y'),
(int) $dateValue->format('m'),
(int) $dateValue->format('d'),
(int) $dateValue->format('H'),
(int) $dateValue->format('i'),
$seconds
);
}
/**
* Convert a Unix timestamp to an MS Excel serialized date/time value.
* The use of Unix timestamps, and therefore this function, is discouraged.
* They are not Y2038-safe on a 32-bit system, and have no timezone info.
*
* @param float|int|string $unixTimestamp Unix Timestamp
*
* @return false|float MS Excel serialized date/time value
*/
public static function timestampToExcel($unixTimestamp): bool|float
{
if (!is_numeric($unixTimestamp)) {
return false;
}
return self::dateTimeToExcel(new DateTime('@' . $unixTimestamp));
}
/**
* formattedPHPToExcel.
*
* @return float Excel date/time value
*/
public static function formattedPHPToExcel(int $year, int $month, int $day, int $hours = 0, int $minutes = 0, float|int $seconds = 0): float
{
if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) {
//
// Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel
// This affects every date following 28th February 1900
//
$excel1900isLeapYear = true;
if (($year == 1900) && ($month <= 2)) {
$excel1900isLeapYear = false;
}
$myexcelBaseDate = 2415020;
} else {
$myexcelBaseDate = 2416481;
$excel1900isLeapYear = false;
}
// Julian base date Adjustment
if ($month > 2) {
$month -= 3;
} else {
$month += 9;
--$year;
}
// Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0)
$century = (int) substr((string) $year, 0, 2);
$decade = (int) substr((string) $year, 2, 2);
$excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myexcelBaseDate + $excel1900isLeapYear;
$excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
return (float) $excelDate + $excelTime;
}
/**
* Is a given cell a date/time?
*/
public static function isDateTime(Cell $cell, mixed $value = null, bool $dateWithoutTimeOkay = true): bool
{
$result = false;
$worksheet = $cell->getWorksheetOrNull();
$spreadsheet = ($worksheet === null) ? null : $worksheet->getParent();
if ($worksheet !== null && $spreadsheet !== null) {
$index = $spreadsheet->getActiveSheetIndex();
$selected = $worksheet->getSelectedCells();
try {
if ($value === null) {
$value = Functions::flattenSingleValue(
$cell->getCalculatedValue()
);
}
if (is_numeric($value)) {
$result = self::isDateTimeFormat(
$worksheet->getStyle(
$cell->getCoordinate()
)->getNumberFormat(),
$dateWithoutTimeOkay
);
/** @var float|int $value */
self::excelToDateTimeObject($value);
}
} catch (Throwable) {
$result = false;
}
$worksheet->setSelectedCells($selected);
$spreadsheet->setActiveSheetIndex($index);
}
return $result;
}
/**
* Is a given NumberFormat code a date/time format code?
*/
public static function isDateTimeFormat(NumberFormat $excelFormatCode, bool $dateWithoutTimeOkay = true): bool
{
return self::isDateTimeFormatCode((string) $excelFormatCode->getFormatCode(), $dateWithoutTimeOkay);
}
private const POSSIBLE_DATETIME_FORMAT_CHARACTERS = 'eymdHs';
private const POSSIBLE_TIME_FORMAT_CHARACTERS = 'Hs'; // note - no 'm' due to ambiguity
/**
* Is a given number format code a date/time?
*/
public static function isDateTimeFormatCode(string $excelFormatCode, bool $dateWithoutTimeOkay = true): bool
{
if (strtolower($excelFormatCode) === strtolower(NumberFormat::FORMAT_GENERAL)) {
// "General" contains an epoch letter 'e', so we trap for it explicitly here (case-insensitive check)
return false;
}
if (preg_match('/[0#]E[+-]0/i', $excelFormatCode)) {
// Scientific format
return false;
}
// Switch on formatcode
$excelFormatCode = (string) NumberFormat::convertSystemFormats($excelFormatCode);
if (in_array($excelFormatCode, NumberFormat::DATE_TIME_OR_DATETIME_ARRAY, true)) {
return $dateWithoutTimeOkay || in_array($excelFormatCode, NumberFormat::TIME_OR_DATETIME_ARRAY);
}
// Typically number, currency or accounting (or occasionally fraction) formats
if ((str_starts_with($excelFormatCode, '_')) || (str_starts_with($excelFormatCode, '0 '))) {
return false;
}
// Some "special formats" provided in German Excel versions were detected as date time value,
// so filter them out here - "\C\H\-00000" (Switzerland) and "\D-00000" (Germany).
if (str_contains($excelFormatCode, '-00000')) {
return false;
}
$possibleFormatCharacters = $dateWithoutTimeOkay ? self::POSSIBLE_DATETIME_FORMAT_CHARACTERS : self::POSSIBLE_TIME_FORMAT_CHARACTERS;
// Try checking for any of the date formatting characters that don't appear within square braces
if (preg_match('/(^|\])[^\[]*[' . $possibleFormatCharacters . ']/i', $excelFormatCode)) {
// We might also have a format mask containing quoted strings...
// we don't want to test for any of our characters within the quoted blocks
if (str_contains($excelFormatCode, '"')) {
$segMatcher = false;
foreach (explode('"', $excelFormatCode) as $subVal) {
// Only test in alternate array entries (the non-quoted blocks)
$segMatcher = $segMatcher === false;
if (
$segMatcher
&& (preg_match('/(^|\])[^\[]*[' . $possibleFormatCharacters . ']/i', $subVal))
) {
return true;
}
}
return false;
}
return true;
}
// No date...
return false;
}
/**
* Convert a date/time string to Excel time.
*
* @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10'
*
* @return false|float Excel date/time serial value
*/
public static function stringToExcel(string $dateValue): bool|float
{
if (strlen($dateValue) < 2) {
return false;
}
if (!preg_match('/^(\d{1,4}[ \.\/\-][A-Z]{3,9}([ \.\/\-]\d{1,4})?|[A-Z]{3,9}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?|\d{1,4}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?)( \d{1,2}:\d{1,2}(:\d{1,2}([.]\d+)?)?)?$/iu', $dateValue)) {
return false;
}
$dateValueNew = DateTimeExcel\DateValue::fromString($dateValue);
if (!is_float($dateValueNew)) {
return false;
}
if (str_contains($dateValue, ':')) {
$timeValue = DateTimeExcel\TimeValue::fromString($dateValue);
if (!is_float($timeValue)) {
return false;
}
$dateValueNew += $timeValue;
}
return $dateValueNew;
}
/**
* Converts a month name (either a long or a short name) to a month number.
*
* @param string $monthName Month name or abbreviation
*
* @return int|string Month number (1 - 12), or the original string argument if it isn't a valid month name
*/
public static function monthStringToNumber(string $monthName)
{
$monthIndex = 1;
foreach (self::$monthNames as $shortMonthName => $longMonthName) {
if (($monthName === $longMonthName) || ($monthName === $shortMonthName)) {
return $monthIndex;
}
++$monthIndex;
}
return $monthName;
}
/**
* Strips an ordinal from a numeric value.
*
* @param string $day Day number with an ordinal
*
* @return int|string The integer value with any ordinal stripped, or the original string argument if it isn't a valid numeric
*/
public static function dayStringToNumber(string $day)
{
$strippedDayValue = (str_replace(self::$numberSuffixes, '', $day));
if (is_numeric($strippedDayValue)) {
return (int) $strippedDayValue;
}
return $day;
}
public static function dateTimeFromTimestamp(string $date, ?DateTimeZone $timeZone = null): DateTime
{
$dtobj = DateTime::createFromFormat('U', $date) ?: new DateTime();
$dtobj->setTimeZone($timeZone ?? self::getDefaultOrLocalTimezone());
return $dtobj;
}
public static function formattedDateTimeFromTimestamp(string $date, string $format, ?DateTimeZone $timeZone = null): string
{
$dtobj = self::dateTimeFromTimestamp($date, $timeZone);
return $dtobj->format($format);
}
/**
* Round the given DateTime object to seconds.
*/
public static function roundMicroseconds(DateTime $dti): void
{
$microseconds = (int) $dti->format('u');
$rounded = (int) round($microseconds, -6);
$modify = $rounded - $microseconds;
if ($modify !== 0) {
$dti->modify(($modify > 0 ? '+' : '') . $modify . ' microseconds');
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/StringHelper.php | src/PhpSpreadsheet/Shared/StringHelper.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
use Composer\Pcre\Preg;
use IntlCalendar;
use NumberFormatter;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use Stringable;
class StringHelper
{
private const CONTROL_CHARACTERS_KEYS = [
"\x00",
"\x01",
"\x02",
"\x03",
"\x04",
"\x05",
"\x06",
"\x07",
"\x08",
"\x0b",
"\x0c",
"\x0e",
"\x0f",
"\x10",
"\x11",
"\x12",
"\x13",
"\x14",
"\x15",
"\x16",
"\x17",
"\x18",
"\x19",
"\x1a",
"\x1b",
"\x1c",
"\x1d",
"\x1e",
"\x1f",
];
private const CONTROL_CHARACTERS_VALUES = [
'_x0000_',
'_x0001_',
'_x0002_',
'_x0003_',
'_x0004_',
'_x0005_',
'_x0006_',
'_x0007_',
'_x0008_',
'_x000B_',
'_x000C_',
'_x000E_',
'_x000F_',
'_x0010_',
'_x0011_',
'_x0012_',
'_x0013_',
'_x0014_',
'_x0015_',
'_x0016_',
'_x0017_',
'_x0018_',
'_x0019_',
'_x001A_',
'_x001B_',
'_x001C_',
'_x001D_',
'_x001E_',
'_x001F_',
];
/**
* SYLK Characters array.
*/
private const SYLK_CHARACTERS = [
"\x1B 0" => "\x00",
"\x1B 1" => "\x01",
"\x1B 2" => "\x02",
"\x1B 3" => "\x03",
"\x1B 4" => "\x04",
"\x1B 5" => "\x05",
"\x1B 6" => "\x06",
"\x1B 7" => "\x07",
"\x1B 8" => "\x08",
"\x1B 9" => "\x09",
"\x1B :" => "\x0a",
"\x1B ;" => "\x0b",
"\x1B <" => "\x0c",
"\x1B =" => "\x0d",
"\x1B >" => "\x0e",
"\x1B ?" => "\x0f",
"\x1B!0" => "\x10",
"\x1B!1" => "\x11",
"\x1B!2" => "\x12",
"\x1B!3" => "\x13",
"\x1B!4" => "\x14",
"\x1B!5" => "\x15",
"\x1B!6" => "\x16",
"\x1B!7" => "\x17",
"\x1B!8" => "\x18",
"\x1B!9" => "\x19",
"\x1B!:" => "\x1a",
"\x1B!;" => "\x1b",
"\x1B!<" => "\x1c",
"\x1B!=" => "\x1d",
"\x1B!>" => "\x1e",
"\x1B!?" => "\x1f",
"\x1B'?" => "\x7f",
"\x1B(0" => '€', // 128 in CP1252
"\x1B(2" => '‚', // 130 in CP1252
"\x1B(3" => 'ƒ', // 131 in CP1252
"\x1B(4" => '„', // 132 in CP1252
"\x1B(5" => '…', // 133 in CP1252
"\x1B(6" => '†', // 134 in CP1252
"\x1B(7" => '‡', // 135 in CP1252
"\x1B(8" => 'ˆ', // 136 in CP1252
"\x1B(9" => '‰', // 137 in CP1252
"\x1B(:" => 'Š', // 138 in CP1252
"\x1B(;" => '‹', // 139 in CP1252
"\x1BNj" => 'Œ', // 140 in CP1252
"\x1B(>" => 'Ž', // 142 in CP1252
"\x1B)1" => '‘', // 145 in CP1252
"\x1B)2" => '’', // 146 in CP1252
"\x1B)3" => '“', // 147 in CP1252
"\x1B)4" => '”', // 148 in CP1252
"\x1B)5" => '•', // 149 in CP1252
"\x1B)6" => '–', // 150 in CP1252
"\x1B)7" => '—', // 151 in CP1252
"\x1B)8" => '˜', // 152 in CP1252
"\x1B)9" => '™', // 153 in CP1252
"\x1B):" => 'š', // 154 in CP1252
"\x1B);" => '›', // 155 in CP1252
"\x1BNz" => 'œ', // 156 in CP1252
"\x1B)>" => 'ž', // 158 in CP1252
"\x1B)?" => 'Ÿ', // 159 in CP1252
"\x1B*0" => ' ', // 160 in CP1252
"\x1BN!" => '¡', // 161 in CP1252
"\x1BN\"" => '¢', // 162 in CP1252
"\x1BN#" => '£', // 163 in CP1252
"\x1BN(" => '¤', // 164 in CP1252
"\x1BN%" => '¥', // 165 in CP1252
"\x1B*6" => '¦', // 166 in CP1252
"\x1BN'" => '§', // 167 in CP1252
"\x1BNH " => '¨', // 168 in CP1252
"\x1BNS" => '©', // 169 in CP1252
"\x1BNc" => 'ª', // 170 in CP1252
"\x1BN+" => '«', // 171 in CP1252
"\x1B*<" => '¬', // 172 in CP1252
"\x1B*=" => '', // 173 in CP1252
"\x1BNR" => '®', // 174 in CP1252
"\x1B*?" => '¯', // 175 in CP1252
"\x1BN0" => '°', // 176 in CP1252
"\x1BN1" => '±', // 177 in CP1252
"\x1BN2" => '²', // 178 in CP1252
"\x1BN3" => '³', // 179 in CP1252
"\x1BNB " => '´', // 180 in CP1252
"\x1BN5" => 'µ', // 181 in CP1252
"\x1BN6" => '¶', // 182 in CP1252
"\x1BN7" => '·', // 183 in CP1252
"\x1B+8" => '¸', // 184 in CP1252
"\x1BNQ" => '¹', // 185 in CP1252
"\x1BNk" => 'º', // 186 in CP1252
"\x1BN;" => '»', // 187 in CP1252
"\x1BN<" => '¼', // 188 in CP1252
"\x1BN=" => '½', // 189 in CP1252
"\x1BN>" => '¾', // 190 in CP1252
"\x1BN?" => '¿', // 191 in CP1252
"\x1BNAA" => 'À', // 192 in CP1252
"\x1BNBA" => 'Á', // 193 in CP1252
"\x1BNCA" => 'Â', // 194 in CP1252
"\x1BNDA" => 'Ã', // 195 in CP1252
"\x1BNHA" => 'Ä', // 196 in CP1252
"\x1BNJA" => 'Å', // 197 in CP1252
"\x1BNa" => 'Æ', // 198 in CP1252
"\x1BNKC" => 'Ç', // 199 in CP1252
"\x1BNAE" => 'È', // 200 in CP1252
"\x1BNBE" => 'É', // 201 in CP1252
"\x1BNCE" => 'Ê', // 202 in CP1252
"\x1BNHE" => 'Ë', // 203 in CP1252
"\x1BNAI" => 'Ì', // 204 in CP1252
"\x1BNBI" => 'Í', // 205 in CP1252
"\x1BNCI" => 'Î', // 206 in CP1252
"\x1BNHI" => 'Ï', // 207 in CP1252
"\x1BNb" => 'Ð', // 208 in CP1252
"\x1BNDN" => 'Ñ', // 209 in CP1252
"\x1BNAO" => 'Ò', // 210 in CP1252
"\x1BNBO" => 'Ó', // 211 in CP1252
"\x1BNCO" => 'Ô', // 212 in CP1252
"\x1BNDO" => 'Õ', // 213 in CP1252
"\x1BNHO" => 'Ö', // 214 in CP1252
"\x1B-7" => '×', // 215 in CP1252
"\x1BNi" => 'Ø', // 216 in CP1252
"\x1BNAU" => 'Ù', // 217 in CP1252
"\x1BNBU" => 'Ú', // 218 in CP1252
"\x1BNCU" => 'Û', // 219 in CP1252
"\x1BNHU" => 'Ü', // 220 in CP1252
"\x1B-=" => 'Ý', // 221 in CP1252
"\x1BNl" => 'Þ', // 222 in CP1252
"\x1BN{" => 'ß', // 223 in CP1252
"\x1BNAa" => 'à', // 224 in CP1252
"\x1BNBa" => 'á', // 225 in CP1252
"\x1BNCa" => 'â', // 226 in CP1252
"\x1BNDa" => 'ã', // 227 in CP1252
"\x1BNHa" => 'ä', // 228 in CP1252
"\x1BNJa" => 'å', // 229 in CP1252
"\x1BNq" => 'æ', // 230 in CP1252
"\x1BNKc" => 'ç', // 231 in CP1252
"\x1BNAe" => 'è', // 232 in CP1252
"\x1BNBe" => 'é', // 233 in CP1252
"\x1BNCe" => 'ê', // 234 in CP1252
"\x1BNHe" => 'ë', // 235 in CP1252
"\x1BNAi" => 'ì', // 236 in CP1252
"\x1BNBi" => 'í', // 237 in CP1252
"\x1BNCi" => 'î', // 238 in CP1252
"\x1BNHi" => 'ï', // 239 in CP1252
"\x1BNs" => 'ð', // 240 in CP1252
"\x1BNDn" => 'ñ', // 241 in CP1252
"\x1BNAo" => 'ò', // 242 in CP1252
"\x1BNBo" => 'ó', // 243 in CP1252
"\x1BNCo" => 'ô', // 244 in CP1252
"\x1BNDo" => 'õ', // 245 in CP1252
"\x1BNHo" => 'ö', // 246 in CP1252
"\x1B/7" => '÷', // 247 in CP1252
"\x1BNy" => 'ø', // 248 in CP1252
"\x1BNAu" => 'ù', // 249 in CP1252
"\x1BNBu" => 'ú', // 250 in CP1252
"\x1BNCu" => 'û', // 251 in CP1252
"\x1BNHu" => 'ü', // 252 in CP1252
"\x1B/=" => 'ý', // 253 in CP1252
"\x1BN|" => 'þ', // 254 in CP1252
"\x1BNHy" => 'ÿ', // 255 in CP1252
];
/**
* Decimal separator.
*/
protected static ?string $decimalSeparator = null;
/**
* Thousands separator.
*/
protected static ?string $thousandsSeparator = null;
/**
* Currency code.
*/
protected static ?string $currencyCode = null;
/**
* Is iconv extension available?
*/
protected static ?bool $isIconvEnabled = null;
/**
* iconv options.
*/
protected static string $iconvOptions = '//IGNORE//TRANSLIT';
/** @var string[] */
protected static array $iconvOptionsArray = ['//IGNORE//TRANSLIT', '//IGNORE'];
/** @internal */
protected static string $iconvName = 'iconv';
/** @internal */
protected static bool $iconvTest2 = false;
/** @internal */
protected static bool $iconvTest3 = false;
/**
* Get whether iconv extension is available.
*/
public static function getIsIconvEnabled(): bool
{
if (isset(static::$isIconvEnabled)) {
return static::$isIconvEnabled;
}
// Assume no problems with iconv
static::$isIconvEnabled = true;
// Fail if iconv doesn't exist
if (!function_exists(static::$iconvName)) {
static::$isIconvEnabled = false;
} elseif (static::$iconvTest2 || !@iconv('UTF-8', 'UTF-16LE', 'x')) {
// Sometimes iconv is not working, and e.g. iconv('UTF-8', 'UTF-16LE', 'x') just returns false,
static::$isIconvEnabled = false;
} elseif (static::$iconvTest3 || (defined('PHP_OS') && @stristr(PHP_OS, 'AIX') && defined('ICONV_IMPL') && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) && defined('ICONV_VERSION') && (@strcasecmp(ICONV_VERSION, 'unknown') == 0))) {
// CUSTOM: IBM AIX iconv() does not work
static::$isIconvEnabled = false;
}
// Deactivate iconv default options if they fail (as seen on IBM i-series)
if (static::$isIconvEnabled) {
static::$iconvOptions = '';
foreach (static::$iconvOptionsArray as $option) {
if (@iconv('UTF-8', 'UTF-16LE' . $option, 'x') !== false) {
static::$iconvOptions = $option;
break;
}
}
}
return static::$isIconvEnabled;
}
/**
* Convert from OpenXML escaped control character to PHP control character.
*
* Excel 2007 team:
* ----------------
* That's correct, control characters are stored directly in the shared-strings table.
* We do encode characters that cannot be represented in XML using the following escape sequence:
* _xHHHH_ where H represents a hexadecimal character in the character's value...
* So you could end up with something like _x0008_ in a string (either in a cell value (<v>)
* element or in the shared string <t> element.
*
* @param string $textValue Value to unescape
*/
public static function controlCharacterOOXML2PHP(string $textValue): string
{
return Preg::replaceCallback('/_x[0-9A-F]{4}_(_xD[CDEF][0-9A-F]{2}_)?/', self::toOutChar(...), $textValue);
}
private static function toHexVal(string $char): int
{
if ($char >= '0' && $char <= '9') {
return ord($char) - ord('0');
}
return ord($char) - ord('A') + 10;
}
/** @param array<?string> $match */
private static function toOutChar(array $match): string
{
/** @var string */
$chars = $match[0];
$h = ((self::toHexVal($chars[2]) << 12)
| (self::toHexVal($chars[3]) << 8)
| (self::toHexVal($chars[4]) << 4)
| (self::toHexVal($chars[5])));
if (strlen($chars) === 7) { // no low surrogate
if ($chars[2] === 'D' && in_array($chars[3], ['8', '9', 'A', 'B', 'C', 'D', 'E', 'F'], true)) {
return '�';
}
return mb_chr($h, 'UTF-8');
}
if ($chars[2] === 'D' && in_array($chars[3], ['C', 'D', 'D', 'F'], true)) {
return '�'; // Excel interprets as one substitute, not 2
}
if ($chars[2] !== 'D' || !in_array($chars[3], ['8', '9', 'A', 'B'], true)) {
return mb_chr($h, 'UTF-8') . '�';
}
$l = ((self::toHexVal($chars[9]) << 12)
| (self::toHexVal($chars[10]) << 8)
| (self::toHexVal($chars[11]) << 4)
| (self::toHexVal($chars[12])));
$result = 0x10000 + ($h - 0xD800) * 0x400 + ($l - 0xDC00);
return mb_chr($result, 'UTF-8');
}
/**
* Convert from PHP control character to OpenXML escaped control character.
*
* Excel 2007 team:
* ----------------
* That's correct, control characters are stored directly in the shared-strings table.
* We do encode characters that cannot be represented in XML using the following escape sequence:
* _xHHHH_ where H represents a hexadecimal character in the character's value...
* So you could end up with something like _x0008_ in a string (either in a cell value (<v>)
* element or in the shared string <t> element.
*
* @param string $textValue Value to escape
*/
public static function controlCharacterPHP2OOXML(string $textValue): string
{
$textValue = Preg::replace('/_(x[0-9A-F]{4}_)/', '_x005F_$1', $textValue);
return str_replace(self::CONTROL_CHARACTERS_KEYS, self::CONTROL_CHARACTERS_VALUES, $textValue);
}
/**
* Try to sanitize UTF8, replacing invalid sequences with Unicode substitution characters.
*/
public static function sanitizeUTF8(string $textValue): string
{
$textValue = str_replace(["\xef\xbf\xbe", "\xef\xbf\xbf"], "\xef\xbf\xbd", $textValue);
$subst = mb_substitute_character(); // default is question mark
mb_substitute_character(65533); // Unicode substitution character
$returnValue = (string) mb_convert_encoding($textValue, 'UTF-8', 'UTF-8');
mb_substitute_character($subst);
return $returnValue;
}
/**
* Check if a string contains UTF8 data.
*/
public static function isUTF8(string $textValue): bool
{
return $textValue === self::sanitizeUTF8($textValue);
}
/**
* Formats a numeric value as a string for output in various output writers forcing
* point as decimal separator in case locale is other than English.
*/
public static function formatNumber(float|int|string|null $numericValue): string
{
if (is_float($numericValue)) {
return str_replace(',', '.', (string) $numericValue);
}
return (string) $numericValue;
}
/**
* Converts a UTF-8 string into BIFF8 Unicode string data (8-bit string length)
* Writes the string using uncompressed notation, no rich text, no Asian phonetics
* If mbstring extension is not available, ASCII is assumed, and compressed notation is used
* although this will give wrong results for non-ASCII strings
* see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
*
* @param string $textValue UTF-8 encoded string
* @param array<int, array{strlen: int, fontidx: int}> $arrcRuns Details of rich text runs in $value
*/
public static function UTF8toBIFF8UnicodeShort(string $textValue, array $arrcRuns = []): string
{
// character count
$ln = self::countCharacters($textValue, 'UTF-8');
// option flags
if (empty($arrcRuns)) {
$data = pack('CC', $ln, 0x0001);
// characters
$data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
} else {
$data = pack('vC', $ln, 0x09);
$data .= pack('v', count($arrcRuns));
// characters
$data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
foreach ($arrcRuns as $cRun) {
$data .= pack('v', $cRun['strlen']);
$data .= pack('v', $cRun['fontidx']);
}
}
return $data;
}
/**
* Converts a UTF-8 string into BIFF8 Unicode string data (16-bit string length)
* Writes the string using uncompressed notation, no rich text, no Asian phonetics
* If mbstring extension is not available, ASCII is assumed, and compressed notation is used
* although this will give wrong results for non-ASCII strings
* see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
*
* @param string $textValue UTF-8 encoded string
*/
public static function UTF8toBIFF8UnicodeLong(string $textValue): string
{
// characters
$chars = self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
$ln = (int) (strlen($chars) / 2); // N.B. - strlen, not mb_strlen issue #642
return pack('vC', $ln, 0x0001) . $chars;
}
/**
* Convert string from one encoding to another.
*
* @param string $to Encoding to convert to, e.g. 'UTF-8'
* @param string $from Encoding to convert from, e.g. 'UTF-16LE'
*/
public static function convertEncoding(string $textValue, string $to, string $from, ?string $options = null): string
{
if (static::getIsIconvEnabled()) {
$result = iconv($from, $to . ($options ?? static::$iconvOptions), $textValue);
if (false !== $result) {
return $result;
}
}
return (string) mb_convert_encoding($textValue, $to, $from);
}
/**
* Get character count.
*
* @param string $encoding Encoding
*
* @return int Character count
*/
public static function countCharacters(string $textValue, string $encoding = 'UTF-8'): int
{
return mb_strlen($textValue, $encoding);
}
/**
* Get character count using mb_strwidth rather than mb_strlen.
*
* @param string $encoding Encoding
*
* @return int Character count
*/
public static function countCharactersDbcs(string $textValue, string $encoding = 'UTF-8'): int
{
return mb_strwidth($textValue, $encoding);
}
/**
* Get a substring of a UTF-8 encoded string.
*
* @param string $textValue UTF-8 encoded string
* @param int $offset Start offset
* @param ?int $length Maximum number of characters in substring
*/
public static function substring(string $textValue, int $offset, ?int $length = 0): string
{
return mb_substr($textValue, $offset, $length, 'UTF-8');
}
/**
* Convert a UTF-8 encoded string to upper case.
*
* @param string $textValue UTF-8 encoded string
*/
public static function strToUpper(string $textValue): string
{
return mb_convert_case($textValue, MB_CASE_UPPER, 'UTF-8');
}
/**
* Convert a UTF-8 encoded string to lower case.
*
* @param string $textValue UTF-8 encoded string
*/
public static function strToLower(string $textValue): string
{
return mb_convert_case($textValue, MB_CASE_LOWER, 'UTF-8');
}
/**
* Convert a UTF-8 encoded string to title/proper case
* (uppercase every first character in each word, lower case all other characters).
*
* @param string $textValue UTF-8 encoded string
*/
public static function strToTitle(string $textValue): string
{
return mb_convert_case($textValue, MB_CASE_TITLE, 'UTF-8');
}
public static function mbIsUpper(string $character): bool
{
return mb_strtolower($character, 'UTF-8') !== $character;
}
/**
* Splits a UTF-8 string into an array of individual characters.
*
* @return string[]
*/
public static function mbStrSplit(string $string): array
{
// Split at all position not after the start: ^
// and not before the end: $
$split = Preg::split('/(?<!^)(?!$)/u', $string);
return $split;
}
/**
* Reverse the case of a string, so that all uppercase characters become lowercase
* and all lowercase characters become uppercase.
*
* @param string $textValue UTF-8 encoded string
*/
public static function strCaseReverse(string $textValue): string
{
$characters = self::mbStrSplit($textValue);
foreach ($characters as &$character) {
if (self::mbIsUpper($character)) {
$character = mb_strtolower($character, 'UTF-8');
} else {
$character = mb_strtoupper($character, 'UTF-8');
}
}
return implode('', $characters);
}
private static function useAlt(string $altValue, string $default, bool $trimAlt): string
{
return ($trimAlt ? trim($altValue) : $altValue) ?: $default;
}
private static function getLocaleValue(string $key, string $altKey, string $default, bool $trimAlt = false): string
{
/** @var string[] */
$localeconv = localeconv();
$rslt = $localeconv[$key];
// win-1252 implements Euro as 0x80 plus other symbols
// Not suitable for Composer\Pcre\Preg
if (preg_match('//u', $rslt) !== 1) {
$rslt = '';
}
return $rslt ?: self::useAlt($localeconv[$altKey], $default, $trimAlt);
}
/**
* Get the decimal separator. If it has not yet been set explicitly, try to obtain number
* formatting information from locale.
*/
public static function getDecimalSeparator(): string
{
if (!isset(static::$decimalSeparator)) {
static::$decimalSeparator = self::getLocaleValue('decimal_point', 'mon_decimal_point', '.');
}
return static::$decimalSeparator;
}
/**
* Set the decimal separator. Only used by NumberFormat::toFormattedString()
* to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
*
* @param ?string $separator Character for decimal separator
*/
public static function setDecimalSeparator(?string $separator): void
{
static::$decimalSeparator = $separator;
}
/**
* Get the thousands separator. If it has not yet been set explicitly, try to obtain number
* formatting information from locale.
*/
public static function getThousandsSeparator(): string
{
if (!isset(static::$thousandsSeparator)) {
static::$thousandsSeparator = self::getLocaleValue('thousands_sep', 'mon_thousands_sep', ',');
}
return static::$thousandsSeparator;
}
/**
* Set the thousands separator. Only used by NumberFormat::toFormattedString()
* to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
*
* @param ?string $separator Character for thousands separator
*/
public static function setThousandsSeparator(?string $separator): void
{
static::$thousandsSeparator = $separator;
}
/**
* Get the currency code. If it has not yet been set explicitly, try to obtain the
* symbol information from locale.
*/
public static function getCurrencyCode(bool $trimAlt = false): string
{
if (!isset(static::$currencyCode)) {
static::$currencyCode = self::getLocaleValue('currency_symbol', 'int_curr_symbol', '$', $trimAlt);
}
return static::$currencyCode;
}
/**
* Set the currency code. Only used by NumberFormat::toFormattedString()
* to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
*
* @param ?string $currencyCode Character for currency code
*/
public static function setCurrencyCode(?string $currencyCode): void
{
static::$currencyCode = $currencyCode;
}
/**
* Convert SYLK encoded string to UTF-8.
*
* @param string $textValue SYLK encoded string
*
* @return string UTF-8 encoded string
*/
public static function SYLKtoUTF8(string $textValue): string
{
// If there is no escape character in the string there is nothing to do
if (!str_contains($textValue, "\x1b")) {
return $textValue;
}
foreach (self::SYLK_CHARACTERS as $k => $v) {
$textValue = str_replace($k, $v, $textValue);
}
return $textValue;
}
/**
* Retrieve any leading numeric part of a string, or return the full string if no leading numeric
* (handles basic integer or float, but not exponent or non decimal).
*
* @return float|string string or only the leading numeric part of the string
*/
public static function testStringAsNumeric(string $textValue): float|string
{
if (is_numeric($textValue)) {
return $textValue;
}
$v = (float) $textValue;
return (is_numeric(substr($textValue, 0, strlen((string) $v)))) ? $v : $textValue;
}
public static function strlenAllowNull(?string $string): int
{
return strlen("$string");
}
/**
* @param bool $convertBool If true, convert bool to locale-aware TRUE/FALSE rather than 1/null-string
* @param bool $lessFloatPrecision If true, floats will be converted to a more human-friendly but less computationally accurate value
*/
public static function convertToString(mixed $value, bool $throw = true, string $default = '', bool $convertBool = false, bool $lessFloatPrecision = false): string
{
if ($convertBool && is_bool($value)) {
return $value ? Calculation::getTRUE() : Calculation::getFALSE();
}
if (is_float($value) && !$lessFloatPrecision) {
$string = (string) $value;
// look out for scientific notation
if (!Preg::isMatch('/[^-+0-9.]/', $string)) {
$minus = $value < 0 ? '-' : '';
$positive = abs($value);
$floor = floor($positive);
$oldFrac = (string) ($positive - $floor);
$frac = Preg::replace('/^0[.](\d+)$/', '$1', $oldFrac);
if ($frac !== $oldFrac) {
return "$minus$floor.$frac";
}
}
return $string;
}
if ($value === null || is_scalar($value) || $value instanceof Stringable) {
return (string) $value;
}
if ($throw) {
throw new SpreadsheetException('Unable to convert to string');
}
return $default;
}
/**
* Assist with POST items when samples are run in browser.
* Never run as part of unit tests, which are command line.
*
* @codeCoverageIgnore
*/
public static function convertPostToString(string $index, string $default = ''): string
{
if (isset($_POST[$index])) {
return htmlentities(self::convertToString($_POST[$index], false, $default));
}
return $default;
}
/**
* Php introduced str_increment with Php8.3,
* but didn't issue deprecation notices till 8.5.
*
* @codeCoverageIgnore
*/
public static function stringIncrement(string &$str): string
{
if (function_exists('str_increment')) {
$str = str_increment($str); // @phpstan-ignore-line
} else {
++$str; // @phpstan-ignore-line
}
return $str; // @phpstan-ignore-line
}
/** @internal */
protected static string $testClass = IntlCalendar::class;
/**
* Set all of currencyCode, thousandsSeparator, decimalSeparator,
* and Calculation locale with a single call.
* The main point here is avoid the use of Php setlocale,
* which is not threadsafe. It uses the Intl extension instead,
* which is not a requirement for PhpSpreadsheet.
* Because of that, the function returns a bool which will
* be false if Intl is not available, or the supplied locale
* is not valid according to Intl.
*/
public static function setLocale(?string $locale): bool
{
if ($locale === null) {
self::$currencyCode = null;
self::$thousandsSeparator = null;
self::$decimalSeparator = null;
Calculation::getInstance()->setLocale('en_us');
return true;
}
$localeCalc = $locale;
if (Preg::isMatch('/^([a-z][a-z])_([a-z][a-z])(?:[.]utf-8)?$/i', $locale, $matches)) {
$locale = strtolower($matches[1]) . '_' . strtoupper($matches[2]);
$localeCalc = strtolower($matches[1]) . '_' . strtolower($matches[2]);
}
if (!class_exists(static::$testClass)) {
return false;
}
// NumberFormatter constructor succeeds even with
// bad locale before Php8.4, so try to validate
// the locale beforehand.
$locales = IntlCalendar::getAvailableLocales();
if (!in_array($locale, $locales, true)) {
return false;
}
$formatter = new NumberFormatter(
$locale,
NumberFormatter::CURRENCY
);
$currency = $formatter->getSymbol(
NumberFormatter::CURRENCY_SYMBOL
);
$formatter = new NumberFormatter(
$locale,
NumberFormatter::DECIMAL
);
$thousands = $formatter->getSymbol(
NumberFormatter::GROUPING_SEPARATOR_SYMBOL
);
$decimal = $formatter->getSymbol(
NumberFormatter::DECIMAL_SEPARATOR_SYMBOL
);
self::$currencyCode = $currency;
self::$thousandsSeparator = $thousands;
self::$decimalSeparator = $decimal;
Calculation::getInstance()->setLocale($localeCalc);
return true;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/OLERead.php | src/PhpSpreadsheet/Shared/OLERead.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
class OLERead
{
private string $data = '';
// Size of a sector = 512 bytes
const BIG_BLOCK_SIZE = 0x200;
// Size of a short sector = 64 bytes
const SMALL_BLOCK_SIZE = 0x40;
// Size of a directory entry always = 128 bytes
const PROPERTY_STORAGE_BLOCK_SIZE = 0x80;
// Minimum size of a standard stream = 4096 bytes, streams smaller than this are stored as short streams
const SMALL_BLOCK_THRESHOLD = 0x1000;
// header offsets
const NUM_BIG_BLOCK_DEPOT_BLOCKS_POS = 0x2C;
const ROOT_START_BLOCK_POS = 0x30;
const SMALL_BLOCK_DEPOT_BLOCK_POS = 0x3C;
const EXTENSION_BLOCK_POS = 0x44;
const NUM_EXTENSION_BLOCK_POS = 0x48;
const BIG_BLOCK_DEPOT_BLOCKS_POS = 0x4C;
// property storage offsets (directory offsets)
const SIZE_OF_NAME_POS = 0x40;
const TYPE_POS = 0x42;
const START_BLOCK_POS = 0x74;
const SIZE_POS = 0x78;
public ?int $wrkbook = null;
public ?int $summaryInformation = null;
public ?int $documentSummaryInformation = null;
private int $numBigBlockDepotBlocks;
private int $rootStartBlock;
private int $sbdStartBlock;
private int $extensionBlock;
private int $numExtensionBlocks;
private string $bigBlockChain;
private string $smallBlockChain;
private string $entry;
private int $rootentry;
/** @var mixed[][] */
private array $props = [];
/**
* Read the file.
*/
public function read(string $filename): void
{
File::assertFile($filename);
// Get the file identifier
// Don't bother reading the whole file until we know it's a valid OLE file
$this->data = (string) file_get_contents($filename, false, null, 0, 8);
// Check OLE identifier
$identifierOle = pack('CCCCCCCC', 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1);
if ($this->data != $identifierOle) {
throw new ReaderException('The filename ' . $filename . ' is not recognised as an OLE file');
}
// Get the file data
$this->data = (string) file_get_contents($filename);
// Total number of sectors used for the SAT
$this->numBigBlockDepotBlocks = self::getInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS);
// SecID of the first sector of the directory stream
$this->rootStartBlock = self::getInt4d($this->data, self::ROOT_START_BLOCK_POS);
// SecID of the first sector of the SSAT (or -2 if not extant)
$this->sbdStartBlock = self::getInt4d($this->data, self::SMALL_BLOCK_DEPOT_BLOCK_POS);
// SecID of the first sector of the MSAT (or -2 if no additional sectors are used)
$this->extensionBlock = self::getInt4d($this->data, self::EXTENSION_BLOCK_POS);
// Total number of sectors used by MSAT
$this->numExtensionBlocks = self::getInt4d($this->data, self::NUM_EXTENSION_BLOCK_POS);
$bigBlockDepotBlocks = [];
$pos = self::BIG_BLOCK_DEPOT_BLOCKS_POS;
$bbdBlocks = $this->numBigBlockDepotBlocks;
if ($this->numExtensionBlocks !== 0) {
$bbdBlocks = (self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS) / 4;
}
for ($i = 0; $i < $bbdBlocks; ++$i) {
$bigBlockDepotBlocks[$i] = self::getInt4d($this->data, $pos);
$pos += 4;
}
for ($j = 0; $j < $this->numExtensionBlocks; ++$j) {
$pos = ($this->extensionBlock + 1) * self::BIG_BLOCK_SIZE;
$blocksToRead = min($this->numBigBlockDepotBlocks - $bbdBlocks, self::BIG_BLOCK_SIZE / 4 - 1);
for ($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; ++$i) {
$bigBlockDepotBlocks[$i] = self::getInt4d($this->data, $pos);
$pos += 4;
}
$bbdBlocks += $blocksToRead;
if ($bbdBlocks < $this->numBigBlockDepotBlocks) {
$this->extensionBlock = self::getInt4d($this->data, $pos);
}
}
$pos = 0;
$this->bigBlockChain = '';
$bbs = self::BIG_BLOCK_SIZE / 4;
for ($i = 0; $i < $this->numBigBlockDepotBlocks; ++$i) {
$pos = ($bigBlockDepotBlocks[$i] + 1) * self::BIG_BLOCK_SIZE;
$this->bigBlockChain .= substr($this->data, $pos, 4 * $bbs);
$pos += 4 * $bbs;
}
$sbdBlock = $this->sbdStartBlock;
$this->smallBlockChain = '';
while ($sbdBlock != -2) {
$pos = ($sbdBlock + 1) * self::BIG_BLOCK_SIZE;
$this->smallBlockChain .= substr($this->data, $pos, 4 * $bbs);
$pos += 4 * $bbs;
$sbdBlock = self::getInt4d($this->bigBlockChain, $sbdBlock * 4);
}
// read the directory stream
$block = $this->rootStartBlock;
$this->entry = $this->readData($block);
$this->readPropertySets();
}
/**
* Extract binary stream data.
*/
public function getStream(?int $stream): ?string
{
if ($stream === null) {
return null;
}
$streamData = '';
if ($this->props[$stream]['size'] < self::SMALL_BLOCK_THRESHOLD) {
/** @var int */
$temp = $this->props[$this->rootentry]['startBlock'];
$rootdata = $this->readData($temp);
/** @var int */
$block = $this->props[$stream]['startBlock'];
while ($block != -2) {
$pos = $block * self::SMALL_BLOCK_SIZE;
$streamData .= substr($rootdata, $pos, self::SMALL_BLOCK_SIZE);
$block = self::getInt4d($this->smallBlockChain, $block * 4);
}
return $streamData;
}
/** @var int */
$temp = $this->props[$stream]['size'];
$numBlocks = $temp / self::BIG_BLOCK_SIZE;
if ($temp % self::BIG_BLOCK_SIZE != 0) {
++$numBlocks;
}
if ($numBlocks == 0) {
return '';
}
/** @var int */
$block = $this->props[$stream]['startBlock'];
while ($block != -2) {
$pos = ($block + 1) * self::BIG_BLOCK_SIZE;
$streamData .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
$block = self::getInt4d($this->bigBlockChain, $block * 4);
}
return $streamData;
}
/**
* Read a standard stream (by joining sectors using information from SAT).
*
* @param int $block Sector ID where the stream starts
*
* @return string Data for standard stream
*/
private function readData(int $block): string
{
$data = '';
while ($block != -2) {
$pos = ($block + 1) * self::BIG_BLOCK_SIZE;
$data .= substr($this->data, $pos, self::BIG_BLOCK_SIZE);
$block = self::getInt4d($this->bigBlockChain, $block * 4);
}
return $data;
}
/**
* Read entries in the directory stream.
*/
private function readPropertySets(): void
{
$offset = 0;
// loop through entries, each entry is 128 bytes
$entryLen = strlen($this->entry);
while ($offset < $entryLen) {
// entry data (128 bytes)
$d = substr($this->entry, $offset, self::PROPERTY_STORAGE_BLOCK_SIZE);
// size in bytes of name
$nameSize = ord($d[self::SIZE_OF_NAME_POS]) | (ord($d[self::SIZE_OF_NAME_POS + 1]) << 8);
// type of entry
$type = ord($d[self::TYPE_POS]);
// sectorID of first sector or short sector, if this entry refers to a stream (the case with workbook)
// sectorID of first sector of the short-stream container stream, if this entry is root entry
$startBlock = self::getInt4d($d, self::START_BLOCK_POS);
$size = self::getInt4d($d, self::SIZE_POS);
$name = str_replace("\x00", '', substr($d, 0, $nameSize));
$this->props[] = [
'name' => $name,
'type' => $type,
'startBlock' => $startBlock,
'size' => $size,
];
// tmp helper to simplify checks
$upName = strtoupper($name);
// Workbook directory entry (BIFF5 uses Book, BIFF8 uses Workbook)
if (($upName === 'WORKBOOK') || ($upName === 'BOOK')) {
$this->wrkbook = count($this->props) - 1;
} elseif ($upName === 'ROOT ENTRY' || $upName === 'R') {
// Root entry
$this->rootentry = count($this->props) - 1;
}
// Summary information
if ($name == chr(5) . 'SummaryInformation') {
$this->summaryInformation = count($this->props) - 1;
}
// Additional Document Summary information
if ($name == chr(5) . 'DocumentSummaryInformation') {
$this->documentSummaryInformation = count($this->props) - 1;
}
$offset += self::PROPERTY_STORAGE_BLOCK_SIZE;
}
}
/**
* Read 4 bytes of data at specified position.
*/
private static function getInt4d(string $data, int $pos): int
{
if ($pos < 0) {
// Invalid position
throw new ReaderException('Parameter pos=' . $pos . ' is invalid.');
}
$len = strlen($data);
if ($len < $pos + 4) {
$data .= str_repeat("\0", $pos + 4 - $len);
}
// FIX: represent numbers correctly on 64-bit system
// http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334
// Changed by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems
$_or_24 = ord($data[$pos + 3]);
if ($_or_24 >= 128) {
// negative number
$_ord_24 = -abs((256 - $_or_24) << 24);
} else {
$_ord_24 = ($_or_24 & 127) << 24;
}
return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/IntOrFloat.php | src/PhpSpreadsheet/Shared/IntOrFloat.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
class IntOrFloat
{
/**
* Help some functions with large results operate correctly on 32-bit,
* by returning result as int when possible, float otherwise.
*/
public static function evaluate(float|int $value): float|int
{
$iValue = (int) $value;
return ($value == $iValue) ? $iValue : $value;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Xls.php | src/PhpSpreadsheet/Shared/Xls.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Helper\Dimension;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class Xls
{
/**
* Get the width of a column in pixels. We use the relationship y = ceil(7x) where
* x is the width in intrinsic Excel units (measuring width in number of normal characters)
* This holds for Arial 10.
*
* @param Worksheet $worksheet The sheet
* @param string $col The column
*
* @return int The width in pixels
*/
public static function sizeCol(Worksheet $worksheet, string $col = 'A'): int
{
// default font of the workbook
$font = $worksheet->getParentOrThrow()->getDefaultStyle()->getFont();
$columnDimensions = $worksheet->getColumnDimensions();
// first find the true column width in pixels (uncollapsed and unhidden)
if (isset($columnDimensions[$col]) && $columnDimensions[$col]->getWidth() != -1) {
// then we have column dimension with explicit width
$columnDimension = $columnDimensions[$col];
$width = $columnDimension->getWidth();
$pixelWidth = Drawing::cellDimensionToPixels($width, $font);
} elseif ($worksheet->getDefaultColumnDimension()->getWidth() != -1) {
// then we have default column dimension with explicit width
$defaultColumnDimension = $worksheet->getDefaultColumnDimension();
$width = $defaultColumnDimension->getWidth();
$pixelWidth = Drawing::cellDimensionToPixels($width, $font);
} else {
// we don't even have any default column dimension. Width depends on default font
$pixelWidth = Font::getDefaultColumnWidthByFont($font, true);
}
// now find the effective column width in pixels
if (isset($columnDimensions[$col]) && !$columnDimensions[$col]->getVisible()) {
$effectivePixelWidth = 0;
} else {
$effectivePixelWidth = $pixelWidth;
}
return $effectivePixelWidth;
}
/**
* Convert the height of a cell from user's units to pixels. By interpolation
* the relationship is: y = 4/3x. If the height hasn't been set by the user we
* use the default value. If the row is hidden we use a value of zero.
*
* @param Worksheet $worksheet The sheet
* @param int $row The row index (1-based)
*
* @return int The width in pixels
*/
public static function sizeRow(Worksheet $worksheet, int $row = 1): int
{
// default font of the workbook
$font = $worksheet->getParentOrThrow()->getDefaultStyle()->getFont();
$rowDimensions = $worksheet->getRowDimensions();
// first find the true row height in pixels (uncollapsed and unhidden)
if (isset($rowDimensions[$row]) && $rowDimensions[$row]->getRowHeight() != -1) {
// then we have a row dimension
$rowDimension = $rowDimensions[$row];
$rowHeight = $rowDimension->getRowHeight();
$pixelRowHeight = (int) ceil(4 * $rowHeight / 3); // here we assume Arial 10
} elseif ($worksheet->getDefaultRowDimension()->getRowHeight() != -1) {
// then we have a default row dimension with explicit height
$defaultRowDimension = $worksheet->getDefaultRowDimension();
$pixelRowHeight = $defaultRowDimension->getRowHeight(Dimension::UOM_PIXELS);
} else {
// we don't even have any default row dimension. Height depends on default font
$pointRowHeight = Font::getDefaultRowHeightByFont($font);
$pixelRowHeight = Font::fontSizeToPixels((int) $pointRowHeight);
}
// now find the effective row height in pixels
if (isset($rowDimensions[$row]) && !$rowDimensions[$row]->getVisible()) {
$effectivePixelRowHeight = 0;
} else {
$effectivePixelRowHeight = $pixelRowHeight;
}
return (int) $effectivePixelRowHeight;
}
/**
* Get the horizontal distance in pixels between two anchors
* The distanceX is found as sum of all the spanning columns widths minus correction for the two offsets.
*
* @param float|int $startOffsetX Offset within start cell measured in 1/1024 of the cell width
* @param float|int $endOffsetX Offset within end cell measured in 1/1024 of the cell width
*
* @return int Horizontal measured in pixels
*/
public static function getDistanceX(Worksheet $worksheet, string $startColumn = 'A', float|int $startOffsetX = 0, string $endColumn = 'A', float|int $endOffsetX = 0): int
{
$distanceX = 0;
// add the widths of the spanning columns
$startColumnIndex = Coordinate::columnIndexFromString($startColumn);
$endColumnIndex = Coordinate::columnIndexFromString($endColumn);
for ($i = $startColumnIndex; $i <= $endColumnIndex; ++$i) {
$distanceX += self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($i));
}
// correct for offsetX in startcell
$distanceX -= (int) floor(self::sizeCol($worksheet, $startColumn) * $startOffsetX / 1024);
// correct for offsetX in endcell
$distanceX -= (int) floor(self::sizeCol($worksheet, $endColumn) * (1 - $endOffsetX / 1024));
return $distanceX;
}
/**
* Get the vertical distance in pixels between two anchors
* The distanceY is found as sum of all the spanning rows minus two offsets.
*
* @param int $startRow (1-based)
* @param float|int $startOffsetY Offset within start cell measured in 1/256 of the cell height
* @param int $endRow (1-based)
* @param float|int $endOffsetY Offset within end cell measured in 1/256 of the cell height
*
* @return int Vertical distance measured in pixels
*/
public static function getDistanceY(Worksheet $worksheet, int $startRow = 1, float|int $startOffsetY = 0, int $endRow = 1, float|int $endOffsetY = 0): int
{
$distanceY = 0;
// add the widths of the spanning rows
for ($row = $startRow; $row <= $endRow; ++$row) {
$distanceY += self::sizeRow($worksheet, $row);
}
// correct for offsetX in startcell
$distanceY -= (int) floor(self::sizeRow($worksheet, $startRow) * $startOffsetY / 256);
// correct for offsetX in endcell
$distanceY -= (int) floor(self::sizeRow($worksheet, $endRow) * (1 - $endOffsetY / 256));
return $distanceY;
}
/**
* Convert 1-cell anchor coordinates to 2-cell anchor coordinates
* This function is ported from PEAR Spreadsheet_Writer_Excel with small modifications.
*
* Calculate the vertices that define the position of the image as required by
* the OBJ record.
*
* +------------+------------+
* | A | B |
* +-----+------------+------------+
* | |(x1,y1) | |
* | 1 |(A1)._______|______ |
* | | | | |
* | | | | |
* +-----+----| BITMAP |-----+
* | | | | |
* | 2 | |______________. |
* | | | (B2)|
* | | | (x2,y2)|
* +---- +------------+------------+
*
* Example of a bitmap that covers some of the area from cell A1 to cell B2.
*
* Based on the width and height of the bitmap we need to calculate 8 vars:
* $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2.
* The width and height of the cells are also variable and have to be taken into
* account.
* The values of $col_start and $row_start are passed in from the calling
* function. The values of $col_end and $row_end are calculated by subtracting
* the width and height of the bitmap from the width and height of the
* underlying cells.
* The vertices are expressed as a percentage of the underlying cell width as
* follows (rhs values are in pixels):
*
* x1 = X / W *1024
* y1 = Y / H *256
* x2 = (X-1) / W *1024
* y2 = (Y-1) / H *256
*
* Where: X is distance from the left side of the underlying cell
* Y is distance from the top of the underlying cell
* W is the width of the cell
* H is the height of the cell
*
* @param string $coordinates E.g. 'A1'
* @param int $offsetX Horizontal offset in pixels
* @param int $offsetY Vertical offset in pixels
* @param int $width Width in pixels
* @param int $height Height in pixels
*
* @return ?array{startCoordinates: string, startOffsetX: float|int, startOffsetY: float|int, endCoordinates: string, endOffsetX: float|int, endOffsetY: float|int}
*/
public static function oneAnchor2twoAnchor(Worksheet $worksheet, string $coordinates, int $offsetX, int $offsetY, int $width, int $height): ?array
{
[$col_start, $row] = Coordinate::indexesFromString($coordinates);
$row_start = $row - 1;
$x1 = $offsetX;
$y1 = $offsetY;
// Initialise end cell to the same as the start cell
$col_end = $col_start; // Col containing lower right corner of object
$row_end = $row_start; // Row containing bottom right corner of object
// Zero the specified offset if greater than the cell dimensions
if ($x1 >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start))) {
$x1 = 0;
}
if ($y1 >= self::sizeRow($worksheet, $row_start + 1)) {
$y1 = 0;
}
$width = $width + $x1 - 1;
$height = $height + $y1 - 1;
// Subtract the underlying cell widths to find the end cell of the image
while ($width >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end))) {
$width -= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end));
++$col_end;
}
// Subtract the underlying cell heights to find the end cell of the image
while ($height >= self::sizeRow($worksheet, $row_end + 1)) {
$height -= self::sizeRow($worksheet, $row_end + 1);
++$row_end;
}
// Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
// with zero height or width.
if (
self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) == 0
|| self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) == 0
|| self::sizeRow($worksheet, $row_start + 1) == 0
|| self::sizeRow($worksheet, $row_end + 1) == 0
) {
return null;
}
// Convert the pixel values to the percentage value expected by Excel
$x1 = $x1 / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) * 1024;
$y1 = $y1 / self::sizeRow($worksheet, $row_start + 1) * 256;
$x2 = ($width + 1) / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object
$y2 = ($height + 1) / self::sizeRow($worksheet, $row_end + 1) * 256; // Distance to bottom of object
$startCoordinates = Coordinate::stringFromColumnIndex($col_start) . ($row_start + 1);
$endCoordinates = Coordinate::stringFromColumnIndex($col_end) . ($row_end + 1);
return [
'startCoordinates' => $startCoordinates,
'startOffsetX' => $x1,
'startOffsetY' => $y1,
'endCoordinates' => $endCoordinates,
'endOffsetX' => $x2,
'endOffsetY' => $y2,
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/File.php | src/PhpSpreadsheet/Shared/File.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
use ZipArchive;
class File
{
/**
* Use Temp or File Upload Temp for temporary files.
*/
protected static bool $useUploadTempDirectory = false;
/**
* Set the flag indicating whether the File Upload Temp directory should be used for temporary files.
*/
public static function setUseUploadTempDirectory(bool $useUploadTempDir): void
{
self::$useUploadTempDirectory = (bool) $useUploadTempDir;
}
/**
* Get the flag indicating whether the File Upload Temp directory should be used for temporary files.
*/
public static function getUseUploadTempDirectory(): bool
{
return self::$useUploadTempDirectory;
}
// https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
// Section 4.3.7
// Looks like there might be endian-ness considerations
private const ZIP_FIRST_4 = [
"\x50\x4b\x03\x04", // what it looks like on my system
"\x04\x03\x4b\x50", // what it says in documentation
];
private static function validateZipFirst4(string $zipFile): bool
{
$contents = @file_get_contents($zipFile, false, null, 0, 4);
return in_array($contents, self::ZIP_FIRST_4, true);
}
/**
* Verify if a file exists.
*/
public static function fileExists(string $filename): bool
{
// Sick construction, but it seems that
// file_exists returns strange values when
// doing the original file_exists on ZIP archives...
if (strtolower(substr($filename, 0, 6)) == 'zip://') {
// Open ZIP file and verify if the file exists
$zipFile = substr($filename, 6, strrpos($filename, '#') - 6);
$archiveFile = substr($filename, strrpos($filename, '#') + 1);
if (self::validateZipFirst4($zipFile)) {
$zip = new ZipArchive();
$res = $zip->open($zipFile);
if ($res === true) {
$returnValue = ($zip->getFromName($archiveFile) !== false);
$zip->close();
return $returnValue;
}
}
return false;
}
return file_exists($filename);
}
/**
* Returns canonicalized absolute pathname, also for ZIP archives.
*/
public static function realpath(string $filename): string
{
// Returnvalue
$returnValue = '';
// Try using realpath()
if (file_exists($filename)) {
$returnValue = realpath($filename) ?: '';
}
// Found something?
if ($returnValue === '') {
$pathArray = explode('/', $filename);
while (in_array('..', $pathArray) && $pathArray[0] != '..') {
$iMax = count($pathArray);
for ($i = 1; $i < $iMax; ++$i) {
if ($pathArray[$i] == '..') {
array_splice($pathArray, $i - 1, 2);
break;
}
}
}
$returnValue = implode('/', $pathArray);
}
// Return
return $returnValue;
}
/**
* Get the systems temporary directory.
*/
public static function sysGetTempDir(): string
{
$path = sys_get_temp_dir();
if (self::$useUploadTempDirectory) {
// use upload-directory when defined to allow running on environments having very restricted
// open_basedir configs
if (ini_get('upload_tmp_dir') !== false) {
if ($temp = ini_get('upload_tmp_dir')) {
if (file_exists($temp)) {
$path = $temp;
}
}
}
}
return realpath($path) ?: '';
}
public static function temporaryFilename(): string
{
return tempnam(self::sysGetTempDir(), 'phpspreadsheet') ?: throw new Exception('Could not create temporary file');
}
/**
* Assert that given path is an existing file and is readable, otherwise throw exception.
*/
public static function assertFile(string $filename, string $zipMember = ''): void
{
if (!is_file($filename) || !is_readable($filename)) {
throw new ReaderException('File "' . $filename . '" does not exist or is not readable.');
}
if ($zipMember !== '') {
$zipfile = "zip://$filename#$zipMember";
if (!self::fileExists($zipfile)) {
// Has the file been saved with Windoze directory separators rather than unix?
$zipfile = "zip://$filename#" . str_replace('/', '\\', $zipMember);
if (!self::fileExists($zipfile)) {
throw new ReaderException("Could not find zip member $zipfile");
}
}
}
}
/**
* Same as assertFile, except return true/false and don't throw Exception.
*/
public static function testFileNoThrow(string $filename, ?string $zipMember = null): bool
{
if (!is_file($filename) || !is_readable($filename)) {
return false;
}
if ($zipMember === null) {
return true;
}
// validate zip, but don't check specific member
if ($zipMember === '') {
return self::validateZipFirst4($filename);
}
$zipfile = "zip://$filename#$zipMember";
if (self::fileExists($zipfile)) {
return true;
}
// Has the file been saved with Windoze directory separators rather than unix?
$zipfile = "zip://$filename#" . str_replace('/', '\\', $zipMember);
return self::fileExists($zipfile);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/PasswordHasher.php | src/PhpSpreadsheet/Shared/PasswordHasher.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Exception as SpException;
use PhpOffice\PhpSpreadsheet\Worksheet\Protection;
class PasswordHasher
{
const MAX_PASSWORD_LENGTH = 255;
/**
* Get algorithm name for PHP.
*/
private static function getAlgorithm(string $algorithmName): string
{
if (!$algorithmName) {
return '';
}
// Mapping between algorithm name in Excel and algorithm name in PHP
$mapping = [
Protection::ALGORITHM_MD2 => 'md2',
Protection::ALGORITHM_MD4 => 'md4',
Protection::ALGORITHM_MD5 => 'md5',
Protection::ALGORITHM_SHA_1 => 'sha1',
Protection::ALGORITHM_SHA_256 => 'sha256',
Protection::ALGORITHM_SHA_384 => 'sha384',
Protection::ALGORITHM_SHA_512 => 'sha512',
Protection::ALGORITHM_RIPEMD_128 => 'ripemd128',
Protection::ALGORITHM_RIPEMD_160 => 'ripemd160',
Protection::ALGORITHM_WHIRLPOOL => 'whirlpool',
];
if (array_key_exists($algorithmName, $mapping)) {
return $mapping[$algorithmName];
}
throw new SpException('Unsupported password algorithm: ' . $algorithmName);
}
/**
* Create a password hash from a given string.
*
* This method is based on the spec at:
* https://interoperability.blob.core.windows.net/files/MS-OFFCRYPTO/[MS-OFFCRYPTO].pdf
* 2.3.7.1 Binary Document Password Verifier Derivation Method 1
*
* It replaces a method based on the algorithm provided by
* Daniel Rentz of OpenOffice and the PEAR package
* Spreadsheet_Excel_Writer by Xavier Noguer <xnoguer@rezebra.com>.
*
* @param string $password Password to hash
*/
private static function defaultHashPassword(string $password): string
{
$verifier = 0;
$pwlen = strlen($password);
$passwordArray = pack('c', $pwlen) . $password;
for ($i = $pwlen; $i >= 0; --$i) {
$intermediate1 = (($verifier & 0x4000) === 0) ? 0 : 1;
$intermediate2 = 2 * $verifier;
$intermediate2 = $intermediate2 & 0x7FFF;
$intermediate3 = $intermediate1 | $intermediate2;
$verifier = $intermediate3 ^ ord($passwordArray[$i]);
}
$verifier ^= 0xCE4B;
return strtoupper(dechex($verifier));
}
/**
* Create a password hash from a given string by a specific algorithm.
*
* 2.4.2.4 ISO Write Protection Method
*
* @see https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-offcrypto/1357ea58-646e-4483-92ef-95d718079d6f
*
* @param string $password Password to hash
* @param string $algorithm Hash algorithm used to compute the password hash value
* @param string $salt Pseudorandom base64-encoded string
* @param int $spinCount Number of times to iterate on a hash of a password
*
* @return string Hashed password
*/
public static function hashPassword(string $password, string $algorithm = '', string $salt = '', int $spinCount = 10000): string
{
if (strlen($password) > self::MAX_PASSWORD_LENGTH) {
throw new SpException('Password exceeds ' . self::MAX_PASSWORD_LENGTH . ' characters');
}
$phpAlgorithm = self::getAlgorithm($algorithm);
if (!$phpAlgorithm) {
return self::defaultHashPassword($password);
}
$saltValue = base64_decode($salt);
$encodedPassword = mb_convert_encoding($password, 'UCS-2LE', 'UTF-8');
$hashValue = hash($phpAlgorithm, $saltValue . $encodedPassword, true);
for ($i = 0; $i < $spinCount; ++$i) {
$hashValue = hash($phpAlgorithm, $hashValue . pack('L', $i), true);
}
return base64_encode($hashValue);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/OLE/PPS.php | src/PhpSpreadsheet/Shared/OLE/PPS.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\OLE;
// vim: set expandtab tabstop=4 shiftwidth=4:
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2002 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Xavier Noguer <xnoguer@php.net> |
// | Based on OLE::Storage_Lite by Kawai, Takanori |
// +----------------------------------------------------------------------+
//
use PhpOffice\PhpSpreadsheet\Shared\OLE;
/**
* Class for creating PPS's for OLE containers.
*
* @author Xavier Noguer <xnoguer@php.net>
*/
class PPS
{
private const ALL_ONE_BITS = (PHP_INT_SIZE > 4) ? 0xFFFFFFFF : -1;
/**
* The PPS index.
*/
public int $No;
/**
* The PPS name (in Unicode).
*/
public string $Name;
/**
* The PPS type. Dir, Root or File.
*/
public int $Type;
/**
* The index of the previous PPS.
*/
public int $PrevPps;
/**
* The index of the next PPS.
*/
public int $NextPps;
/**
* The index of it's first child if this is a Dir or Root PPS.
*/
public int $DirPps;
/**
* A timestamp.
*/
public float|int $Time1st;
/**
* A timestamp.
*/
public float|int $Time2nd;
/**
* Starting block (small or big) for this PPS's data inside the container.
*/
public ?int $startBlock = null;
/**
* The size of the PPS's data (in bytes).
*/
public int $Size;
/**
* The PPS's data (only used if it's not using a temporary file).
*/
public string $_data = '';
/**
* Array of child PPS's (only used by Root and Dir PPS's).
*
* @var mixed[]
*/
public array $children = [];
/**
* Pointer to OLE container.
*/
public OLE $ole;
/**
* The constructor.
*
* @param ?int $No The PPS index
* @param ?string $name The PPS name
* @param ?int $type The PPS type. Dir, Root or File
* @param ?int $prev The index of the previous PPS
* @param ?int $next The index of the next PPS
* @param ?int $dir The index of it's first child if this is a Dir or Root PPS
* @param null|float|int $time_1st A timestamp
* @param null|float|int $time_2nd A timestamp
* @param ?string $data The (usually binary) source data of the PPS
* @param mixed[] $children Array containing children PPS for this PPS
*/
public function __construct(?int $No, ?string $name, ?int $type, ?int $prev, ?int $next, ?int $dir, $time_1st, $time_2nd, ?string $data, array $children)
{
$this->No = (int) $No;
$this->Name = (string) $name;
$this->Type = (int) $type;
$this->PrevPps = (int) $prev;
$this->NextPps = (int) $next;
$this->DirPps = (int) $dir;
$this->Time1st = $time_1st ?? 0;
$this->Time2nd = $time_2nd ?? 0;
$this->_data = (string) $data;
$this->children = $children;
$this->Size = strlen((string) $data);
}
/**
* Returns the amount of data saved for this PPS.
*
* @return int The amount of data (in bytes)
*/
public function getDataLen(): int
{
//if (!isset($this->_data)) {
// return 0;
//}
return strlen($this->_data);
}
/**
* Returns a string with the PPS's WK (What is a WK?).
*
* @return string The binary string
*/
public function getPpsWk(): string
{
$ret = str_pad($this->Name, 64, "\x00");
$ret .= pack('v', strlen($this->Name) + 2) // 66
. pack('c', $this->Type) // 67
. pack('c', 0x00) //UK // 68
. pack('V', $this->PrevPps) //Prev // 72
. pack('V', $this->NextPps) //Next // 76
. pack('V', $this->DirPps) //Dir // 80
. "\x00\x09\x02\x00" // 84
. "\x00\x00\x00\x00" // 88
. "\xc0\x00\x00\x00" // 92
. "\x00\x00\x00\x46" // 96 // Seems to be ok only for Root
. "\x00\x00\x00\x00" // 100
. OLE::localDateToOLE($this->Time1st) // 108
. OLE::localDateToOLE($this->Time2nd) // 116
. pack('V', $this->startBlock ?? 0) // 120
. pack('V', $this->Size) // 124
. pack('V', 0); // 128
return $ret;
}
/**
* Updates index and pointers to previous, next and children PPS's for this
* PPS. I don't think it'll work with Dir PPS's.
*
* @param self[] $raList Reference to the array of PPS's for the whole OLE
* container
*
* @return int The index for this PPS
*/
public static function savePpsSetPnt(array &$raList, mixed $to_save, int $depth = 0): int
{
if (!is_array($to_save) || (empty($to_save))) {
return self::ALL_ONE_BITS;
}
/** @var self[] $to_save */
if (count($to_save) == 1) {
$cnt = count($raList);
// If the first entry, it's the root... Don't clone it!
$raList[$cnt] = ($depth == 0) ? $to_save[0] : clone $to_save[0];
$raList[$cnt]->No = $cnt;
$raList[$cnt]->PrevPps = self::ALL_ONE_BITS;
$raList[$cnt]->NextPps = self::ALL_ONE_BITS;
$raList[$cnt]->DirPps = self::savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++);
} else {
$iPos = (int) floor(count($to_save) / 2);
$aPrev = array_slice($to_save, 0, $iPos);
$aNext = array_slice($to_save, $iPos + 1);
$cnt = count($raList);
// If the first entry, it's the root... Don't clone it!
$raList[$cnt] = ($depth == 0) ? $to_save[$iPos] : clone $to_save[$iPos];
$raList[$cnt]->No = $cnt;
$raList[$cnt]->PrevPps = self::savePpsSetPnt($raList, $aPrev, $depth++);
$raList[$cnt]->NextPps = self::savePpsSetPnt($raList, $aNext, $depth++);
$raList[$cnt]->DirPps = self::savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++);
}
return $cnt;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php | src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\OLE;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Shared\OLE;
class ChainedBlockStream
{
/** @var mixed */
public $context;
/**
* The OLE container of the file that is being read.
*/
public ?OLE $ole = null;
/**
* Parameters specified by fopen().
*
* @var mixed[]
*/
public array $params = [];
/**
* The binary data of the file.
*/
public string $data;
/**
* The file pointer.
*
* @var int byte offset
*/
public int $pos = 0;
/**
* Implements support for fopen().
* For creating streams using this wrapper, use OLE_PPS_File::getStream().
*
* @param string $path resource name including scheme, e.g.
* ole-chainedblockstream://oleInstanceId=1
* @param string $mode only "r" is supported
* @param int $options mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH
* @param ?string $openedPath absolute path of the opened stream (out parameter)
*
* @return bool true on success
*/
public function stream_open(string $path, string $mode, int $options, ?string &$openedPath): bool // @codingStandardsIgnoreLine
{
if ($mode[0] !== 'r') {
if ($options & STREAM_REPORT_ERRORS) {
trigger_error('Only reading is supported', E_USER_WARNING);
}
return false;
}
// 25 is length of "ole-chainedblockstream://"
parse_str(substr($path, 25), $this->params);
if (!isset($this->params['oleInstanceId'], $this->params['blockId'], $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']])) { //* @phpstan-ignore-line
if ($options & STREAM_REPORT_ERRORS) {
trigger_error('OLE stream not found', E_USER_WARNING);
}
return false;
}
$this->ole = $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']]; //* @phpstan-ignore-line
if (!($this->ole instanceof OLE)) { //* @phpstan-ignore-line
throw new Exception('class is not OLE');
}
$blockId = $this->params['blockId'];
$this->data = '';
if (isset($this->params['size']) && $this->params['size'] < $this->ole->bigBlockThreshold && $blockId != $this->ole->root->startBlock) {
// Block id refers to small blocks
$rootPos = $this->ole->getBlockOffset((int) $this->ole->root->startBlock);
while ($blockId != -2) {
/** @var int $blockId */
$pos = $rootPos + $blockId * $this->ole->bigBlockSize;
$blockId = $this->ole->sbat[$blockId];
fseek($this->ole->_file_handle, $pos);
$this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize);
}
} else {
// Block id refers to big blocks
while ($blockId != -2) {
/** @var int $blockId */
$pos = $this->ole->getBlockOffset($blockId);
fseek($this->ole->_file_handle, $pos);
$this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize);
$blockId = $this->ole->bbat[$blockId];
}
}
if (isset($this->params['size'])) {
$this->data = substr($this->data, 0, $this->params['size']); //* @phpstan-ignore-line
}
if ($options & STREAM_USE_PATH) {
$openedPath = $path;
}
return true;
}
/**
* Implements support for fclose().
*/
public function stream_close(): void // @codingStandardsIgnoreLine
{
$this->ole = null;
unset($GLOBALS['_OLE_INSTANCES']);
}
/**
* Implements support for fread(), fgets() etc.
*
* @param int $count maximum number of bytes to read
*
* @return false|string
*/
public function stream_read(int $count): bool|string // @codingStandardsIgnoreLine
{
if ($this->stream_eof()) {
return false;
}
$s = substr($this->data, (int) $this->pos, $count);
$this->pos += $count;
return $s;
}
/**
* Implements support for feof().
*
* @return bool TRUE if the file pointer is at EOF; otherwise FALSE
*/
public function stream_eof(): bool // @codingStandardsIgnoreLine
{
return $this->pos >= strlen($this->data);
}
/**
* Returns the position of the file pointer, i.e. its offset into the file
* stream. Implements support for ftell().
*/
public function stream_tell(): int // @codingStandardsIgnoreLine
{
return $this->pos;
}
/**
* Implements support for fseek().
*
* @param int $offset byte offset
* @param int $whence SEEK_SET, SEEK_CUR or SEEK_END
*/
public function stream_seek(int $offset, int $whence): bool // @codingStandardsIgnoreLine
{
if ($whence == SEEK_SET && $offset >= 0) {
$this->pos = $offset;
} elseif ($whence == SEEK_CUR && -$offset <= $this->pos) {
$this->pos += $offset;
} elseif ($whence == SEEK_END && -$offset <= count($this->data)) { // @phpstan-ignore-line
$this->pos = strlen($this->data) + $offset;
} else {
return false;
}
return true;
}
/**
* Implements support for fstat(). Currently the only supported field is
* "size".
*
* @return array{size: int}
*/
public function stream_stat(): array // @codingStandardsIgnoreLine
{
return [
'size' => strlen($this->data),
];
}
// Methods used by stream_wrapper_register() that are not implemented:
// bool stream_flush ( void )
// int stream_write ( string data )
// bool rename ( string path_from, string path_to )
// bool mkdir ( string path, int mode, int options )
// bool rmdir ( string path, int options )
// bool dir_opendir ( string path, int options )
// array url_stat ( string path, int flags )
// string dir_readdir ( void )
// bool dir_rewinddir ( void )
// bool dir_closedir ( void )
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php | src/PhpSpreadsheet/Shared/OLE/PPS/Root.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\OLE\PPS;
// vim: set expandtab tabstop=4 shiftwidth=4:
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2002 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Xavier Noguer <xnoguer@php.net> |
// | Based on OLE::Storage_Lite by Kawai, Takanori |
// +----------------------------------------------------------------------+
//
use PhpOffice\PhpSpreadsheet\Shared\OLE;
use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS;
/**
* Class for creating Root PPS's for OLE containers.
*
* @author Xavier Noguer <xnoguer@php.net>
*/
class Root extends PPS
{
/**
* @var resource
*/
private $fileHandle;
private ?int $smallBlockSize = null;
private ?int $bigBlockSize = null;
/**
* @param null|float|int $time_1st A timestamp
* @param null|float|int $time_2nd A timestamp
* @param File[] $raChild
*/
public function __construct($time_1st, $time_2nd, array $raChild)
{
parent::__construct(null, OLE::ascToUcs('Root Entry'), OLE::OLE_PPS_TYPE_ROOT, null, null, null, $time_1st, $time_2nd, null, $raChild);
}
/**
* Method for saving the whole OLE container (including files).
* In fact, if called with an empty argument (or '-'), it saves to a
* temporary file and then outputs it's contents to stdout.
* If a resource pointer to a stream created by fopen() is passed
* it will be used, but you have to close such stream by yourself.
*
* @param resource $fileHandle the name of the file or stream where to save the OLE container
*
* @return bool true on success
*/
public function save($fileHandle): bool
{
$this->fileHandle = $fileHandle;
// Initial Setting for saving
$this->bigBlockSize = (int) (2 ** (
(isset($this->bigBlockSize)) ? self::adjust2($this->bigBlockSize) : 9
));
$this->smallBlockSize = (int) (2 ** (
(isset($this->smallBlockSize)) ? self::adjust2($this->smallBlockSize) : 6
));
// Make an array of PPS's (for Save)
$aList = [];
PPS::savePpsSetPnt($aList, [$this]);
// calculate values for header
[$iSBDcnt, $iBBcnt, $iPPScnt] = $this->calcSize($aList); //, $rhInfo);
// Save Header
$this->saveHeader((int) $iSBDcnt, (int) $iBBcnt, (int) $iPPScnt);
// Make Small Data string (write SBD)
$this->_data = $this->makeSmallData($aList);
// Write BB
$this->saveBigData((int) $iSBDcnt, $aList);
// Write PPS
$this->savePps($aList);
// Write Big Block Depot and BDList and Adding Header informations
$this->saveBbd((int) $iSBDcnt, (int) $iBBcnt, (int) $iPPScnt);
return true;
}
/**
* Calculate some numbers.
*
* @param PPS[] $raList Reference to an array of PPS's
*
* @return float[] The array of numbers
*/
private function calcSize(array &$raList): array
{
// Calculate Basic Setting
[$iSBDcnt, $iBBcnt, $iPPScnt] = [0, 0, 0];
$iSBcnt = 0;
$iCount = count($raList);
for ($i = 0; $i < $iCount; ++$i) {
if ($raList[$i]->Type == OLE::OLE_PPS_TYPE_FILE) {
$raList[$i]->Size = $raList[$i]->getDataLen();
if ($raList[$i]->Size < OLE::OLE_DATA_SIZE_SMALL) {
$iSBcnt += floor($raList[$i]->Size / $this->smallBlockSize)
+ (($raList[$i]->Size % $this->smallBlockSize) ? 1 : 0);
} else {
$iBBcnt += (floor($raList[$i]->Size / $this->bigBlockSize)
+ (($raList[$i]->Size % $this->bigBlockSize) ? 1 : 0));
}
}
}
$iSmallLen = $iSBcnt * $this->smallBlockSize;
$iSlCnt = floor($this->bigBlockSize / OLE::OLE_LONG_INT_SIZE);
$iSBDcnt = floor($iSBcnt / $iSlCnt) + (($iSBcnt % $iSlCnt) ? 1 : 0);
$iBBcnt += (floor($iSmallLen / $this->bigBlockSize)
+ (($iSmallLen % $this->bigBlockSize) ? 1 : 0));
$iCnt = count($raList);
$iBdCnt = $this->bigBlockSize / OLE::OLE_PPS_SIZE;
$iPPScnt = (floor($iCnt / $iBdCnt) + (($iCnt % $iBdCnt) ? 1 : 0));
return [$iSBDcnt, $iBBcnt, $iPPScnt];
}
/**
* Helper function for calculating a magic value for block sizes.
*
* @param int $i2 The argument
*
* @see save()
*/
private static function adjust2(int $i2): float
{
$iWk = log($i2) / log(2);
return ($iWk > floor($iWk)) ? floor($iWk) + 1 : $iWk;
}
/**
* Save OLE header.
*/
private function saveHeader(int $iSBDcnt, int $iBBcnt, int $iPPScnt): void
{
$FILE = $this->fileHandle;
// Calculate Basic Setting
$iBlCnt = $this->bigBlockSize / OLE::OLE_LONG_INT_SIZE;
$i1stBdL = ($this->bigBlockSize - 0x4C) / OLE::OLE_LONG_INT_SIZE;
$iBdExL = 0;
$iAll = $iBBcnt + $iPPScnt + $iSBDcnt;
$iAllW = $iAll;
$iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt) ? 1 : 0);
$iBdCnt = floor(($iAll + $iBdCntW) / $iBlCnt) + ((($iAllW + $iBdCntW) % $iBlCnt) ? 1 : 0);
// Calculate BD count
if ($iBdCnt > $i1stBdL) {
while (1) {
++$iBdExL;
++$iAllW;
$iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt) ? 1 : 0);
$iBdCnt = floor(($iAllW + $iBdCntW) / $iBlCnt) + ((($iAllW + $iBdCntW) % $iBlCnt) ? 1 : 0);
if ($iBdCnt <= ($iBdExL * $iBlCnt + $i1stBdL)) {
break;
}
}
}
// Save Header
fwrite(
$FILE,
"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1"
. "\x00\x00\x00\x00"
. "\x00\x00\x00\x00"
. "\x00\x00\x00\x00"
. "\x00\x00\x00\x00"
. pack('v', 0x3B)
. pack('v', 0x03)
. pack('v', -2)
. pack('v', 9)
. pack('v', 6)
. pack('v', 0)
. "\x00\x00\x00\x00"
. "\x00\x00\x00\x00"
. pack('V', $iBdCnt)
. pack('V', $iBBcnt + $iSBDcnt) //ROOT START
. pack('V', 0)
. pack('V', 0x1000)
. pack('V', $iSBDcnt ? 0 : -2) //Small Block Depot
. pack('V', $iSBDcnt)
);
// Extra BDList Start, Count
if ($iBdCnt < $i1stBdL) {
fwrite(
$FILE,
pack('V', -2) // Extra BDList Start
. pack('V', 0)// Extra BDList Count
);
} else {
fwrite($FILE, pack('V', $iAll + $iBdCnt) . pack('V', $iBdExL));
}
// BDList
for ($i = 0; $i < $i1stBdL && $i < $iBdCnt; ++$i) {
fwrite($FILE, pack('V', $iAll + $i));
}
if ($i < $i1stBdL) {
$jB = $i1stBdL - $i;
for ($j = 0; $j < $jB; ++$j) {
fwrite($FILE, (pack('V', -1)));
}
}
}
/**
* Saving big data (PPS's with data bigger than \PhpOffice\PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL).
*
* @param PPS[] $raList Reference to array of PPS's
*/
private function saveBigData(int $iStBlk, array &$raList): void
{
$FILE = $this->fileHandle;
// cycle through PPS's
$iCount = count($raList);
for ($i = 0; $i < $iCount; ++$i) {
if ($raList[$i]->Type != OLE::OLE_PPS_TYPE_DIR) {
$raList[$i]->Size = $raList[$i]->getDataLen();
if (($raList[$i]->Size >= OLE::OLE_DATA_SIZE_SMALL) || (($raList[$i]->Type == OLE::OLE_PPS_TYPE_ROOT) && isset($raList[$i]->_data))) {
fwrite($FILE, $raList[$i]->_data);
if ($raList[$i]->Size % $this->bigBlockSize) {
fwrite($FILE, str_repeat("\x00", $this->bigBlockSize - ($raList[$i]->Size % $this->bigBlockSize)));
}
// Set For PPS
$raList[$i]->startBlock = $iStBlk;
$iStBlk
+= ((int) floor($raList[$i]->Size / $this->bigBlockSize)
+ (($raList[$i]->Size % $this->bigBlockSize) ? 1 : 0));
}
}
}
}
/**
* get small data (PPS's with data smaller than \PhpOffice\PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL).
*
* @param PPS[] $raList Reference to array of PPS's
*/
private function makeSmallData(array &$raList): string
{
$sRes = '';
$FILE = $this->fileHandle;
$iSmBlk = 0;
$iCount = count($raList);
for ($i = 0; $i < $iCount; ++$i) {
// Make SBD, small data string
if ($raList[$i]->Type == OLE::OLE_PPS_TYPE_FILE) {
if ($raList[$i]->Size <= 0) {
continue;
}
if ($raList[$i]->Size < OLE::OLE_DATA_SIZE_SMALL) {
$iSmbCnt = (int) floor($raList[$i]->Size / $this->smallBlockSize)
+ (($raList[$i]->Size % $this->smallBlockSize) ? 1 : 0);
// Add to SBD
$jB = $iSmbCnt - 1;
for ($j = 0; $j < $jB; ++$j) {
fwrite($FILE, pack('V', $j + $iSmBlk + 1));
}
fwrite($FILE, pack('V', -2));
// Add to Data String(this will be written for RootEntry)
$sRes .= $raList[$i]->_data;
if ($raList[$i]->Size % $this->smallBlockSize) {
$sRes .= str_repeat("\x00", $this->smallBlockSize - ($raList[$i]->Size % $this->smallBlockSize));
}
// Set for PPS
$raList[$i]->startBlock = $iSmBlk;
$iSmBlk += $iSmbCnt;
}
}
}
$iSbCnt = floor($this->bigBlockSize / OLE::OLE_LONG_INT_SIZE);
if ($iSmBlk % $iSbCnt) {
$iB = $iSbCnt - ($iSmBlk % $iSbCnt);
for ($i = 0; $i < $iB; ++$i) {
fwrite($FILE, pack('V', -1));
}
}
return $sRes;
}
/**
* Saves all the PPS's WKs.
*
* @param PPS[] $raList Reference to an array with all PPS's
*/
private function savePps(array &$raList): void
{
// Save each PPS WK
$iC = count($raList);
for ($i = 0; $i < $iC; ++$i) {
fwrite($this->fileHandle, $raList[$i]->getPpsWk());
}
// Adjust for Block
$iCnt = count($raList);
$iBCnt = $this->bigBlockSize / OLE::OLE_PPS_SIZE;
if ($iCnt % $iBCnt) {
fwrite($this->fileHandle, str_repeat("\x00", ($iBCnt - ($iCnt % $iBCnt)) * OLE::OLE_PPS_SIZE));
}
}
/**
* Saving Big Block Depot.
*/
private function saveBbd(int $iSbdSize, int $iBsize, int $iPpsCnt): void
{
$FILE = $this->fileHandle;
// Calculate Basic Setting
$iBbCnt = $this->bigBlockSize / OLE::OLE_LONG_INT_SIZE;
$i1stBdL = ($this->bigBlockSize - 0x4C) / OLE::OLE_LONG_INT_SIZE;
$iBdExL = 0;
$iAll = $iBsize + $iPpsCnt + $iSbdSize;
$iAllW = $iAll;
$iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt) ? 1 : 0);
$iBdCnt = floor(($iAll + $iBdCntW) / $iBbCnt) + ((($iAllW + $iBdCntW) % $iBbCnt) ? 1 : 0);
// Calculate BD count
if ($iBdCnt > $i1stBdL) {
while (1) {
++$iBdExL;
++$iAllW;
$iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt) ? 1 : 0);
$iBdCnt = floor(($iAllW + $iBdCntW) / $iBbCnt) + ((($iAllW + $iBdCntW) % $iBbCnt) ? 1 : 0);
if ($iBdCnt <= ($iBdExL * $iBbCnt + $i1stBdL)) {
break;
}
}
}
// Making BD
// Set for SBD
if ($iSbdSize > 0) {
for ($i = 0; $i < ($iSbdSize - 1); ++$i) {
fwrite($FILE, pack('V', $i + 1));
}
fwrite($FILE, pack('V', -2));
}
// Set for B
for ($i = 0; $i < ($iBsize - 1); ++$i) {
fwrite($FILE, pack('V', $i + $iSbdSize + 1));
}
fwrite($FILE, pack('V', -2));
// Set for PPS
for ($i = 0; $i < ($iPpsCnt - 1); ++$i) {
fwrite($FILE, pack('V', $i + $iSbdSize + $iBsize + 1));
}
fwrite($FILE, pack('V', -2));
// Set for BBD itself ( 0xFFFFFFFD : BBD)
for ($i = 0; $i < $iBdCnt; ++$i) {
fwrite($FILE, pack('V', 0xFFFFFFFD));
}
// Set for ExtraBDList
for ($i = 0; $i < $iBdExL; ++$i) {
fwrite($FILE, pack('V', 0xFFFFFFFC));
}
// Adjust for Block
if (($iAllW + $iBdCnt) % $iBbCnt) {
$iBlock = ($iBbCnt - (($iAllW + $iBdCnt) % $iBbCnt));
for ($i = 0; $i < $iBlock; ++$i) {
fwrite($FILE, pack('V', -1));
}
}
// Extra BDList
if ($iBdCnt > $i1stBdL) {
$iN = 0;
$iNb = 0;
for ($i = $i1stBdL; $i < $iBdCnt; $i++, ++$iN) {
if ($iN >= ($iBbCnt - 1)) {
$iN = 0;
++$iNb;
fwrite($FILE, pack('V', $iAll + $iBdCnt + $iNb));
}
fwrite($FILE, pack('V', $iBsize + $iSbdSize + $iPpsCnt + $i));
}
if (($iBdCnt - $i1stBdL) % ($iBbCnt - 1)) {
$iB = ($iBbCnt - 1) - (($iBdCnt - $i1stBdL) % ($iBbCnt - 1));
for ($i = 0; $i < $iB; ++$i) {
fwrite($FILE, pack('V', -1));
}
}
fwrite($FILE, pack('V', -2));
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/OLE/PPS/File.php | src/PhpSpreadsheet/Shared/OLE/PPS/File.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\OLE\PPS;
// vim: set expandtab tabstop=4 shiftwidth=4:
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2002 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Xavier Noguer <xnoguer@php.net> |
// | Based on OLE::Storage_Lite by Kawai, Takanori |
// +----------------------------------------------------------------------+
//
use PhpOffice\PhpSpreadsheet\Shared\OLE;
use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS;
/**
* Class for creating File PPS's for OLE containers.
*
* @author Xavier Noguer <xnoguer@php.net>
*/
class File extends PPS
{
/**
* The constructor.
*
* @param string $name The name of the file (in Unicode)
*
* @see OLE::ascToUcs()
*/
public function __construct(string $name)
{
parent::__construct(null, $name, OLE::OLE_PPS_TYPE_FILE, null, null, null, null, null, '', []);
}
/**
* Initialization method. Has to be called right after OLE_PPS_File().
*/
public function init(): bool
{
return true;
}
/**
* Append data to PPS.
*
* @param string $data The data to append
*/
public function append(string $data): void
{
$this->_data .= $data;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Escher/DgContainer.php | src/PhpSpreadsheet/Shared/Escher/DgContainer.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Escher;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer;
class DgContainer
{
/**
* Drawing index, 1-based.
*/
private ?int $dgId = null;
/**
* Last shape index in this drawing.
*/
private ?int $lastSpId = null;
private ?SpgrContainer $spgrContainer = null;
public function getDgId(): ?int
{
return $this->dgId;
}
public function setDgId(int $value): void
{
$this->dgId = $value;
}
public function getLastSpId(): ?int
{
return $this->lastSpId;
}
public function setLastSpId(int $value): void
{
$this->lastSpId = $value;
}
public function getSpgrContainer(): ?SpgrContainer
{
return $this->spgrContainer;
}
public function getSpgrContainerOrThrow(): SpgrContainer
{
if ($this->spgrContainer !== null) {
return $this->spgrContainer;
}
throw new SpreadsheetException('spgrContainer is unexpectedly null');
}
public function setSpgrContainer(SpgrContainer $spgrContainer): SpgrContainer
{
return $this->spgrContainer = $spgrContainer;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Escher/DggContainer.php | src/PhpSpreadsheet/Shared/Escher/DggContainer.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Escher;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
class DggContainer
{
/**
* Maximum shape index of all shapes in all drawings increased by one.
*/
private int $spIdMax;
/**
* Total number of drawings saved.
*/
private int $cDgSaved;
/**
* Total number of shapes saved (including group shapes).
*/
private int $cSpSaved;
/**
* BLIP Store Container.
*/
private ?DggContainer\BstoreContainer $bstoreContainer = null;
/**
* Array of options for the drawing group.
*
* @var mixed[]
*/
private array $OPT = [];
/**
* Array of identifier clusters containing information about the maximum shape identifiers.
*
* @var mixed[]
*/
private array $IDCLs = [];
/**
* Get maximum shape index of all shapes in all drawings (plus one).
*/
public function getSpIdMax(): int
{
return $this->spIdMax;
}
/**
* Set maximum shape index of all shapes in all drawings (plus one).
*/
public function setSpIdMax(int $value): void
{
$this->spIdMax = $value;
}
/**
* Get total number of drawings saved.
*/
public function getCDgSaved(): int
{
return $this->cDgSaved;
}
/**
* Set total number of drawings saved.
*/
public function setCDgSaved(int $value): void
{
$this->cDgSaved = $value;
}
/**
* Get total number of shapes saved (including group shapes).
*/
public function getCSpSaved(): int
{
return $this->cSpSaved;
}
/**
* Set total number of shapes saved (including group shapes).
*/
public function setCSpSaved(int $value): void
{
$this->cSpSaved = $value;
}
/**
* Get BLIP Store Container.
*/
public function getBstoreContainer(): ?DggContainer\BstoreContainer
{
return $this->bstoreContainer;
}
/**
* Get BLIP Store Container.
*/
public function getBstoreContainerOrThrow(): DggContainer\BstoreContainer
{
return $this->bstoreContainer ?? throw new SpreadsheetException('bstoreContainer is unexpectedly null');
}
/**
* Set BLIP Store Container.
*/
public function setBstoreContainer(DggContainer\BstoreContainer $bstoreContainer): void
{
$this->bstoreContainer = $bstoreContainer;
}
/**
* Set an option for the drawing group.
*
* @param int $property The number specifies the option
*/
public function setOPT(int $property, mixed $value): void
{
$this->OPT[$property] = $value;
}
/**
* Get an option for the drawing group.
*
* @param int $property The number specifies the option
*/
public function getOPT(int $property): mixed
{
if (isset($this->OPT[$property])) {
return $this->OPT[$property];
}
return null;
}
/**
* Get identifier clusters.
*
* @return mixed[]
*/
public function getIDCLs(): array
{
return $this->IDCLs;
}
/**
* Set identifier clusters. [<drawingId> => <max shape id>, ...].
*
* @param mixed[] $IDCLs
*/
public function setIDCLs(array $IDCLs): void
{
$this->IDCLs = $IDCLs;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php | src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer;
class BstoreContainer
{
/**
* BLIP Store Entries. Each of them holds one BLIP (Big Large Image or Picture).
*
* @var BstoreContainer\BSE[]
*/
private array $BSECollection = [];
/**
* Add a BLIP Store Entry.
*/
public function addBSE(BstoreContainer\BSE $BSE): void
{
$this->BSECollection[] = $BSE;
$BSE->setParent($this);
}
/**
* Get the collection of BLIP Store Entries.
*
* @return BstoreContainer\BSE[]
*/
public function getBSECollection(): array
{
return $this->BSECollection;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php | src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer;
class BSE
{
const BLIPTYPE_ERROR = 0x00;
const BLIPTYPE_UNKNOWN = 0x01;
const BLIPTYPE_EMF = 0x02;
const BLIPTYPE_WMF = 0x03;
const BLIPTYPE_PICT = 0x04;
const BLIPTYPE_JPEG = 0x05;
const BLIPTYPE_PNG = 0x06;
const BLIPTYPE_DIB = 0x07;
const BLIPTYPE_TIFF = 0x11;
const BLIPTYPE_CMYKJPEG = 0x12;
/**
* The parent BLIP Store Entry Container.
* Property is currently unused.
*/
private BstoreContainer $parent;
/**
* The BLIP (Big Large Image or Picture).
*/
private ?BSE\Blip $blip = null;
/**
* The BLIP type.
*/
private int $blipType;
/**
* Set parent BLIP Store Entry Container.
*/
public function setParent(BstoreContainer $parent): void
{
$this->parent = $parent;
}
public function getParent(): BstoreContainer
{
return $this->parent;
}
/**
* Get the BLIP.
*/
public function getBlip(): ?BSE\Blip
{
return $this->blip;
}
/**
* Set the BLIP.
*/
public function setBlip(BSE\Blip $blip): void
{
$this->blip = $blip;
$blip->setParent($this);
}
/**
* Get the BLIP type.
*/
public function getBlipType(): int
{
return $this->blipType;
}
/**
* Set the BLIP type.
*/
public function setBlipType(int $blipType): void
{
$this->blipType = $blipType;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php | src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE;
class Blip
{
/**
* The parent BSE.
*/
private BSE $parent;
/**
* Raw image data.
*/
private string $data;
/**
* Get the raw image data.
*/
public function getData(): string
{
return $this->data;
}
/**
* Set the raw image data.
*/
public function setData(string $data): void
{
$this->data = $data;
}
/**
* Set parent BSE.
*/
public function setParent(BSE $parent): void
{
$this->parent = $parent;
}
/**
* Get parent BSE.
*/
public function getParent(): BSE
{
return $this->parent;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php | src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer;
class SpgrContainer
{
/**
* Parent Shape Group Container.
*/
private ?self $parent = null;
/**
* Shape Container collection.
*
* @var mixed[]
*/
private array $children = [];
/**
* Set parent Shape Group Container.
*/
public function setParent(?self $parent): void
{
$this->parent = $parent;
}
/**
* Get the parent Shape Group Container if any.
*/
public function getParent(): ?self
{
return $this->parent;
}
/**
* Add a child. This will be either spgrContainer or spContainer.
*
* @param SpgrContainer|SpgrContainer\SpContainer $child child to be added
*/
public function addChild(mixed $child): void
{
$this->children[] = $child;
$child->setParent($this);
}
/**
* Get collection of Shape Containers.
*
* @return mixed[]
*/
public function getChildren(): array
{
return $this->children;
}
/**
* Recursively get all spContainers within this spgrContainer.
*
* @return SpgrContainer\SpContainer[]
*/
public function getAllSpContainers(): array
{
$allSpContainers = [];
foreach ($this->children as $child) {
if ($child instanceof self) {
$allSpContainers = array_merge($allSpContainers, $child->getAllSpContainers());
} else {
$allSpContainers[] = $child;
}
}
/** @var SpgrContainer\SpContainer[] $allSpContainers */
return $allSpContainers;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php | src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer;
class SpContainer
{
/**
* Parent Shape Group Container.
*/
private SpgrContainer $parent;
/**
* Is this a group shape?
*/
private bool $spgr = false;
/**
* Shape type.
*/
private int $spType;
/**
* Shape flag.
*/
private int $spFlag;
/**
* Shape index (usually group shape has index 0, and the rest: 1,2,3...).
*/
private int $spId;
/**
* Array of options.
*
* @var mixed[]
*/
private array $OPT = [];
/**
* Cell coordinates of upper-left corner of shape, e.g. 'A1'.
*/
private string $startCoordinates = '';
/**
* Horizontal offset of upper-left corner of shape measured in 1/1024 of column width.
*/
private int|float $startOffsetX;
/**
* Vertical offset of upper-left corner of shape measured in 1/256 of row height.
*/
private int|float $startOffsetY;
/**
* Cell coordinates of bottom-right corner of shape, e.g. 'B2'.
*/
private string $endCoordinates;
/**
* Horizontal offset of bottom-right corner of shape measured in 1/1024 of column width.
*/
private int|float $endOffsetX;
/**
* Vertical offset of bottom-right corner of shape measured in 1/256 of row height.
*/
private int|float $endOffsetY;
/**
* Set parent Shape Group Container.
*/
public function setParent(SpgrContainer $parent): void
{
$this->parent = $parent;
}
/**
* Get the parent Shape Group Container.
*/
public function getParent(): SpgrContainer
{
return $this->parent;
}
/**
* Set whether this is a group shape.
*/
public function setSpgr(bool $value): void
{
$this->spgr = $value;
}
/**
* Get whether this is a group shape.
*/
public function getSpgr(): bool
{
return $this->spgr;
}
/**
* Set the shape type.
*/
public function setSpType(int $value): void
{
$this->spType = $value;
}
/**
* Get the shape type.
*/
public function getSpType(): int
{
return $this->spType;
}
/**
* Set the shape flag.
*/
public function setSpFlag(int $value): void
{
$this->spFlag = $value;
}
/**
* Get the shape flag.
*/
public function getSpFlag(): int
{
return $this->spFlag;
}
/**
* Set the shape index.
*/
public function setSpId(int $value): void
{
$this->spId = $value;
}
/**
* Get the shape index.
*/
public function getSpId(): int
{
return $this->spId;
}
/**
* Set an option for the Shape Group Container.
*
* @param int $property The number specifies the option
*/
public function setOPT(int $property, mixed $value): void
{
$this->OPT[$property] = $value;
}
/**
* Get an option for the Shape Group Container.
*
* @param int $property The number specifies the option
*/
public function getOPT(int $property): mixed
{
return $this->OPT[$property] ?? null;
}
/**
* Get the collection of options.
*
* @return mixed[]
*/
public function getOPTCollection(): array
{
return $this->OPT;
}
/**
* Set cell coordinates of upper-left corner of shape.
*
* @param string $value eg: 'A1'
*/
public function setStartCoordinates(string $value): void
{
$this->startCoordinates = $value;
}
/**
* Get cell coordinates of upper-left corner of shape.
*/
public function getStartCoordinates(): string
{
return $this->startCoordinates;
}
/**
* Set offset in x-direction of upper-left corner of shape measured in 1/1024 of column width.
*/
public function setStartOffsetX(int|float $startOffsetX): void
{
$this->startOffsetX = $startOffsetX;
}
/**
* Get offset in x-direction of upper-left corner of shape measured in 1/1024 of column width.
*/
public function getStartOffsetX(): int|float
{
return $this->startOffsetX;
}
/**
* Set offset in y-direction of upper-left corner of shape measured in 1/256 of row height.
*/
public function setStartOffsetY(int|float $startOffsetY): void
{
$this->startOffsetY = $startOffsetY;
}
/**
* Get offset in y-direction of upper-left corner of shape measured in 1/256 of row height.
*/
public function getStartOffsetY(): int|float
{
return $this->startOffsetY;
}
/**
* Set cell coordinates of bottom-right corner of shape.
*
* @param string $value eg: 'A1'
*/
public function setEndCoordinates(string $value): void
{
$this->endCoordinates = $value;
}
/**
* Get cell coordinates of bottom-right corner of shape.
*/
public function getEndCoordinates(): string
{
return $this->endCoordinates;
}
/**
* Set offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width.
*/
public function setEndOffsetX(int|float $endOffsetX): void
{
$this->endOffsetX = $endOffsetX;
}
/**
* Get offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width.
*/
public function getEndOffsetX(): int|float
{
return $this->endOffsetX;
}
/**
* Set offset in y-direction of bottom-right corner of shape measured in 1/256 of row height.
*/
public function setEndOffsetY(int|float $endOffsetY): void
{
$this->endOffsetY = $endOffsetY;
}
/**
* Get offset in y-direction of bottom-right corner of shape measured in 1/256 of row height.
*/
public function getEndOffsetY(): int|float
{
return $this->endOffsetY;
}
/**
* Get the nesting level of this spContainer. This is the number of spgrContainers between this spContainer and
* the dgContainer. A value of 1 = immediately within first spgrContainer
* Higher nesting level occurs if and only if spContainer is part of a shape group.
*
* @return int Nesting level
*/
public function getNestingLevel(): int
{
$nestingLevel = 0;
$parent = $this->getParent();
while ($parent instanceof SpgrContainer) {
++$nestingLevel;
$parent = $parent->getParent();
}
return $nestingLevel;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php | src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Trend;
class ExponentialBestFit extends BestFit
{
/**
* Algorithm type to use for best-fit
* (Name of this Trend class).
*/
protected string $bestFitType = 'exponential';
/**
* Return the Y-Value for a specified value of X.
*
* @param float $xValue X-Value
*
* @return float Y-Value
*/
public function getValueOfYForX(float $xValue): float
{
return $this->getIntersect() * $this->getSlope() ** ($xValue - $this->xOffset);
}
/**
* Return the X-Value for a specified value of Y.
*
* @param float $yValue Y-Value
*
* @return float X-Value
*/
public function getValueOfXForY(float $yValue): float
{
return log(($yValue + $this->yOffset) / $this->getIntersect()) / log($this->getSlope());
}
/**
* Return the Equation of the best-fit line.
*
* @param int $dp Number of places of decimal precision to display
*/
public function getEquation(int $dp = 0): string
{
$slope = $this->getSlope($dp);
$intersect = $this->getIntersect($dp);
return 'Y = ' . $intersect . ' * ' . $slope . '^X';
}
/**
* Return the Slope of the line.
*
* @param int $dp Number of places of decimal precision to display
*/
public function getSlope(int $dp = 0): float
{
if ($dp != 0) {
return round(exp($this->slope), $dp);
}
return exp($this->slope);
}
/**
* Return the Value of X where it intersects Y = 0.
*
* @param int $dp Number of places of decimal precision to display
*/
public function getIntersect(int $dp = 0): float
{
if ($dp != 0) {
return round(exp($this->intersect), $dp);
}
return exp($this->intersect);
}
/**
* Execute the regression and calculate the goodness of fit for a set of X and Y data values.
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
*/
private function exponentialRegression(array $yValues, array $xValues, bool $const): void
{
$adjustedYValues = array_map(
fn ($value): float => ($value < 0.0) ? 0 - log(abs($value)) : log($value),
$yValues
);
$this->leastSquareFit($adjustedYValues, $xValues, $const);
}
/**
* Define the regression and calculate the goodness of fit for a set of X and Y data values.
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
*/
public function __construct(array $yValues, array $xValues = [], bool $const = true)
{
parent::__construct($yValues, $xValues);
if (!$this->error) {
$this->exponentialRegression($yValues, $xValues, (bool) $const);
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php | src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Trend;
class PowerBestFit extends BestFit
{
/**
* Algorithm type to use for best-fit
* (Name of this Trend class).
*/
protected string $bestFitType = 'power';
/**
* Return the Y-Value for a specified value of X.
*
* @param float $xValue X-Value
*
* @return float Y-Value
*/
public function getValueOfYForX(float $xValue): float
{
return $this->getIntersect() * ($xValue - $this->xOffset) ** $this->getSlope();
}
/**
* Return the X-Value for a specified value of Y.
*
* @param float $yValue Y-Value
*
* @return float X-Value
*/
public function getValueOfXForY(float $yValue): float
{
return (($yValue + $this->yOffset) / $this->getIntersect()) ** (1 / $this->getSlope());
}
/**
* Return the Equation of the best-fit line.
*
* @param int $dp Number of places of decimal precision to display
*/
public function getEquation(int $dp = 0): string
{
$slope = $this->getSlope($dp);
$intersect = $this->getIntersect($dp);
return 'Y = ' . $intersect . ' * X^' . $slope;
}
/**
* Return the Value of X where it intersects Y = 0.
*
* @param int $dp Number of places of decimal precision to display
*/
public function getIntersect(int $dp = 0): float
{
if ($dp != 0) {
return round(exp($this->intersect), $dp);
}
return exp($this->intersect);
}
/**
* Execute the regression and calculate the goodness of fit for a set of X and Y data values.
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
*/
private function powerRegression(array $yValues, array $xValues, bool $const): void
{
$adjustedYValues = array_map(
fn ($value): float => ($value < 0.0) ? 0 - log(abs($value)) : log($value),
$yValues
);
$adjustedXValues = array_map(
fn ($value): float => ($value < 0.0) ? 0 - log(abs($value)) : log($value),
$xValues
);
$this->leastSquareFit($adjustedYValues, $adjustedXValues, $const);
}
/**
* Define the regression and calculate the goodness of fit for a set of X and Y data values.
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
*/
public function __construct(array $yValues, array $xValues = [], bool $const = true)
{
parent::__construct($yValues, $xValues);
if (!$this->error) {
$this->powerRegression($yValues, $xValues, (bool) $const);
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php | src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Trend;
class LinearBestFit extends BestFit
{
/**
* Algorithm type to use for best-fit
* (Name of this Trend class).
*/
protected string $bestFitType = 'linear';
/**
* Return the Y-Value for a specified value of X.
*
* @param float $xValue X-Value
*
* @return float Y-Value
*/
public function getValueOfYForX(float $xValue): float
{
return $this->getIntersect() + $this->getSlope() * $xValue;
}
/**
* Return the X-Value for a specified value of Y.
*
* @param float $yValue Y-Value
*
* @return float X-Value
*/
public function getValueOfXForY(float $yValue): float
{
return ($yValue - $this->getIntersect()) / $this->getSlope();
}
/**
* Return the Equation of the best-fit line.
*
* @param int $dp Number of places of decimal precision to display
*/
public function getEquation(int $dp = 0): string
{
$slope = $this->getSlope($dp);
$intersect = $this->getIntersect($dp);
return 'Y = ' . $intersect . ' + ' . $slope . ' * X';
}
/**
* Execute the regression and calculate the goodness of fit for a set of X and Y data values.
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
*/
private function linearRegression(array $yValues, array $xValues, bool $const): void
{
$this->leastSquareFit($yValues, $xValues, $const);
}
/**
* Define the regression and calculate the goodness of fit for a set of X and Y data values.
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
*/
public function __construct(array $yValues, array $xValues = [], bool $const = true)
{
parent::__construct($yValues, $xValues);
if (!$this->error) {
$this->linearRegression($this->yValues, $this->xValues, (bool) $const);
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php | src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Trend;
use Matrix\Matrix;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
// Phpstan and Scrutinizer seem to have legitimate complaints.
// $this->slope is specified where an array is expected in several places.
// But it seems that it should always be float.
// This code is probably not exercised at all in unit tests.
// Private bool property $implemented is set to indicate
// whether this implementation is correct.
class PolynomialBestFit extends BestFit
{
/**
* Algorithm type to use for best-fit
* (Name of this Trend class).
*/
protected string $bestFitType = 'polynomial';
/**
* Polynomial order.
*/
protected int $order = 0;
private bool $implemented = false;
/**
* Return the order of this polynomial.
*/
public function getOrder(): int
{
return $this->order;
}
/**
* Return the Y-Value for a specified value of X.
*
* @param float $xValue X-Value
*
* @return float Y-Value
*/
public function getValueOfYForX(float $xValue): float
{
$retVal = $this->getIntersect();
$slope = $this->getSlope();
// Phpstan and Scrutinizer are both correct - getSlope returns float, not array.
// @phpstan-ignore-next-line
foreach ($slope as $key => $value) {
/** @var float $value */
if ($value != 0.0) {
/** @var int $key */
$retVal += $value * $xValue ** ($key + 1);
}
}
return $retVal;
}
/**
* Return the X-Value for a specified value of Y.
*
* @param float $yValue Y-Value
*
* @return float X-Value
*/
public function getValueOfXForY(float $yValue): float
{
return ($yValue - $this->getIntersect()) / $this->getSlope();
}
/**
* Return the Equation of the best-fit line.
*
* @param int $dp Number of places of decimal precision to display
*/
public function getEquation(int $dp = 0): string
{
$slope = $this->getSlope($dp);
$intersect = $this->getIntersect($dp);
$equation = 'Y = ' . $intersect;
// Phpstan and Scrutinizer are both correct - getSlope returns float, not array.
// @phpstan-ignore-next-line
foreach ($slope as $key => $value) {
/** @var float|int $value */
if ($value != 0.0) {
$equation .= ' + ' . $value . ' * X';
/** @var int $key */
if ($key > 0) {
$equation .= '^' . ($key + 1);
}
}
}
return $equation;
}
/**
* Return the Slope of the line.
*
* @param int $dp Number of places of decimal precision to display
*/
public function getSlope(int $dp = 0): float
{
if ($dp != 0) {
$coefficients = [];
//* @phpstan-ignore-next-line
foreach ($this->slope as $coefficient) {
/** @var float|int $coefficient */
$coefficients[] = round($coefficient, $dp);
}
// @phpstan-ignore-next-line
return $coefficients;
}
return $this->slope;
}
/** @return array<float|int> */
public function getCoefficients(int $dp = 0): array
{
// Phpstan and Scrutinizer are both correct - getSlope returns float, not array.
// @phpstan-ignore-next-line
return array_merge([$this->getIntersect($dp)], $this->getSlope($dp));
}
/**
* Execute the regression and calculate the goodness of fit for a set of X and Y data values.
*
* @param int $order Order of Polynomial for this regression
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
*/
private function polynomialRegression(int $order, array $yValues, array $xValues): void
{
// calculate sums
$x_sum = array_sum($xValues);
$y_sum = array_sum($yValues);
$xx_sum = $xy_sum = $yy_sum = 0;
for ($i = 0; $i < $this->valueCount; ++$i) {
$xy_sum += $xValues[$i] * $yValues[$i];
$xx_sum += $xValues[$i] * $xValues[$i];
$yy_sum += $yValues[$i] * $yValues[$i];
}
/*
* This routine uses logic from the PHP port of polyfit version 0.1
* written by Michael Bommarito and Paul Meagher
*
* The function fits a polynomial function of order $order through
* a series of x-y data points using least squares.
*
*/
$A = [];
$B = [];
for ($i = 0; $i < $this->valueCount; ++$i) {
for ($j = 0; $j <= $order; ++$j) {
$A[$i][$j] = $xValues[$i] ** $j;
}
}
for ($i = 0; $i < $this->valueCount; ++$i) {
$B[$i] = [$yValues[$i]];
}
$matrixA = new Matrix($A);
$matrixB = new Matrix($B);
$C = $matrixA->solve($matrixB);
$coefficients = [];
for ($i = 0; $i < $C->rows; ++$i) {
$r = $C->getValue($i + 1, 1); // row and column are origin-1
if (!is_numeric($r) || abs($r + 0) <= 10 ** (-9)) {
$r = 0;
} else {
$r += 0;
}
$coefficients[] = $r;
}
$this->intersect = (float) array_shift($coefficients);
// Phpstan is correct
//* @phpstan-ignore-next-line
$this->slope = $coefficients;
$this->calculateGoodnessOfFit($x_sum, $y_sum, $xx_sum, $yy_sum, $xy_sum, 0, 0, 0);
foreach ($this->xValues as $xKey => $xValue) {
$this->yBestFitValues[$xKey] = $this->getValueOfYForX($xValue);
}
}
/**
* Define the regression and calculate the goodness of fit for a set of X and Y data values.
*
* @param int $order Order of Polynomial for this regression
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
*/
public function __construct(int $order, array $yValues, array $xValues = [])
{
if (!$this->implemented) {
throw new SpreadsheetException('Polynomial Best Fit not yet implemented');
}
parent::__construct($yValues, $xValues);
if (!$this->error) {
if ($order < $this->valueCount) {
$this->bestFitType .= '_' . $order;
$this->order = $order;
$this->polynomialRegression($order, $yValues, $xValues);
if (($this->getGoodnessOfFit() < 0.0) || ($this->getGoodnessOfFit() > 1.0)) {
$this->error = true;
}
} else {
$this->error = true;
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php | src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Trend;
class LogarithmicBestFit extends BestFit
{
/**
* Algorithm type to use for best-fit
* (Name of this Trend class).
*/
protected string $bestFitType = 'logarithmic';
/**
* Return the Y-Value for a specified value of X.
*
* @param float $xValue X-Value
*
* @return float Y-Value
*/
public function getValueOfYForX(float $xValue): float
{
return $this->getIntersect() + $this->getSlope() * log($xValue - $this->xOffset);
}
/**
* Return the X-Value for a specified value of Y.
*
* @param float $yValue Y-Value
*
* @return float X-Value
*/
public function getValueOfXForY(float $yValue): float
{
return exp(($yValue - $this->getIntersect()) / $this->getSlope());
}
/**
* Return the Equation of the best-fit line.
*
* @param int $dp Number of places of decimal precision to display
*/
public function getEquation(int $dp = 0): string
{
$slope = $this->getSlope($dp);
$intersect = $this->getIntersect($dp);
return 'Y = ' . $slope . ' * log(' . $intersect . ' * X)';
}
/**
* Execute the regression and calculate the goodness of fit for a set of X and Y data values.
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
*/
private function logarithmicRegression(array $yValues, array $xValues, bool $const): void
{
$adjustedYValues = array_map(
fn ($value): float => ($value < 0.0) ? 0 - log(abs($value)) : log($value),
$yValues
);
$this->leastSquareFit($adjustedYValues, $xValues, $const);
}
/**
* Define the regression and calculate the goodness of fit for a set of X and Y data values.
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
*/
public function __construct(array $yValues, array $xValues = [], bool $const = true)
{
parent::__construct($yValues, $xValues);
if (!$this->error) {
$this->logarithmicRegression($yValues, $xValues, (bool) $const);
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Trend/BestFit.php | src/PhpSpreadsheet/Shared/Trend/BestFit.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Trend;
abstract class BestFit
{
/**
* Indicator flag for a calculation error.
*/
protected bool $error = false;
/**
* Algorithm type to use for best-fit.
*/
protected string $bestFitType = 'undetermined';
/**
* Number of entries in the sets of x- and y-value arrays.
*/
protected int $valueCount;
/**
* X-value dataseries of values.
*
* @var float[]
*/
protected array $xValues = [];
/**
* Y-value dataseries of values.
*
* @var float[]
*/
protected array $yValues = [];
/**
* Flag indicating whether values should be adjusted to Y=0.
*/
protected bool $adjustToZero = false;
/**
* Y-value series of best-fit values.
*
* @var float[]
*/
protected array $yBestFitValues = [];
protected float $goodnessOfFit = 1;
protected float $stdevOfResiduals = 0;
protected float $covariance = 0;
protected float $correlation = 0;
protected float $SSRegression = 0;
protected float $SSResiduals = 0;
protected float $DFResiduals = 0;
protected float $f = 0;
protected float $slope = 0;
protected float $slopeSE = 0;
protected float $intersect = 0;
protected float $intersectSE = 0;
protected float $xOffset = 0;
protected float $yOffset = 0;
public function getError(): bool
{
return $this->error;
}
public function getBestFitType(): string
{
return $this->bestFitType;
}
/**
* Return the Y-Value for a specified value of X.
*
* @param float $xValue X-Value
*
* @return float Y-Value
*/
abstract public function getValueOfYForX(float $xValue): float;
/**
* Return the X-Value for a specified value of Y.
*
* @param float $yValue Y-Value
*
* @return float X-Value
*/
abstract public function getValueOfXForY(float $yValue): float;
/**
* Return the original set of X-Values.
*
* @return float[] X-Values
*/
public function getXValues(): array
{
return $this->xValues;
}
/**
* Return the original set of Y-Values.
*
* @return float[] Y-Values
*/
public function getYValues(): array
{
return $this->yValues;
}
/**
* Return the Equation of the best-fit line.
*
* @param int $dp Number of places of decimal precision to display
*/
abstract public function getEquation(int $dp = 0): string;
/**
* Return the Slope of the line.
*
* @param int $dp Number of places of decimal precision to display
*/
public function getSlope(int $dp = 0): float
{
if ($dp != 0) {
return round($this->slope, $dp);
}
return $this->slope;
}
/**
* Return the standard error of the Slope.
*
* @param int $dp Number of places of decimal precision to display
*/
public function getSlopeSE(int $dp = 0): float
{
if ($dp != 0) {
return round($this->slopeSE, $dp);
}
return $this->slopeSE;
}
/**
* Return the Value of X where it intersects Y = 0.
*
* @param int $dp Number of places of decimal precision to display
*/
public function getIntersect(int $dp = 0): float
{
if ($dp != 0) {
return round($this->intersect, $dp);
}
return $this->intersect;
}
/**
* Return the standard error of the Intersect.
*
* @param int $dp Number of places of decimal precision to display
*/
public function getIntersectSE(int $dp = 0): float
{
if ($dp != 0) {
return round($this->intersectSE, $dp);
}
return $this->intersectSE;
}
/**
* Return the goodness of fit for this regression.
*
* @param int $dp Number of places of decimal precision to return
*/
public function getGoodnessOfFit(int $dp = 0): float
{
if ($dp != 0) {
return round($this->goodnessOfFit, $dp);
}
return $this->goodnessOfFit;
}
/**
* Return the goodness of fit for this regression.
*
* @param int $dp Number of places of decimal precision to return
*/
public function getGoodnessOfFitPercent(int $dp = 0): float
{
if ($dp != 0) {
return round($this->goodnessOfFit * 100, $dp);
}
return $this->goodnessOfFit * 100;
}
/**
* Return the standard deviation of the residuals for this regression.
*
* @param int $dp Number of places of decimal precision to return
*/
public function getStdevOfResiduals(int $dp = 0): float
{
if ($dp != 0) {
return round($this->stdevOfResiduals, $dp);
}
return $this->stdevOfResiduals;
}
/**
* @param int $dp Number of places of decimal precision to return
*/
public function getSSRegression(int $dp = 0): float
{
if ($dp != 0) {
return round($this->SSRegression, $dp);
}
return $this->SSRegression;
}
/**
* @param int $dp Number of places of decimal precision to return
*/
public function getSSResiduals(int $dp = 0): float
{
if ($dp != 0) {
return round($this->SSResiduals, $dp);
}
return $this->SSResiduals;
}
/**
* @param int $dp Number of places of decimal precision to return
*/
public function getDFResiduals(int $dp = 0): float
{
if ($dp != 0) {
return round($this->DFResiduals, $dp);
}
return $this->DFResiduals;
}
/**
* @param int $dp Number of places of decimal precision to return
*/
public function getF(int $dp = 0): float
{
if ($dp != 0) {
return round($this->f, $dp);
}
return $this->f;
}
/**
* @param int $dp Number of places of decimal precision to return
*/
public function getCovariance(int $dp = 0): float
{
if ($dp != 0) {
return round($this->covariance, $dp);
}
return $this->covariance;
}
/**
* @param int $dp Number of places of decimal precision to return
*/
public function getCorrelation(int $dp = 0): float
{
if ($dp != 0) {
return round($this->correlation, $dp);
}
return $this->correlation;
}
/**
* @return float[]
*/
public function getYBestFitValues(): array
{
return $this->yBestFitValues;
}
protected function calculateGoodnessOfFit(float $sumX, float $sumY, float $sumX2, float $sumY2, float $sumXY, float $meanX, float $meanY, bool|int $const): void
{
$SSres = $SScov = $SStot = $SSsex = 0.0;
foreach ($this->xValues as $xKey => $xValue) {
$bestFitY = $this->yBestFitValues[$xKey] = $this->getValueOfYForX($xValue);
$SSres += ($this->yValues[$xKey] - $bestFitY) * ($this->yValues[$xKey] - $bestFitY);
if ($const === true) {
$SStot += ($this->yValues[$xKey] - $meanY) * ($this->yValues[$xKey] - $meanY);
} else {
$SStot += $this->yValues[$xKey] * $this->yValues[$xKey];
}
$SScov += ($this->xValues[$xKey] - $meanX) * ($this->yValues[$xKey] - $meanY);
if ($const === true) {
$SSsex += ($this->xValues[$xKey] - $meanX) * ($this->xValues[$xKey] - $meanX);
} else {
$SSsex += $this->xValues[$xKey] * $this->xValues[$xKey];
}
}
$this->SSResiduals = $SSres;
$this->DFResiduals = $this->valueCount - 1 - ($const === true ? 1 : 0);
if ($this->DFResiduals == 0.0) {
$this->stdevOfResiduals = 0.0;
} else {
$this->stdevOfResiduals = sqrt($SSres / $this->DFResiduals);
}
if ($SStot == 0.0 || $SSres == $SStot) {
$this->goodnessOfFit = 1;
} else {
$this->goodnessOfFit = 1 - ($SSres / $SStot);
}
$this->SSRegression = $this->goodnessOfFit * $SStot;
$this->covariance = $SScov / $this->valueCount;
$this->correlation = ($this->valueCount * $sumXY - $sumX * $sumY) / sqrt(($this->valueCount * $sumX2 - $sumX ** 2) * ($this->valueCount * $sumY2 - $sumY ** 2));
$this->slopeSE = $this->stdevOfResiduals / sqrt($SSsex);
$this->intersectSE = $this->stdevOfResiduals * sqrt(1 / ($this->valueCount - ($sumX * $sumX) / $sumX2));
if ($this->SSResiduals != 0.0) {
if ($this->DFResiduals == 0.0) {
$this->f = 0.0;
} else {
$this->f = $this->SSRegression / ($this->SSResiduals / $this->DFResiduals);
}
} else {
if ($this->DFResiduals == 0.0) {
$this->f = 0.0;
} else {
$this->f = $this->SSRegression / $this->DFResiduals;
}
}
}
/**
* @param array<float|int> $values
*
* @return float|int
*/
private function sumSquares(array $values)
{
return array_sum(
array_map(
fn ($value): float|int => $value ** 2,
$values
)
);
}
/**
* @param float[] $yValues
* @param float[] $xValues
*/
protected function leastSquareFit(array $yValues, array $xValues, bool $const): void
{
// calculate sums
$sumValuesX = array_sum($xValues);
$sumValuesY = array_sum($yValues);
$meanValueX = $sumValuesX / $this->valueCount;
$meanValueY = $sumValuesY / $this->valueCount;
$sumSquaresX = $this->sumSquares($xValues);
$sumSquaresY = $this->sumSquares($yValues);
$mBase = $mDivisor = 0.0;
$xy_sum = 0.0;
for ($i = 0; $i < $this->valueCount; ++$i) {
$xy_sum += $xValues[$i] * $yValues[$i];
if ($const === true) {
$mBase += ($xValues[$i] - $meanValueX) * ($yValues[$i] - $meanValueY);
$mDivisor += ($xValues[$i] - $meanValueX) * ($xValues[$i] - $meanValueX);
} else {
$mBase += $xValues[$i] * $yValues[$i];
$mDivisor += $xValues[$i] * $xValues[$i];
}
}
// calculate slope
$this->slope = $mBase / $mDivisor;
// calculate intersect
$this->intersect = ($const === true) ? $meanValueY - ($this->slope * $meanValueX) : 0.0;
$this->calculateGoodnessOfFit($sumValuesX, $sumValuesY, $sumSquaresX, $sumSquaresY, $xy_sum, $meanValueX, $meanValueY, $const);
}
/**
* Define the regression.
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
*/
public function __construct(array $yValues, array $xValues = [])
{
// Calculate number of points
$yValueCount = count($yValues);
$xValueCount = count($xValues);
// Define X Values if necessary
if ($xValueCount === 0) {
$xValues = range(1.0, $yValueCount);
} elseif ($yValueCount !== $xValueCount) {
// Ensure both arrays of points are the same size
$this->error = true;
}
$this->valueCount = $yValueCount;
$this->xValues = $xValues;
$this->yValues = $yValues;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Shared/Trend/Trend.php | src/PhpSpreadsheet/Shared/Trend/Trend.php | <?php
namespace PhpOffice\PhpSpreadsheet\Shared\Trend;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
class Trend
{
const TREND_LINEAR = 'Linear';
const TREND_LOGARITHMIC = 'Logarithmic';
const TREND_EXPONENTIAL = 'Exponential';
const TREND_POWER = 'Power';
const TREND_POLYNOMIAL_2 = 'Polynomial_2';
const TREND_POLYNOMIAL_3 = 'Polynomial_3';
const TREND_POLYNOMIAL_4 = 'Polynomial_4';
const TREND_POLYNOMIAL_5 = 'Polynomial_5';
const TREND_POLYNOMIAL_6 = 'Polynomial_6';
const TREND_BEST_FIT = 'Bestfit';
const TREND_BEST_FIT_NO_POLY = 'Bestfit_no_Polynomials';
/**
* Names of the best-fit Trend analysis methods.
*/
private const TREND_TYPES = [
self::TREND_LINEAR,
self::TREND_LOGARITHMIC,
self::TREND_EXPONENTIAL,
self::TREND_POWER,
];
/**
* Names of the best-fit Trend polynomial orders.
*
* @var string[]
*/
private static array $trendTypePolynomialOrders = [
self::TREND_POLYNOMIAL_2,
self::TREND_POLYNOMIAL_3,
self::TREND_POLYNOMIAL_4,
self::TREND_POLYNOMIAL_5,
self::TREND_POLYNOMIAL_6,
];
/**
* Cached results for each method when trying to identify which provides the best fit.
*
* @var BestFit[]
*/
private static array $trendCache = [];
/**
* @param mixed[] $yValues
* @param mixed[] $xValues
*/
public static function calculate(string $trendType = self::TREND_BEST_FIT, array $yValues = [], array $xValues = [], bool $const = true): BestFit
{
// Calculate number of points in each dataset
/** @var float[] $xValues */
$nY = count($yValues);
/** @var float[] $xValues */
$nX = count($xValues);
// Define X Values if necessary
if ($nX === 0) {
$xValues = range(1, $nY);
} elseif ($nY !== $nX) {
// Ensure both arrays of points are the same size
throw new SpreadsheetException('Trend(): Number of elements in coordinate arrays do not match.');
}
$key = md5($trendType . $const . serialize($yValues) . serialize($xValues));
// Determine which Trend method has been requested
switch ($trendType) {
// Instantiate and return the class for the requested Trend method
case self::TREND_LINEAR:
case self::TREND_LOGARITHMIC:
case self::TREND_EXPONENTIAL:
case self::TREND_POWER:
if (!isset(self::$trendCache[$key])) {
/** @var float[] $yValues */
$className = '\PhpOffice\PhpSpreadsheet\Shared\Trend\\' . $trendType . 'BestFit';
/** @var float[] $xValues */
self::$trendCache[$key] = new $className($yValues, $xValues, $const);
}
return self::$trendCache[$key];
case self::TREND_POLYNOMIAL_2:
case self::TREND_POLYNOMIAL_3:
case self::TREND_POLYNOMIAL_4:
case self::TREND_POLYNOMIAL_5:
case self::TREND_POLYNOMIAL_6:
if (!isset(self::$trendCache[$key])) {
$order = (int) substr($trendType, -1);
/** @var float[] $yValues */
self::$trendCache[$key] = new PolynomialBestFit($order, $yValues, $xValues);
}
return self::$trendCache[$key];
case self::TREND_BEST_FIT:
case self::TREND_BEST_FIT_NO_POLY:
// If the request is to determine the best fit regression, then we test each Trend line in turn
// Start by generating an instance of each available Trend method
/** @var float[] $yValues */
$bestFit = [];
/** @var float[] $xValues */
$bestFitValue = [];
foreach (self::TREND_TYPES as $trendMethod) {
$className = '\PhpOffice\PhpSpreadsheet\Shared\Trend\\' . $trendMethod . 'BestFit';
$bestFit[$trendMethod] = new $className($yValues, $xValues, $const);
$bestFitValue[$trendMethod] = $bestFit[$trendMethod]->getGoodnessOfFit();
}
if ($trendType !== self::TREND_BEST_FIT_NO_POLY) {
foreach (self::$trendTypePolynomialOrders as $trendMethod) {
$order = (int) substr($trendMethod, -1);
$bestFit[$trendMethod] = new PolynomialBestFit($order, $yValues, $xValues);
if ($bestFit[$trendMethod]->getError()) {
unset($bestFit[$trendMethod]);
} else {
$bestFitValue[$trendMethod] = $bestFit[$trendMethod]->getGoodnessOfFit();
}
}
}
// Determine which of our Trend lines is the best fit, and then we return the instance of that Trend class
arsort($bestFitValue);
$bestFitType = key($bestFitValue);
return $bestFit[$bestFitType];
default:
throw new SpreadsheetException("Unknown trend type $trendType");
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/bootstrap.php | tests/bootstrap.php | <?php
declare(strict_types=1);
setlocale(LC_ALL, 'en_US.utf8');
ini_set('error_reporting', (string) E_ALL);
function phpunit10ErrorHandler(int $errno, string $errstr, string $filename, int $lineno): bool
{
$x = error_reporting() & $errno;
if (
in_array(
$errno,
[
E_DEPRECATED,
E_WARNING,
E_NOTICE,
E_USER_DEPRECATED,
E_USER_NOTICE,
E_USER_WARNING,
],
true
)
) {
if (0 === $x) {
return true; // message suppressed - stop error handling
}
throw new Exception("$errstr $filename $lineno");
}
return false; // continue error handling
}
set_error_handler('phpunit10ErrorHandler');
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/CustomWriter.php | tests/PhpSpreadsheetTests/CustomWriter.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Writer\Html as HtmlWriter;
// Used in IOFactoryRegister tests
class CustomWriter extends HtmlWriter
{
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/DefinedNameFormulaTest.php | tests/PhpSpreadsheetTests/DefinedNameFormulaTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\NamedFormula;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class DefinedNameFormulaTest extends TestCase
{
#[DataProvider('providerRangeOrFormula')]
public function testRangeOrFormula(string $value, bool $expectedResult): void
{
$actualResult = DefinedName::testIfFormula($value);
self::assertSame($expectedResult, $actualResult);
}
public function testAddDefinedNames(): void
{
$spreadSheet = new Spreadsheet();
$workSheet = $spreadSheet->getActiveSheet();
$definedNamesForTest = $this->providerRangeOrFormula();
foreach ($definedNamesForTest as $key => $definedNameData) {
/** @var array{string, bool} $definedNameData */
[$value] = $definedNameData;
$name = str_replace([' ', '-'], '_', $key);
$spreadSheet
->addDefinedName(
DefinedName::createInstance($name, $workSheet, $value)
);
}
$allDefinedNames = $spreadSheet->getDefinedNames();
self::assertCount(count($definedNamesForTest), $allDefinedNames);
}
public function testGetNamedRanges(): void
{
$spreadSheet = new Spreadsheet();
$workSheet = $spreadSheet->getActiveSheet();
$rangeOrFormula = [];
$definedNamesForTest = $this->providerRangeOrFormula();
foreach ($definedNamesForTest as $key => $definedNameData) {
/** @var array{string, bool} $definedNameData */
[$value, $isFormula] = $definedNameData;
$rangeOrFormula[] = !$isFormula;
$name = str_replace([' ', '-'], '_', $key);
$spreadSheet->addDefinedName(DefinedName::createInstance($name, $workSheet, $value));
}
$allNamedRanges = $spreadSheet->getNamedRanges();
self::assertCount(count(array_filter($rangeOrFormula)), $allNamedRanges);
}
public function testGetScopedNamedRange(): void
{
$rangeName = 'NAMED_RANGE';
$globalRangeValue = 'A1';
$localRangeValue = 'A2';
$spreadSheet = new Spreadsheet();
$workSheet = $spreadSheet->getActiveSheet();
$spreadSheet->addDefinedName(DefinedName::createInstance($rangeName, $workSheet, $globalRangeValue));
$spreadSheet->addDefinedName(DefinedName::createInstance($rangeName, $workSheet, $localRangeValue, true));
$localScopedRange = $spreadSheet->getNamedRange($rangeName, $workSheet);
self::assertNotNull($localScopedRange);
self::assertSame($localRangeValue, $localScopedRange->getValue());
}
public function testGetGlobalNamedRange(): void
{
$rangeName = 'NAMED_RANGE';
$globalRangeValue = 'A1';
$localRangeValue = 'A2';
$spreadSheet = new Spreadsheet();
$workSheet1 = $spreadSheet->getActiveSheet();
$spreadSheet->createSheet(1);
$workSheet2 = $spreadSheet->getSheet(1);
$spreadSheet->addDefinedName(DefinedName::createInstance($rangeName, $workSheet1, $globalRangeValue));
$spreadSheet->addDefinedName(DefinedName::createInstance($rangeName, $workSheet1, $localRangeValue, true));
$localScopedRange = $spreadSheet->getNamedRange($rangeName, $workSheet2);
self::assertNotNull($localScopedRange);
self::assertSame($globalRangeValue, $localScopedRange->getValue());
}
public function testGetNamedFormulae(): void
{
$spreadSheet = new Spreadsheet();
$workSheet = $spreadSheet->getActiveSheet();
$rangeOrFormula = [];
$definedNamesForTest = $this->providerRangeOrFormula();
foreach ($definedNamesForTest as $key => $definedNameData) {
/** @var array{string, bool} $definedNameData */
[$value, $isFormula] = $definedNameData;
$rangeOrFormula[] = $isFormula;
$name = str_replace([' ', '-'], '_', $key);
$spreadSheet->addDefinedName(DefinedName::createInstance($name, $workSheet, $value));
}
$allNamedFormulae = $spreadSheet->getNamedFormulae();
self::assertCount(count(array_filter($rangeOrFormula)), $allNamedFormulae);
}
public function testGetScopedNamedFormula(): void
{
$formulaName = 'GERMAN_VAT_RATE';
$globalFormulaValue = '=19.0%';
$localFormulaValue = '=16.0%';
$spreadSheet = new Spreadsheet();
$workSheet = $spreadSheet->getActiveSheet();
$spreadSheet->addDefinedName(DefinedName::createInstance($formulaName, $workSheet, $globalFormulaValue));
$spreadSheet->addDefinedName(DefinedName::createInstance($formulaName, $workSheet, $localFormulaValue, true));
$localScopedFormula = $spreadSheet->getNamedFormula($formulaName, $workSheet);
self::assertNotNull($localScopedFormula);
self::assertSame($localFormulaValue, $localScopedFormula->getValue());
}
public function testGetGlobalNamedFormula(): void
{
$formulaName = 'GERMAN_VAT_RATE';
$globalFormulaValue = '=19.0%';
$localFormulaValue = '=16.0%';
$spreadSheet = new Spreadsheet();
$workSheet1 = $spreadSheet->getActiveSheet();
$spreadSheet->createSheet(1);
$workSheet2 = $spreadSheet->getSheet(1);
$spreadSheet->addDefinedName(DefinedName::createInstance($formulaName, $workSheet1, $globalFormulaValue));
$spreadSheet->addDefinedName(DefinedName::createInstance($formulaName, $workSheet1, $localFormulaValue, true));
$localScopedFormula = $spreadSheet->getNamedFormula($formulaName, $workSheet2);
self::assertNotNull($localScopedFormula);
self::assertSame($globalFormulaValue, $localScopedFormula->getValue());
}
public static function providerRangeOrFormula(): array
{
return [
'simple range' => ['A1', false],
'simple absolute range' => ['$A$1', false],
'simple integer value' => ['42', true],
'simple float value' => ['12.5', true],
'simple string value' => ['"HELLO WORLD"', true],
'range with a worksheet name' => ['Sheet2!$A$1', false],
'range with a quoted worksheet name' => ["'Work Sheet #2'!\$A\$1:\$E\$1", false],
'range with a quoted worksheet name containing quotes' => ["'Mark''s WorkSheet'!\$A\$1:\$E\$1", false],
'range with a utf-8 worksheet name' => ['Γειά!$A$1', false],
'range with a quoted utf-8 worksheet name' => ["'Γειά σου Κόσμε'!\$A\$1", false],
'range with a quoted worksheet name with quotes in a formula' => ["'Mark''s WorkSheet'!\$A\$1+5", true],
'range with a quoted worksheet name in a formula' => ["5*'Work Sheet #2'!\$A\$1", true],
'multiple ranges with quoted worksheet names with quotes in a formula' => ["'Mark''s WorkSheet'!\$A\$1+'Mark''s WorkSheet'!\$B\$2", true],
'named range in a formula' => ['NAMED_RANGE_VALUE+12', true],
'named range and range' => ['NAMED_RANGE_VALUE_1,Sheet2!$A$1', false],
'range with quoted utf-8 worksheet name and a named range' => ["NAMED_RANGE_VALUE_1,'Γειά σου Κόσμε'!\$A\$1", false],
'composite named range' => ['NAMED_RANGE_VALUE_1,NAMED_RANGE_VALUE_2 NAMED_RANGE_VALUE_3', false],
'named ranges in a formula' => ['NAMED_RANGE_VALUE_1/NAMED_RANGE_VALUE_2', true],
'utf-8 named range' => ['Γειά', false],
'utf-8 named range in a formula' => ['2*Γειά', true],
'utf-8 named ranges' => ['Γειά,σου Κόσμε', false],
'utf-8 named ranges in a formula' => ['Здравствуй+мир', true],
];
}
public function testEmptyNamedFormula(): void
{
$this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class);
$spreadSheet = new Spreadsheet();
$workSheet1 = $spreadSheet->getActiveSheet();
new NamedFormula('namedformula', $workSheet1);
}
public function testChangeFormula(): void
{
$spreadSheet = new Spreadsheet();
$workSheet1 = $spreadSheet->getActiveSheet();
$namedFormula = new NamedFormula('namedformula', $workSheet1, '=1');
self::assertEquals('=1', $namedFormula->getFormula());
$namedFormula->setFormula('=2');
self::assertEquals('=2', $namedFormula->getFormula());
$namedFormula->setFormula('');
self::assertEquals('=2', $namedFormula->getFormula());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/ReferenceHelper4Test.php | tests/PhpSpreadsheetTests/ReferenceHelper4Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class ReferenceHelper4Test extends TestCase
{
#[\PHPUnit\Framework\Attributes\DataProvider('dataProvider')]
public function testIssue3907(string $expectedResult, string $settingsTitle, string $formula, string $dataTitle = 'DATA'): void
{
$spreadsheet = new Spreadsheet();
$dataSheet = $spreadsheet->getActiveSheet();
$dataSheet->setTitle($dataTitle);
$settingsSheet = $spreadsheet->createSheet();
$settingsSheet->setTitle($settingsTitle);
$settingsSheet->getCell('A1')->setValue(10);
$settingsSheet->getCell('B1')->setValue(20);
$dataSheet->getCell('A5')->setValue($formula);
$dataSheet->getCell('A2')->setValue(1);
$dataSheet->insertNewColumnBefore('A');
self::assertSame($expectedResult, $dataSheet->getCell('B5')->getValue());
$spreadsheet->disconnectWorksheets();
}
public static function dataProvider(): array
{
return [
["=SUM(B2, 'F1 (SETTINGS)'!A1:B1)", 'F1 (SETTINGS)', "=SUM(A2, 'F1 (SETTINGS)'!A1:B1)"],
["=SUM(B2, 'x F1 (SETTINGS)'!A1:B1)", 'x F1 (SETTINGS)', "=SUM(A2, 'x F1 (SETTINGS)'!A1:B1)"],
["=SUM(B2, 'DATA'!B1)", 'F1 (SETTINGS)', "=SUM(A2, 'DATA'!A1)"],
["=SUM(B2, 'DATA'!C1)", 'F1 (SETTINGS)', "=SUM(A2, 'data'!B1)"],
['=SUM(B2, DATA!D1)', 'F1 (SETTINGS)', '=SUM(A2, data!C1)'],
["=SUM(B2, 'DATA'!B1:C1)", 'F1 (SETTINGS)', "=SUM(A2, 'Data'!A1:B1)"],
['=SUM(B2, DATA!B1:C1)', 'F1 (SETTINGS)', '=SUM(A2, DAta!A1:B1)'],
["=SUM(B2, 'F1 Data'!C1)", 'F1 (SETTINGS)', "=SUM(A2, 'F1 Data'!B1)", 'F1 Data'],
["=SUM(B2, 'x F1 Data'!C1)", 'F1 (SETTINGS)', "=SUM(A2, 'x F1 Data'!B1)", 'x F1 Data'],
["=SUM(B2, 'x F1 Data'!C1)", 'F1 (SETTINGS)', "=SUM(A2, 'x F1 Data'!B1)", 'x F1 Data'],
["=SUM(B2, 'x F1 Data'!C1:D2)", 'F1 (SETTINGS)', "=SUM(A2, 'x F1 Data'!B1:C2)", 'x F1 Data'],
['=SUM(B2, definedname1A1)', 'F1 (SETTINGS)', '=SUM(A2, definedname1A1)', 'x F1 Data'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/CustomReader.php | tests/PhpSpreadsheetTests/CustomReader.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx as XlsxReader;
// Used in IOFactoryRegister tests
class CustomReader extends XlsxReader
{
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/ReferenceHelperTest.php | tests/PhpSpreadsheetTests/ReferenceHelperTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
use PhpOffice\PhpSpreadsheet\Comment;
use PhpOffice\PhpSpreadsheet\NamedFormula;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\TestCase;
class ReferenceHelperTest extends TestCase
{
public function testColumnSort(): void
{
$columnBase = $columnExpectedResult = [
'A', 'B', 'Z',
'AA', 'AB', 'AZ',
'BA', 'BB', 'BZ',
'ZA', 'ZB', 'ZZ',
'AAA', 'AAB', 'AAZ',
'ABA', 'ABB', 'ABZ',
'AZA', 'AZB', 'AZZ',
'BAA', 'BAB', 'BAZ',
'BBA', 'BBB', 'BBZ',
'BZA', 'BZB', 'BZZ',
];
shuffle($columnBase);
usort($columnBase, [ReferenceHelper::class, 'columnSort']);
foreach ($columnBase as $key => $value) {
self::assertEquals($columnExpectedResult[$key], $value);
}
}
public function testColumnReverseSort(): void
{
$columnBase = $columnExpectedResult = [
'A', 'B', 'Z',
'AA', 'AB', 'AZ',
'BA', 'BB', 'BZ',
'ZA', 'ZB', 'ZZ',
'AAA', 'AAB', 'AAZ',
'ABA', 'ABB', 'ABZ',
'AZA', 'AZB', 'AZZ',
'BAA', 'BAB', 'BAZ',
'BBA', 'BBB', 'BBZ',
'BZA', 'BZB', 'BZZ',
];
shuffle($columnBase);
$columnExpectedResult = array_reverse($columnExpectedResult);
usort($columnBase, [ReferenceHelper::class, 'columnReverseSort']);
foreach ($columnBase as $key => $value) {
self::assertEquals($columnExpectedResult[$key], $value);
}
}
public function testCellSort(): void
{
$cellBase = $columnExpectedResult = [
'A1', 'B1', 'AZB1',
'BBB1', 'BB2', 'BAB2',
'BZA2', 'Z3', 'AZA3',
'BZB3', 'AB5', 'AZ6',
'ABZ7', 'BA9', 'BZ9',
'AAA9', 'AAZ9', 'BA10',
'BZZ10', 'ZA11', 'AAB11',
'BBZ29', 'BAA32', 'ZZ43',
'AZZ43', 'BAZ67', 'ZB78',
'ABA121', 'ABB289', 'BBA544',
];
shuffle($cellBase);
usort($cellBase, [ReferenceHelper::class, 'cellSort']);
foreach ($cellBase as $key => $value) {
self::assertEquals($columnExpectedResult[$key], $value);
}
}
public function testCellReverseSort(): void
{
$cellBase = $columnExpectedResult = [
'BBA544', 'ABB289', 'ABA121',
'ZB78', 'BAZ67', 'AZZ43',
'ZZ43', 'BAA32', 'BBZ29',
'AAB11', 'ZA11', 'BZZ10',
'BA10', 'AAZ9', 'AAA9',
'BZ9', 'BA9', 'ABZ7',
'AZ6', 'AB5', 'BZB3',
'AZA3', 'Z3', 'BZA2',
'BAB2', 'BB2', 'BBB1',
'AZB1', 'B1', 'A1',
];
shuffle($cellBase);
usort($cellBase, [ReferenceHelper::class, 'cellReverseSort']);
foreach ($cellBase as $key => $value) {
self::assertEquals($columnExpectedResult[$key], $value);
}
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormulaUpdates')]
public function testUpdateFormula(string $formula, int $insertRows, int $insertColumns, string $worksheet, string $expectedResult): void
{
$referenceHelper = ReferenceHelper::getInstance();
$result = $referenceHelper->updateFormulaReferences($formula, 'A1', $insertRows, $insertColumns, $worksheet);
self::assertSame($expectedResult, $result);
}
public static function providerFormulaUpdates(): array
{
return require 'tests/data/ReferenceHelperFormulaUpdates.php';
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerMultipleWorksheetFormulaUpdates')]
public function testUpdateFormulaForMultipleWorksheets(string $formula, int $insertRows, int $insertColumns, string $expectedResult): void
{
$referenceHelper = ReferenceHelper::getInstance();
$result = $referenceHelper->updateFormulaReferencesAnyWorksheet($formula, $insertRows, $insertColumns);
self::assertSame($expectedResult, $result);
}
public static function providerMultipleWorksheetFormulaUpdates(): array
{
return require 'tests/data/ReferenceHelperFormulaUpdatesMultipleSheet.php';
}
public function testInsertNewBeforeRetainDataType(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cell = $sheet->getCell('A1');
$cell->setValueExplicit('+1', DataType::TYPE_STRING);
$oldDataType = $cell->getDataType();
$oldValue = $cell->getValue();
$sheet->insertNewRowBefore(1);
$newCell = $sheet->getCell('A2');
$newDataType = $newCell->getDataType();
$newValue = $newCell->getValue();
self::assertSame($oldValue, $newValue);
self::assertSame($oldDataType, $newDataType);
$spreadsheet->disconnectWorksheets();
}
public function testRemoveColumnShiftsCorrectColumnValueIntoRemovedColumnCoordinates(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([
['a1', 'b1', 'c1'],
['a2', 'b2', null],
]);
$cells = $sheet->toArray();
self::assertSame('a1', $cells[0][0]);
self::assertSame('b1', $cells[0][1]);
self::assertSame('c1', $cells[0][2]);
self::assertSame('a2', $cells[1][0]);
self::assertSame('b2', $cells[1][1]);
self::assertNull($cells[1][2]);
$sheet->removeColumn('B');
$cells = $sheet->toArray();
self::assertSame('a1', $cells[0][0]);
self::assertSame('c1', $cells[0][1]);
self::assertArrayNotHasKey(2, $cells[0]);
self::assertSame('a2', $cells[1][0]);
self::assertNull($cells[1][1]);
self::assertArrayNotHasKey(2, $cells[1]);
$spreadsheet->disconnectWorksheets();
}
public function testInsertRowsWithPageBreaks(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], null, 'A1', true);
$sheet->setBreak('A2', Worksheet::BREAK_ROW);
$sheet->setBreak('A5', Worksheet::BREAK_ROW);
$sheet->insertNewRowBefore(2, 2);
$breaks = $sheet->getBreaks();
ksort($breaks);
self::assertSame(['A4' => Worksheet::BREAK_ROW, 'A7' => Worksheet::BREAK_ROW], $breaks);
$spreadsheet->disconnectWorksheets();
}
public function testDeleteRowsWithPageBreaks(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], null, 'A1', true);
$sheet->setBreak('A2', Worksheet::BREAK_ROW);
$sheet->setBreak('A5', Worksheet::BREAK_ROW);
$sheet->removeRow(2, 2);
$breaks = $sheet->getBreaks();
self::assertSame(['A3' => Worksheet::BREAK_ROW], $breaks);
$spreadsheet->disconnectWorksheets();
}
public function testInsertRowsWithComments(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], null, 'A1', true);
$sheet->getComment('A2')->getText()->createText('First Comment');
$sheet->getComment('A5')->getText()->createText('Second Comment');
$sheet->insertNewRowBefore(2, 2);
$comments = array_map(
fn (Comment $value): string => $value->getText()->getPlainText(),
$sheet->getComments()
);
self::assertSame(['A4' => 'First Comment', 'A7' => 'Second Comment'], $comments);
$spreadsheet->disconnectWorksheets();
}
public function testDeleteRowsWithComments(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], null, 'A1', true);
$sheet->getComment('A2')->getText()->createText('First Comment');
$sheet->getComment('A5')->getText()->createText('Second Comment');
$sheet->removeRow(2, 2);
$comments = array_map(
fn (Comment $value): string => $value->getText()->getPlainText(),
$sheet->getComments()
);
self::assertSame(['A3' => 'Second Comment'], $comments);
$spreadsheet->disconnectWorksheets();
}
public function testInsertRowsWithHyperlinks(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], null, 'A1', true);
$sheet->getCell('A2')->getHyperlink()->setUrl('https://github.com/PHPOffice/PhpSpreadsheet');
$sheet->getCell('A5')->getHyperlink()->setUrl('https://phpspreadsheet.readthedocs.io/en/latest/');
$sheet->insertNewRowBefore(2, 2);
$hyperlinks = array_map(
fn (Hyperlink $value) => $value->getUrl(),
$sheet->getHyperlinkCollection()
);
ksort($hyperlinks);
self::assertSame(
[
'A4' => 'https://github.com/PHPOffice/PhpSpreadsheet',
'A7' => 'https://phpspreadsheet.readthedocs.io/en/latest/',
],
$hyperlinks
);
$spreadsheet->disconnectWorksheets();
}
public function testDeleteRowsWithHyperlinks(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], null, 'A1', true);
$sheet->getCell('A2')->getHyperlink()->setUrl('https://github.com/PHPOffice/PhpSpreadsheet');
$sheet->getCell('A5')->getHyperlink()->setUrl('https://phpspreadsheet.readthedocs.io/en/latest/');
$sheet->removeRow(2, 2);
$hyperlinks = array_map(
fn (Hyperlink $value) => $value->getUrl(),
$sheet->getHyperlinkCollection()
);
self::assertSame(['A3' => 'https://phpspreadsheet.readthedocs.io/en/latest/'], $hyperlinks);
$spreadsheet->disconnectWorksheets();
}
public function testInsertRowsWithConditionalFormatting(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([[1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8], [7, 8, 9, 10], [9, 10, 11, 12]], null, 'C3', true);
$sheet->getCell('H5')->setValue(5);
$cellRange = 'C3:F7';
$this->setConditionalFormatting($sheet, $cellRange);
$sheet->insertNewRowBefore(4, 2);
$styles = $sheet->getConditionalStylesCollection();
// verify that the conditional range has been updated
self::assertSame('C3:F9', array_keys($styles)[0]);
// verify that the conditions have been updated
foreach ($styles as $style) {
foreach ($style as $conditions) {
self::assertSame('$H$7', $conditions->getConditions()[0]);
}
}
$spreadsheet->disconnectWorksheets();
}
public function testInsertColumnssWithConditionalFormatting(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([[1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8], [7, 8, 9, 10], [9, 10, 11, 12]], null, 'C3', true);
$sheet->getCell('H5')->setValue(5);
$cellRange = 'C3:F7';
$this->setConditionalFormatting($sheet, $cellRange);
$sheet->insertNewColumnBefore('C', 2);
$styles = $sheet->getConditionalStylesCollection();
// verify that the conditional range has been updated
self::assertSame('E3:H7', array_keys($styles)[0]);
// verify that the conditions have been updated
foreach ($styles as $style) {
foreach ($style as $conditions) {
self::assertSame('$J$5', $conditions->getConditions()[0]);
}
}
$spreadsheet->disconnectWorksheets();
}
public function testDeleteRowsWithConditionalFormatting(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([[1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8], [7, 8, 9, 10], [9, 10, 11, 12]], null, 'C3', true);
$sheet->getCell('H5')->setValue(5);
$cellRange = 'C3:F7';
$this->setConditionalFormatting($sheet, $cellRange);
$sheet->removeRow(4, 2);
$styles = $sheet->getConditionalStylesCollection();
// verify that the conditional range has been updated
self::assertSame('C3:F5', array_keys($styles)[0]);
// verify that the conditions have been updated
foreach ($styles as $style) {
foreach ($style as $conditions) {
self::assertSame('$H$5', $conditions->getConditions()[0]);
}
}
$spreadsheet->disconnectWorksheets();
}
public function testDeleteColumnsWithConditionalFormatting(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([[1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8], [7, 8, 9, 10], [9, 10, 11, 12]], null, 'C3', true);
$sheet->getCell('H5')->setValue(5);
$cellRange = 'C3:F7';
$this->setConditionalFormatting($sheet, $cellRange);
$sheet->removeColumn('D', 2);
$styles = $sheet->getConditionalStylesCollection();
// verify that the conditional range has been updated
self::assertSame('C3:D7', array_keys($styles)[0]);
// verify that the conditions have been updated
foreach ($styles as $style) {
foreach ($style as $conditions) {
self::assertSame('$F$5', $conditions->getConditions()[0]);
}
}
$spreadsheet->disconnectWorksheets();
}
private function setConditionalFormatting(Worksheet $sheet, string $cellRange): void
{
$conditionalStyles = [];
$wizardFactory = new Wizard($cellRange);
/** @var Wizard\CellValue $cellWizard */
$cellWizard = $wizardFactory->newRule(Wizard::CELL_VALUE);
$cellWizard->equals('$H$5', Wizard::VALUE_TYPE_CELL);
$conditionalStyles[] = $cellWizard->getConditional();
$cellWizard->greaterThan('$H$5', Wizard::VALUE_TYPE_CELL);
$conditionalStyles[] = $cellWizard->getConditional();
$cellWizard->lessThan('$H$5', Wizard::VALUE_TYPE_CELL);
$conditionalStyles[] = $cellWizard->getConditional();
$sheet->getStyle($cellWizard->getCellRange())
->setConditionalStyles($conditionalStyles);
}
public function testInsertRowsWithPrintArea(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getPageSetup()->setPrintArea('A1:J10');
$sheet->insertNewRowBefore(2, 2);
$printArea = $sheet->getPageSetup()->getPrintArea();
self::assertSame('A1:J12', $printArea);
$spreadsheet->disconnectWorksheets();
}
public function testInsertColumnsWithPrintArea(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getPageSetup()->setPrintArea('A1:J10');
$sheet->insertNewColumnBefore('B', 2);
$printArea = $sheet->getPageSetup()->getPrintArea();
self::assertSame('A1:L10', $printArea);
$spreadsheet->disconnectWorksheets();
}
public function testDeleteRowsWithPrintArea(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getPageSetup()->setPrintArea('A1:J10');
$sheet->removeRow(2, 2);
$printArea = $sheet->getPageSetup()->getPrintArea();
self::assertSame('A1:J8', $printArea);
$spreadsheet->disconnectWorksheets();
}
public function testDeleteColumnsWithPrintArea(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getPageSetup()->setPrintArea('A1:J10');
$sheet->removeColumn('B', 2);
$printArea = $sheet->getPageSetup()->getPrintArea();
self::assertSame('A1:H10', $printArea);
$spreadsheet->disconnectWorksheets();
}
public function testInsertDeleteRowsWithDefinedNames(): void
{
$spreadsheet = $this->buildDefinedNamesTestWorkbook();
/** @var Worksheet $dataSheet */
$dataSheet = $spreadsheet->getSheetByName('Data');
/** @var Worksheet $totalsSheet */
$totalsSheet = $spreadsheet->getSheetByName('Totals');
/** @var NamedRange $firstColumn */
$firstColumn = $spreadsheet->getNamedRange('FirstColumn');
/** @var NamedRange $secondColumn */
$secondColumn = $spreadsheet->getNamedRange('SecondColumn');
$dataSheet->setCellValue('D2', '=FirstTotal');
$dataSheet->setCellValue('D3', '=FirstTotal');
$dataSheet->setCellValue('B2', '=SecondTotal');
$dataSheet->setCellValue('B3', '=SecondTotal');
$dataSheet->setCellValue('B4', '=ProductTotal');
$dataSheet->insertNewRowBefore(2, 5); // 5 rows before row 2
self::assertSame('=Data!$A$7:$A6', $firstColumn->getRange());
self::assertSame('=Data!B$7:B6', $secondColumn->getRange());
$dataSheet->removeRow(2, 1); // remove one of inserted rows
self::assertSame('=Data!$A$6:$A6', $firstColumn->getRange());
self::assertSame('=Data!B$6:B6', $secondColumn->getRange());
self::assertSame('=Data!$A$6:$A6', $firstColumn->getRange());
self::assertSame('=Data!B$6:B6', $secondColumn->getRange());
self::assertSame(42, $dataSheet->getCell('D6')->getCalculatedValue());
self::assertSame(56, $dataSheet->getCell('D7')->getCalculatedValue());
self::assertSame(36, $dataSheet->getCell('B6')->getCalculatedValue());
self::assertSame(49, $dataSheet->getCell('B7')->getCalculatedValue());
$totalsSheet->setCellValue('D6', '=FirstTotal');
$totalsSheet->setCellValue('D7', '=FirstTotal');
$totalsSheet->setCellValue('B6', '=SecondTotal');
$totalsSheet->setCellValue('B7', '=SecondTotal');
$totalsSheet->setCellValue('B8', '=ProductTotal');
self::assertSame($dataSheet->getCell('D6')->getCalculatedValue(), $totalsSheet->getCell('D6')->getCalculatedValue());
self::assertSame($dataSheet->getCell('D7')->getCalculatedValue(), $totalsSheet->getCell('D7')->getCalculatedValue());
self::assertSame($dataSheet->getCell('B6')->getCalculatedValue(), $totalsSheet->getCell('B6')->getCalculatedValue());
self::assertSame($dataSheet->getCell('B7')->getCalculatedValue(), $totalsSheet->getCell('B7')->getCalculatedValue());
self::assertSame(4608, $dataSheet->getCell('B8')->getCalculatedValue());
self::assertSame($dataSheet->getCell('B8')->getCalculatedValue(), $totalsSheet->getCell('B8')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public function testInsertDeleteColumnsWithDefinedNames(): void
{
$spreadsheet = $this->buildDefinedNamesTestWorkbook();
/** @var Worksheet $dataSheet */
$dataSheet = $spreadsheet->getSheetByName('Data');
/** @var Worksheet $totalsSheet */
$totalsSheet = $spreadsheet->getSheetByName('Totals');
/** @var NamedRange $firstColumn */
$firstColumn = $spreadsheet->getNamedRange('FirstColumn');
/** @var NamedRange $secondColumn */
$secondColumn = $spreadsheet->getNamedRange('SecondColumn');
$dataSheet->setCellValue('D2', '=FirstTotal');
$dataSheet->setCellValue('D3', '=FirstTotal');
$dataSheet->setCellValue('B2', '=SecondTotal');
$dataSheet->setCellValue('B3', '=SecondTotal');
$dataSheet->setCellValue('B4', '=ProductTotal');
$dataSheet->insertNewColumnBefore('A', 3);
self::assertSame('=Data!$D$2:$D6', $firstColumn->getRange());
self::assertSame('=Data!B$2:B6', $secondColumn->getRange());
$dataSheet->removeColumn('A');
self::assertSame('=Data!$C$2:$C6', $firstColumn->getRange());
self::assertSame('=Data!B$2:B6', $secondColumn->getRange());
self::assertSame(42, $dataSheet->getCell('F2')->getCalculatedValue());
self::assertSame(56, $dataSheet->getCell('F3')->getCalculatedValue());
self::assertSame(36, $dataSheet->getCell('D2')->getCalculatedValue());
self::assertSame(49, $dataSheet->getCell('D3')->getCalculatedValue());
$totalsSheet->setCellValue('B2', '=SecondTotal');
$totalsSheet->setCellValue('B3', '=SecondTotal');
self::assertSame(42, $totalsSheet->getCell('B2')->getCalculatedValue());
self::assertSame(56, $totalsSheet->getCell('B3')->getCalculatedValue());
self::assertSame(4608, $dataSheet->getCell('D4')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
private function buildDefinedNamesTestWorkbook(): Spreadsheet
{
$spreadsheet = new Spreadsheet();
$dataSheet = $spreadsheet->getActiveSheet();
$dataSheet->setTitle('Data');
$totalsSheet = $spreadsheet->addSheet(new Worksheet());
$totalsSheet->setTitle('Totals');
$spreadsheet->setActiveSheetIndexByName('Data');
$dataSheet->fromArray([['Column 1', 'Column 2'], [2, 1], [4, 3], [6, 5], [8, 7], [10, 9], [12, 11], [14, 13], [16, 15]], null, 'A1', true);
$dataSheet->insertNewColumnBefore('B', 1);
$spreadsheet->addNamedRange(
new NamedRange('FirstColumn', $spreadsheet->getActiveSheet(), '=Data!$A$2:$A6')
);
$spreadsheet->addNamedFormula(
new NamedFormula('FirstTotal', $spreadsheet->getActiveSheet(), '=SUM(FirstColumn)')
);
$spreadsheet->addNamedRange(
new NamedRange('SecondColumn', $spreadsheet->getActiveSheet(), '=Data!B$2:B6')
);
$spreadsheet->addNamedFormula(
new NamedFormula('SecondTotal', $spreadsheet->getActiveSheet(), '=SUM(SecondColumn)')
);
$spreadsheet->addNamedFormula(
new NamedFormula('ProductTotal', $spreadsheet->getActiveSheet(), '=FirstTotal*SecondTotal')
);
return $spreadsheet;
}
private function buildDefinedNamesAbsoluteWorkbook(): Spreadsheet
{
$spreadsheet = new Spreadsheet();
$dataSheet = $spreadsheet->getActiveSheet();
$dataSheet->setTitle('Data');
$totalsSheet = $spreadsheet->addSheet(new Worksheet());
$totalsSheet->setTitle('Totals');
$spreadsheet->setActiveSheetIndexByName('Data');
$dataSheet->fromArray([['Column 1', 'Column 2'], [2, 1], [4, 3], [6, 5], [8, 7], [10, 9], [12, 11], [14, 13], [16, 15]], null, 'A1', true);
$spreadsheet->addNamedRange(
new NamedRange('FirstColumn', $spreadsheet->getActiveSheet(), '=Data!$A$2:$A$6')
);
$spreadsheet->addNamedFormula(
new NamedFormula('FirstTotal', $spreadsheet->getActiveSheet(), '=SUM(FirstColumn)')
);
$totalsSheet->setCellValue('A20', '=FirstTotal');
$spreadsheet->addNamedRange(
new NamedRange('SecondColumn', $spreadsheet->getActiveSheet(), '=Data!$B$2:$B$6')
);
$spreadsheet->addNamedFormula(
new NamedFormula('SecondTotal', $spreadsheet->getActiveSheet(), '=SUM(SecondColumn)')
);
$totalsSheet->setCellValue('B20', '=SecondTotal');
$spreadsheet->addNamedFormula(
new NamedFormula('ProductTotal', $spreadsheet->getActiveSheet(), '=FirstTotal*SecondTotal')
);
$totalsSheet->setCellValue('D20', '=ProductTotal');
return $spreadsheet;
}
public function testInsertBothWithDefinedNamesAbsolute(): void
{
$spreadsheet = $this->buildDefinedNamesAbsoluteWorkbook();
/** @var Worksheet $dataSheet */
$dataSheet = $spreadsheet->getSheetByName('Data');
/** @var Worksheet $totalsSheet */
$totalsSheet = $spreadsheet->getSheetByName('Totals');
$dataSheet->setCellValue('C2', '=FirstTotal');
$dataSheet->setCellValue('C3', '=FirstTotal');
$dataSheet->setCellValue('C4', '=SecondTotal');
$dataSheet->insertNewColumnBefore('A', 2);
$dataSheet->insertNewRowBefore(2, 4); // 4 rows before row 2
/** @var NamedRange $firstColumn */
$firstColumn = $spreadsheet->getNamedRange('FirstColumn');
/** @var NamedRange $secondColumn */
$secondColumn = $spreadsheet->getNamedRange('SecondColumn');
self::assertSame('=Data!$C$6:$C$10', $firstColumn->getRange());
self::assertSame('=Data!$D$6:$D$10', $secondColumn->getRange());
self::assertSame(30, $totalsSheet->getCell('A20')->getCalculatedValue());
self::assertSame(25, $totalsSheet->getCell('B20')->getCalculatedValue());
self::assertSame(750, $totalsSheet->getCell('D20')->getCalculatedValue());
self::assertSame(30, $dataSheet->getCell('E6')->getCalculatedValue());
self::assertSame(30, $dataSheet->getCell('E7')->getCalculatedValue());
self::assertSame(25, $dataSheet->getCell('E8')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.