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/Reader/Ods/DefinedNames.php | src/PhpSpreadsheet/Reader/Ods/DefinedNames.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Ods;
use DOMElement;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class DefinedNames extends BaseLoader
{
public function read(DOMElement $workbookData): void
{
$this->readDefinedRanges($workbookData);
$this->readDefinedExpressions($workbookData);
}
/**
* Read any Named Ranges that are defined in this spreadsheet.
*/
protected function readDefinedRanges(DOMElement $workbookData): void
{
$namedRanges = $workbookData->getElementsByTagNameNS($this->tableNs, 'named-range');
foreach ($namedRanges as $definedNameElement) {
$definedName = $definedNameElement->getAttributeNS($this->tableNs, 'name');
$baseAddress = $definedNameElement->getAttributeNS($this->tableNs, 'base-cell-address');
$range = $definedNameElement->getAttributeNS($this->tableNs, 'cell-range-address');
/** @var non-empty-string $baseAddress */
$baseAddress = FormulaTranslator::convertToExcelAddressValue($baseAddress);
$range = FormulaTranslator::convertToExcelAddressValue($range);
$this->addDefinedName($baseAddress, $definedName, $range);
}
}
/**
* Read any Named Formulae that are defined in this spreadsheet.
*/
protected function readDefinedExpressions(DOMElement $workbookData): void
{
$namedExpressions = $workbookData->getElementsByTagNameNS($this->tableNs, 'named-expression');
foreach ($namedExpressions as $definedNameElement) {
$definedName = $definedNameElement->getAttributeNS($this->tableNs, 'name');
$baseAddress = $definedNameElement->getAttributeNS($this->tableNs, 'base-cell-address');
$expression = $definedNameElement->getAttributeNS($this->tableNs, 'expression');
/** @var non-empty-string $baseAddress */
$baseAddress = FormulaTranslator::convertToExcelAddressValue($baseAddress);
$expression = substr($expression, strpos($expression, ':=') + 1);
$expression = FormulaTranslator::convertToExcelFormulaValue($expression);
$this->addDefinedName($baseAddress, $definedName, $expression);
}
}
/**
* Assess scope and store the Defined Name.
*
* @param non-empty-string $baseAddress
*/
private function addDefinedName(string $baseAddress, string $definedName, string $value): void
{
[$sheetReference] = Worksheet::extractSheetTitle($baseAddress, true, true);
$worksheet = $this->spreadsheet->getSheetByName($sheetReference);
// Worksheet might still be null if we're only loading selected sheets rather than the full spreadsheet
if ($worksheet !== null) {
$this->spreadsheet->addDefinedName(DefinedName::createInstance((string) $definedName, $worksheet, $value));
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Ods/FormulaTranslator.php | src/PhpSpreadsheet/Reader/Ods/FormulaTranslator.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Ods;
use Composer\Pcre\Preg;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
class FormulaTranslator
{
private static function replaceQuotedPeriod(string $value): string
{
$value2 = '';
$quoted = false;
foreach (mb_str_split($value, 1, 'UTF-8') as $char) {
if ($char === "'") {
$quoted = !$quoted;
} elseif ($char === '.' && $quoted) {
$char = "\u{fffe}";
}
$value2 .= $char;
}
return $value2;
}
public static function convertToExcelAddressValue(string $openOfficeAddress): string
{
// Cell range 3-d reference
// As we don't support 3-d ranges, we're just going to take a quick and dirty approach
// and assume that the second worksheet reference is the same as the first
$excelAddress = Preg::replace(
[
'/\$?([^\.]+)\.([^\.]+):\$?([^\.]+)\.([^\.]+)/miu',
'/\$?([^\.]+)\.([^\.]+):\.([^\.]+)/miu', // Cell range reference in another sheet
'/\$?([^\.]+)\.([^\.]+)/miu', // Cell reference in another sheet
'/\.([^\.]+):\.([^\.]+)/miu', // Cell range reference
'/\.([^\.]+)/miu', // Simple cell reference
'/\x{FFFE}/miu', // restore quoted periods
],
[
'$1!$2:$4',
'$1!$2:$3',
'$1!$2',
'$1:$2',
'$1',
'.',
],
self::replaceQuotedPeriod($openOfficeAddress)
);
return $excelAddress;
}
public static function convertToExcelFormulaValue(string $openOfficeFormula): string
{
$temp = explode(Calculation::FORMULA_STRING_QUOTE, $openOfficeFormula);
$tKey = false;
$inMatrixBracesLevel = 0;
$inFunctionBracesLevel = 0;
foreach ($temp as &$value) {
// @var string $value
// Only replace in alternate array entries (i.e. non-quoted blocks)
// so that conversion isn't done in string values
$tKey = $tKey === false;
if ($tKey) {
$value = Preg::replace(
[
'/\[\$?([^\.]+)\.([^\.]+):\.([^\.]+)\]/miu', // Cell range reference in another sheet
'/\[\$?([^\.]+)\.([^\.]+)\]/miu', // Cell reference in another sheet
'/\[\.([^\.]+):\.([^\.]+)\]/miu', // Cell range reference
'/\[\.([^\.]+)\]/miu', // Simple cell reference
'/\x{FFFE}/miu', // restore quoted periods
],
[
'$1!$2:$3',
'$1!$2',
'$1:$2',
'$1',
'.',
],
self::replaceQuotedPeriod($value)
);
// Convert references to defined names/formulae
$value = str_replace('$$', '', $value);
// Convert ODS function argument separators to Excel function argument separators
$value = Calculation::translateSeparator(';', ',', $value, $inFunctionBracesLevel);
// Convert ODS matrix separators to Excel matrix separators
$value = Calculation::translateSeparator(
';',
',',
$value,
$inMatrixBracesLevel,
Calculation::FORMULA_OPEN_MATRIX_BRACE,
Calculation::FORMULA_CLOSE_MATRIX_BRACE
);
$value = Calculation::translateSeparator(
'|',
';',
$value,
$inMatrixBracesLevel,
Calculation::FORMULA_OPEN_MATRIX_BRACE,
Calculation::FORMULA_CLOSE_MATRIX_BRACE
);
$value = Preg::replace(
[
'/\b(?<!com[.]microsoft[.])'
. '(floor|ceiling)\s*[(]/ui',
'/COM\.MICROSOFT\./ui',
],
[
'$1.ODS(',
'',
],
$value
);
}
}
// Then rebuild the formula string
$excelFormula = implode('"', $temp);
return $excelFormula;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Csv/Delimiter.php | src/PhpSpreadsheet/Reader/Csv/Delimiter.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Csv;
class Delimiter
{
protected const POTENTIAL_DELIMITERS = [',', ';', "\t", '|', ':', ' ', '~'];
/** @var resource */
protected $fileHandle;
protected string $escapeCharacter;
protected string $enclosure;
/** @var array<string, int[]> */
protected array $counts = [];
protected int $numberLines = 0;
protected ?string $delimiter = null;
/**
* @param resource $fileHandle
*/
public function __construct($fileHandle, string $escapeCharacter, string $enclosure)
{
$this->fileHandle = $fileHandle;
$this->escapeCharacter = $escapeCharacter;
$this->enclosure = $enclosure;
$this->countPotentialDelimiters();
}
public function getDefaultDelimiter(): string
{
return self::POTENTIAL_DELIMITERS[0];
}
public function linesCounted(): int
{
return $this->numberLines;
}
protected function countPotentialDelimiters(): void
{
$this->counts = array_fill_keys(self::POTENTIAL_DELIMITERS, []);
$delimiterKeys = array_flip(self::POTENTIAL_DELIMITERS);
// Count how many times each of the potential delimiters appears in each line
$this->numberLines = 0;
while (($line = $this->getNextLine()) !== false && (++$this->numberLines < 1000)) {
$this->countDelimiterValues($line, $delimiterKeys);
}
}
/** @param array<string, int> $delimiterKeys */
protected function countDelimiterValues(string $line, array $delimiterKeys): void
{
$splitString = mb_str_split($line, 1, 'UTF-8');
$distribution = array_count_values($splitString);
$countLine = array_intersect_key($distribution, $delimiterKeys);
foreach (self::POTENTIAL_DELIMITERS as $delimiter) {
$this->counts[$delimiter][] = $countLine[$delimiter] ?? 0;
}
}
public function infer(): ?string
{
// Calculate the mean square deviations for each delimiter
// (ignoring delimiters that haven't been found consistently)
$meanSquareDeviations = [];
$middleIdx = (int) floor(($this->numberLines - 1) / 2);
foreach (self::POTENTIAL_DELIMITERS as $delimiter) {
$series = $this->counts[$delimiter];
sort($series);
$median = ($this->numberLines % 2)
? $series[$middleIdx]
: ($series[$middleIdx] + $series[$middleIdx + 1]) / 2;
if ($median === 0) {
continue;
}
$meanSquareDeviations[$delimiter] = array_reduce(
$series,
fn ($sum, $value): int|float => $sum + ($value - $median) ** 2
) / count($series);
}
// ... and pick the delimiter with the smallest mean square deviation
// (in case of ties, the order in potentialDelimiters is respected)
$min = INF;
foreach (self::POTENTIAL_DELIMITERS as $delimiter) {
if (!isset($meanSquareDeviations[$delimiter])) {
continue;
}
if ($meanSquareDeviations[$delimiter] < $min) {
$min = $meanSquareDeviations[$delimiter];
$this->delimiter = $delimiter;
}
}
return $this->delimiter;
}
/**
* Get the next full line from the file.
*
* @return false|string
*/
public function getNextLine()
{
$line = '';
$enclosure = ($this->escapeCharacter === '' ? ''
: ('(?<!' . preg_quote($this->escapeCharacter, '/') . ')'))
. preg_quote($this->enclosure, '/');
do {
// Get the next line in the file
$newLine = fgets($this->fileHandle);
// Return false if there is no next line
if ($newLine === false) {
return false;
}
// Add the new line to the line passed in
$line = $line . $newLine;
// Drop everything that is enclosed to avoid counting false positives in enclosures
$line = (string) preg_replace('/(' . $enclosure . '.*' . $enclosure . ')/Us', '', $line);
// See if we have any enclosures left in the line
// if we still have an enclosure then we need to read the next line as well
} while (preg_match('/(' . $enclosure . ')/', $line) > 0);
return ($line !== '') ? $line : false;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Gnumeric/Styles.php | src/PhpSpreadsheet/Reader/Gnumeric/Styles.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Gnumeric;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
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 SimpleXMLElement;
class Styles
{
private Spreadsheet $spreadsheet;
protected bool $readDataOnly;
/** @var array<string, string[]> */
public static array $mappings = [
'borderStyle' => [
'0' => Border::BORDER_NONE,
'1' => Border::BORDER_THIN,
'2' => Border::BORDER_MEDIUM,
'3' => Border::BORDER_SLANTDASHDOT,
'4' => Border::BORDER_DASHED,
'5' => Border::BORDER_THICK,
'6' => Border::BORDER_DOUBLE,
'7' => Border::BORDER_DOTTED,
'8' => Border::BORDER_MEDIUMDASHED,
'9' => Border::BORDER_DASHDOT,
'10' => Border::BORDER_MEDIUMDASHDOT,
'11' => Border::BORDER_DASHDOTDOT,
'12' => Border::BORDER_MEDIUMDASHDOTDOT,
'13' => Border::BORDER_MEDIUMDASHDOTDOT,
],
'fillType' => [
'1' => Fill::FILL_SOLID,
'2' => Fill::FILL_PATTERN_DARKGRAY,
'3' => Fill::FILL_PATTERN_MEDIUMGRAY,
'4' => Fill::FILL_PATTERN_LIGHTGRAY,
'5' => Fill::FILL_PATTERN_GRAY125,
'6' => Fill::FILL_PATTERN_GRAY0625,
'7' => Fill::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe
'8' => Fill::FILL_PATTERN_DARKVERTICAL, // vertical stripe
'9' => Fill::FILL_PATTERN_DARKDOWN, // diagonal stripe
'10' => Fill::FILL_PATTERN_DARKUP, // reverse diagonal stripe
'11' => Fill::FILL_PATTERN_DARKGRID, // diagonal crosshatch
'12' => Fill::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch
'13' => Fill::FILL_PATTERN_LIGHTHORIZONTAL,
'14' => Fill::FILL_PATTERN_LIGHTVERTICAL,
'15' => Fill::FILL_PATTERN_LIGHTUP,
'16' => Fill::FILL_PATTERN_LIGHTDOWN,
'17' => Fill::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch
'18' => Fill::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch
],
'horizontal' => [
'1' => Alignment::HORIZONTAL_GENERAL,
'2' => Alignment::HORIZONTAL_LEFT,
'4' => Alignment::HORIZONTAL_RIGHT,
'8' => Alignment::HORIZONTAL_CENTER,
'16' => Alignment::HORIZONTAL_CENTER_CONTINUOUS,
'32' => Alignment::HORIZONTAL_JUSTIFY,
'64' => Alignment::HORIZONTAL_CENTER_CONTINUOUS,
],
'underline' => [
'1' => Font::UNDERLINE_SINGLE,
'2' => Font::UNDERLINE_DOUBLE,
'3' => Font::UNDERLINE_SINGLEACCOUNTING,
'4' => Font::UNDERLINE_DOUBLEACCOUNTING,
],
'vertical' => [
'1' => Alignment::VERTICAL_TOP,
'2' => Alignment::VERTICAL_BOTTOM,
'4' => Alignment::VERTICAL_CENTER,
'8' => Alignment::VERTICAL_JUSTIFY,
],
];
public function __construct(Spreadsheet $spreadsheet, bool $readDataOnly)
{
$this->spreadsheet = $spreadsheet;
$this->readDataOnly = $readDataOnly;
}
public function read(SimpleXMLElement $sheet, int $maxRow, int $maxCol): void
{
if ($sheet->Styles->StyleRegion !== null) {
$this->readStyles($sheet->Styles->StyleRegion, $maxRow, $maxCol);
}
}
private function readStyles(SimpleXMLElement $styleRegion, int $maxRow, int $maxCol): void
{
foreach ($styleRegion as $style) {
$styleAttributes = $style->attributes();
if ($styleAttributes !== null && ($styleAttributes['startRow'] <= $maxRow) && ($styleAttributes['startCol'] <= $maxCol)) {
$cellRange = $this->readStyleRange($styleAttributes, $maxCol, $maxRow);
$styleAttributes = $style->Style->attributes();
/** @var mixed[][] */
$styleArray = [];
// We still set the number format mask for date/time values, even if readDataOnly is true
// so that we can identify whether a float is a float or a date value
$formatCode = $styleAttributes ? (string) $styleAttributes['Format'] : null;
if ($formatCode && Date::isDateTimeFormatCode($formatCode)) {
$styleArray['numberFormat']['formatCode'] = $formatCode;
}
if ($this->readDataOnly === false && $styleAttributes !== null) {
// If readDataOnly is false, we set all formatting information
$styleArray['numberFormat']['formatCode'] = $formatCode;
$styleArray = $this->readStyle($styleArray, $styleAttributes, $style);
}
/** @var mixed[][] $styleArray */
$this->spreadsheet
->getActiveSheet()
->getStyle($cellRange)
->applyFromArray($styleArray);
}
}
}
/** @param mixed[][] $styleArray */
private function addBorderDiagonal(SimpleXMLElement $srssb, array &$styleArray): void
{
if (isset($srssb->Diagonal, $srssb->{'Rev-Diagonal'})) {
$styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes());
$styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_BOTH;
} elseif (isset($srssb->Diagonal)) {
$styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes());
$styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_UP;
} elseif (isset($srssb->{'Rev-Diagonal'})) {
$styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->{'Rev-Diagonal'}->attributes());
$styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_DOWN;
}
}
/** @param mixed[][] $styleArray */
private function addBorderStyle(SimpleXMLElement $srssb, array &$styleArray, string $direction): void
{
$ucDirection = ucfirst($direction);
if (isset($srssb->$ucDirection)) {
/** @var SimpleXMLElement */
$temp = $srssb->$ucDirection;
$styleArray['borders'][$direction] = self::parseBorderAttributes($temp->attributes());
}
}
private function calcRotation(SimpleXMLElement $styleAttributes): int
{
$rotation = (int) $styleAttributes->Rotation;
if ($rotation >= 270 && $rotation <= 360) {
$rotation -= 360;
}
$rotation = (abs($rotation) > 90) ? 0 : $rotation;
return $rotation;
}
/** @param mixed[][] $styleArray */
private static function addStyle(array &$styleArray, string $key, string $value): void
{
if (array_key_exists($value, self::$mappings[$key])) {
$styleArray[$key] = self::$mappings[$key][$value]; //* @phpstan-ignore-line
}
}
/** @param mixed[][] $styleArray */
private static function addStyle2(array &$styleArray, string $key1, string $key, string $value): void
{
if (array_key_exists($value, self::$mappings[$key])) {
$styleArray[$key1][$key] = self::$mappings[$key][$value];
}
}
/** @return mixed[][] */
private static function parseBorderAttributes(?SimpleXMLElement $borderAttributes): array
{
/** @var mixed[][] */
$styleArray = [];
if ($borderAttributes !== null) {
if (isset($borderAttributes['Color'])) {
$styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes['Color']);
}
self::addStyle($styleArray, 'borderStyle', (string) $borderAttributes['Style']);
}
/** @var mixed[][] $styleArray */
return $styleArray;
}
private static function parseGnumericColour(string $gnmColour): string
{
[$gnmR, $gnmG, $gnmB] = explode(':', $gnmColour);
$gnmR = substr(str_pad($gnmR, 4, '0', STR_PAD_RIGHT), 0, 2);
$gnmG = substr(str_pad($gnmG, 4, '0', STR_PAD_RIGHT), 0, 2);
$gnmB = substr(str_pad($gnmB, 4, '0', STR_PAD_RIGHT), 0, 2);
return $gnmR . $gnmG . $gnmB;
}
/** @param mixed[][] $styleArray */
private function addColors(array &$styleArray, SimpleXMLElement $styleAttributes): void
{
$RGB = self::parseGnumericColour((string) $styleAttributes['Fore']);
/** @var mixed[][][] $styleArray */
$styleArray['font']['color']['rgb'] = $RGB;
$RGB = self::parseGnumericColour((string) $styleAttributes['Back']);
$shade = (string) $styleAttributes['Shade'];
if (($RGB !== '000000') || ($shade !== '0')) {
$RGB2 = self::parseGnumericColour((string) $styleAttributes['PatternColor']);
if ($shade === '1') {
$styleArray['fill']['startColor']['rgb'] = $RGB;
$styleArray['fill']['endColor']['rgb'] = $RGB2;
} else {
$styleArray['fill']['endColor']['rgb'] = $RGB;
$styleArray['fill']['startColor']['rgb'] = $RGB2;
}
self::addStyle2($styleArray, 'fill', 'fillType', $shade);
}
}
private function readStyleRange(SimpleXMLElement $styleAttributes, int $maxCol, int $maxRow): string
{
$startColumn = Coordinate::stringFromColumnIndex((int) $styleAttributes['startCol'] + 1);
$startRow = $styleAttributes['startRow'] + 1;
$endColumn = ($styleAttributes['endCol'] > $maxCol) ? $maxCol : (int) $styleAttributes['endCol'];
$endColumn = Coordinate::stringFromColumnIndex($endColumn + 1);
$endRow = 1 + (($styleAttributes['endRow'] > $maxRow) ? $maxRow : (int) $styleAttributes['endRow']);
$cellRange = $startColumn . $startRow . ':' . $endColumn . $endRow;
return $cellRange;
}
/**
* @param mixed[][] $styleArray
*
* @return mixed[]
*/
private function readStyle(array $styleArray, SimpleXMLElement $styleAttributes, SimpleXMLElement $style): array
{
self::addStyle2($styleArray, 'alignment', 'horizontal', (string) $styleAttributes['HAlign']);
self::addStyle2($styleArray, 'alignment', 'vertical', (string) $styleAttributes['VAlign']);
$styleArray['alignment']['wrapText'] = $styleAttributes['WrapText'] == '1';
$styleArray['alignment']['textRotation'] = $this->calcRotation($styleAttributes);
$styleArray['alignment']['shrinkToFit'] = $styleAttributes['ShrinkToFit'] == '1';
$styleArray['alignment']['indent'] = ((int) ($styleAttributes['Indent']) > 0) ? $styleAttributes['indent'] : 0;
$this->addColors($styleArray, $styleAttributes);
$fontAttributes = $style->Style->Font->attributes();
if ($fontAttributes !== null) {
$styleArray['font']['name'] = (string) $style->Style->Font;
$styleArray['font']['size'] = (int) ($fontAttributes['Unit']);
$styleArray['font']['bold'] = $fontAttributes['Bold'] == '1';
$styleArray['font']['italic'] = $fontAttributes['Italic'] == '1';
$styleArray['font']['strikethrough'] = $fontAttributes['StrikeThrough'] == '1';
self::addStyle2($styleArray, 'font', 'underline', (string) $fontAttributes['Underline']);
switch ($fontAttributes['Script']) {
case '1':
$styleArray['font']['superscript'] = true;
break;
case '-1':
$styleArray['font']['subscript'] = true;
break;
}
}
if (isset($style->Style->StyleBorder)) {
$srssb = $style->Style->StyleBorder;
$this->addBorderStyle($srssb, $styleArray, 'top');
$this->addBorderStyle($srssb, $styleArray, 'bottom');
$this->addBorderStyle($srssb, $styleArray, 'left');
$this->addBorderStyle($srssb, $styleArray, 'right');
$this->addBorderDiagonal($srssb, $styleArray);
}
// TO DO
/*
if (isset($style->Style->HyperLink)) {
$hyperlink = $style->Style->HyperLink->attributes();
}
*/
return $styleArray;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php | src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Gnumeric;
use PhpOffice\PhpSpreadsheet\Reader\Gnumeric;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\PageMargins;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup as WorksheetPageSetup;
use SimpleXMLElement;
class PageSetup
{
private Spreadsheet $spreadsheet;
public function __construct(Spreadsheet $spreadsheet)
{
$this->spreadsheet = $spreadsheet;
}
public function printInformation(SimpleXMLElement $sheet): self
{
if (isset($sheet->PrintInformation, $sheet->PrintInformation[0])) {
$printInformation = $sheet->PrintInformation[0];
$setup = $this->spreadsheet->getActiveSheet()->getPageSetup();
$attributes = $printInformation->Scale->attributes();
if (isset($attributes['percentage'])) {
$setup->setScale((int) $attributes['percentage']);
}
$pageOrder = (string) $printInformation->order;
if ($pageOrder === 'r_then_d') {
$setup->setPageOrder(WorksheetPageSetup::PAGEORDER_OVER_THEN_DOWN);
} elseif ($pageOrder === 'd_then_r') {
$setup->setPageOrder(WorksheetPageSetup::PAGEORDER_DOWN_THEN_OVER);
}
$orientation = (string) $printInformation->orientation;
if ($orientation !== '') {
$setup->setOrientation($orientation);
}
$attributes = $printInformation->hcenter->attributes();
if (isset($attributes['value'])) {
$setup->setHorizontalCentered((bool) (string) $attributes['value']);
}
$attributes = $printInformation->vcenter->attributes();
if (isset($attributes['value'])) {
$setup->setVerticalCentered((bool) (string) $attributes['value']);
}
}
return $this;
}
public function sheetMargins(SimpleXMLElement $sheet): self
{
if (isset($sheet->PrintInformation, $sheet->PrintInformation->Margins)) {
$marginSet = [
// Default Settings
'top' => 0.75,
'header' => 0.3,
'left' => 0.7,
'right' => 0.7,
'bottom' => 0.75,
'footer' => 0.3,
];
$marginSet = $this->buildMarginSet($sheet, $marginSet);
$this->adjustMargins($marginSet);
}
return $this;
}
/**
* @param float[] $marginSet
*
* @return float[]
*/
private function buildMarginSet(SimpleXMLElement $sheet, array $marginSet): array
{
foreach ($sheet->PrintInformation->Margins->children(Gnumeric::NAMESPACE_GNM) as $key => $margin) {
$marginAttributes = $margin->attributes();
$marginSize = ($marginAttributes['Points']) ?? 72; // Default is 72pt
// Convert value in points to inches
$marginSize = PageMargins::fromPoints((float) $marginSize);
$marginSet[$key] = $marginSize;
}
return $marginSet;
}
/** @param float[] $marginSet */
private function adjustMargins(array $marginSet): void
{
foreach ($marginSet as $key => $marginSize) {
// Gnumeric is quirky in the way it displays the header/footer values:
// header is actually the sum of top and header; footer is actually the sum of bottom and footer
// then top is actually the header value, and bottom is actually the footer value
switch ($key) {
case 'left':
case 'right':
$this->sheetMargin($key, $marginSize);
break;
case 'top':
$this->sheetMargin($key, $marginSet['header'] ?? 0);
break;
case 'bottom':
$this->sheetMargin($key, $marginSet['footer'] ?? 0);
break;
case 'header':
$this->sheetMargin($key, ($marginSet['top'] ?? 0) - $marginSize);
break;
case 'footer':
$this->sheetMargin($key, ($marginSet['bottom'] ?? 0) - $marginSize);
break;
}
}
}
private function sheetMargin(string $key, float $marginSize): void
{
switch ($key) {
case 'top':
$this->spreadsheet->getActiveSheet()->getPageMargins()->setTop($marginSize);
break;
case 'bottom':
$this->spreadsheet->getActiveSheet()->getPageMargins()->setBottom($marginSize);
break;
case 'left':
$this->spreadsheet->getActiveSheet()->getPageMargins()->setLeft($marginSize);
break;
case 'right':
$this->spreadsheet->getActiveSheet()->getPageMargins()->setRight($marginSize);
break;
case 'header':
$this->spreadsheet->getActiveSheet()->getPageMargins()->setHeader($marginSize);
break;
case 'footer':
$this->spreadsheet->getActiveSheet()->getPageMargins()->setFooter($marginSize);
break;
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Gnumeric/Properties.php | src/PhpSpreadsheet/Reader/Gnumeric/Properties.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Gnumeric;
use PhpOffice\PhpSpreadsheet\Reader\Gnumeric;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use SimpleXMLElement;
class Properties
{
protected Spreadsheet $spreadsheet;
public function __construct(Spreadsheet $spreadsheet)
{
$this->spreadsheet = $spreadsheet;
}
private function docPropertiesOld(SimpleXMLElement $gnmXML): void
{
$docProps = $this->spreadsheet->getProperties();
foreach ($gnmXML->Summary->Item as $summaryItem) {
$propertyName = $summaryItem->name;
$propertyValue = $summaryItem->{'val-string'};
switch ($propertyName) {
case 'title':
$docProps->setTitle(trim($propertyValue));
break;
case 'comments':
$docProps->setDescription(trim($propertyValue));
break;
case 'keywords':
$docProps->setKeywords(trim($propertyValue));
break;
case 'category':
$docProps->setCategory(trim($propertyValue));
break;
case 'manager':
$docProps->setManager(trim($propertyValue));
break;
case 'author':
$docProps->setCreator(trim($propertyValue));
$docProps->setLastModifiedBy(trim($propertyValue));
break;
case 'company':
$docProps->setCompany(trim($propertyValue));
break;
}
}
}
private function docPropertiesDC(SimpleXMLElement $officePropertyDC): void
{
$docProps = $this->spreadsheet->getProperties();
foreach ($officePropertyDC as $propertyName => $propertyValue) {
$propertyValue = trim((string) $propertyValue);
switch ($propertyName) {
case 'title':
$docProps->setTitle($propertyValue);
break;
case 'subject':
$docProps->setSubject($propertyValue);
break;
case 'creator':
$docProps->setCreator($propertyValue);
$docProps->setLastModifiedBy($propertyValue);
break;
case 'date':
$creationDate = $propertyValue;
$docProps->setModified($creationDate);
break;
case 'description':
$docProps->setDescription($propertyValue);
break;
}
}
}
private function docPropertiesMeta(SimpleXMLElement $officePropertyMeta): void
{
$docProps = $this->spreadsheet->getProperties();
foreach ($officePropertyMeta as $propertyName => $propertyValue) {
$attributes = $propertyValue->attributes(Gnumeric::NAMESPACE_META);
$propertyValue = trim((string) $propertyValue);
switch ($propertyName) {
case 'keyword':
$docProps->setKeywords($propertyValue);
break;
case 'initial-creator':
$docProps->setCreator($propertyValue);
$docProps->setLastModifiedBy($propertyValue);
break;
case 'creation-date':
$creationDate = $propertyValue;
$docProps->setCreated($creationDate);
break;
case 'user-defined':
if ($attributes) {
[, $attrName] = explode(':', (string) $attributes['name']);
$this->userDefinedProperties($attrName, $propertyValue);
}
break;
}
}
}
private function userDefinedProperties(string $attrName, string $propertyValue): void
{
$docProps = $this->spreadsheet->getProperties();
switch ($attrName) {
case 'publisher':
$docProps->setCompany($propertyValue);
break;
case 'category':
$docProps->setCategory($propertyValue);
break;
case 'manager':
$docProps->setManager($propertyValue);
break;
}
}
public function readProperties(SimpleXMLElement $xml, SimpleXMLElement $gnmXML): void
{
$officeXML = $xml->children(Gnumeric::NAMESPACE_OFFICE);
if (!empty($officeXML)) {
$officeDocXML = $officeXML->{'document-meta'};
$officeDocMetaXML = $officeDocXML->meta;
foreach ($officeDocMetaXML as $officePropertyData) {
$officePropertyDC = $officePropertyData->children(Gnumeric::NAMESPACE_DC);
$this->docPropertiesDC($officePropertyDC);
$officePropertyMeta = $officePropertyData->children(Gnumeric::NAMESPACE_META);
$this->docPropertiesMeta($officePropertyMeta);
}
} elseif (isset($gnmXML->Summary)) {
$this->docPropertiesOld($gnmXML);
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/Styles.php | src/PhpSpreadsheet/Reader/Xlsx/Styles.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Borders;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Font;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Protection;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Worksheet\Table\TableDxfsStyle;
use SimpleXMLElement;
use stdClass;
class Styles extends BaseParserClass
{
/**
* Theme instance.
*/
private ?Theme $theme = null;
/** @var string[] */
private array $workbookPalette = [];
/** @var mixed[] */
private array $styles = [];
/** @var array<SimpleXMLElement|stdClass> */
private array $cellStyles = [];
private SimpleXMLElement $styleXml;
private string $namespace = '';
/** @var array<string, int> */
private array $fontCharsets = [];
/** @return array<string, int> */
public function getFontCharsets(): array
{
return $this->fontCharsets;
}
public function setNamespace(string $namespace): void
{
$this->namespace = $namespace;
}
/** @param string[] $palette */
public function setWorkbookPalette(array $palette): void
{
$this->workbookPalette = $palette;
}
private function getStyleAttributes(SimpleXMLElement $value): SimpleXMLElement
{
$attr = $value->attributes('');
if ($attr === null || count($attr) === 0) {
$attr = $value->attributes($this->namespace);
}
return Xlsx::testSimpleXml($attr);
}
public function setStyleXml(SimpleXMLElement $styleXml): void
{
$this->styleXml = $styleXml;
}
public function setTheme(Theme $theme): void
{
$this->theme = $theme;
}
/**
* @param mixed[] $styles
* @param array<SimpleXMLElement|stdClass> $cellStyles
*/
public function setStyleBaseData(?Theme $theme = null, array $styles = [], array $cellStyles = []): void
{
$this->theme = $theme;
$this->styles = $styles;
$this->cellStyles = $cellStyles;
}
public function readFontStyle(Font $fontStyle, SimpleXMLElement $fontStyleXml): void
{
if (isset($fontStyleXml->name)) {
$attr = $this->getStyleAttributes($fontStyleXml->name);
if (isset($attr['val'])) {
$fontStyle->setName((string) $attr['val']);
}
if (isset($fontStyleXml->charset)) {
$charsetAttr = $this->getStyleAttributes($fontStyleXml->charset);
if (isset($charsetAttr['val'])) {
$charsetVal = (int) $charsetAttr['val'];
$this->fontCharsets[$fontStyle->getName()] = $charsetVal;
}
}
}
if (isset($fontStyleXml->sz)) {
$attr = $this->getStyleAttributes($fontStyleXml->sz);
if (isset($attr['val'])) {
$fontStyle->setSize((float) $attr['val']);
}
}
if (isset($fontStyleXml->b)) {
$attr = $this->getStyleAttributes($fontStyleXml->b);
$fontStyle->setBold(!isset($attr['val']) || self::boolean((string) $attr['val']));
}
if (isset($fontStyleXml->i)) {
$attr = $this->getStyleAttributes($fontStyleXml->i);
$fontStyle->setItalic(!isset($attr['val']) || self::boolean((string) $attr['val']));
}
if (isset($fontStyleXml->strike)) {
$attr = $this->getStyleAttributes($fontStyleXml->strike);
$fontStyle->setStrikethrough(!isset($attr['val']) || self::boolean((string) $attr['val']));
}
$fontStyle->getColor()
->setARGB(
$this->readColor($fontStyleXml->color)
);
$theme = $this->readColorTheme($fontStyleXml->color);
if ($theme >= 0) {
$fontStyle->getColor()->setTheme($theme);
}
if (isset($fontStyleXml->u)) {
$attr = $this->getStyleAttributes($fontStyleXml->u);
if (!isset($attr['val'])) {
$fontStyle->setUnderline(Font::UNDERLINE_SINGLE);
} else {
$fontStyle->setUnderline((string) $attr['val']);
}
}
if (isset($fontStyleXml->vertAlign)) {
$attr = $this->getStyleAttributes($fontStyleXml->vertAlign);
if (isset($attr['val'])) {
$verticalAlign = strtolower((string) $attr['val']);
if ($verticalAlign === 'superscript') {
$fontStyle->setSuperscript(true);
} elseif ($verticalAlign === 'subscript') {
$fontStyle->setSubscript(true);
}
}
}
if (isset($fontStyleXml->scheme)) {
$attr = $this->getStyleAttributes($fontStyleXml->scheme);
$fontStyle->setScheme((string) $attr['val']);
}
if (isset($fontStyleXml->auto)) {
$attr = $this->getStyleAttributes($fontStyleXml->auto);
if (isset($attr['val'])) {
$fontStyle->setAutoColor(self::boolean((string) $attr['val']));
}
}
}
private function readNumberFormat(NumberFormat $numfmtStyle, SimpleXMLElement $numfmtStyleXml): void
{
if ((string) $numfmtStyleXml['formatCode'] !== '') {
$numfmtStyle->setFormatCode(self::formatGeneral((string) $numfmtStyleXml['formatCode']));
return;
}
$numfmt = $this->getStyleAttributes($numfmtStyleXml);
if (isset($numfmt['formatCode'])) {
$numfmtStyle->setFormatCode(self::formatGeneral((string) $numfmt['formatCode']));
}
}
public function readFillStyle(Fill $fillStyle, SimpleXMLElement $fillStyleXml): void
{
if ($fillStyleXml->gradientFill) {
/** @var SimpleXMLElement $gradientFill */
$gradientFill = $fillStyleXml->gradientFill[0];
$attr = $this->getStyleAttributes($gradientFill);
if (!empty($attr['type'])) {
$fillStyle->setFillType((string) $attr['type']);
}
$fillStyle->setRotation((float) ($attr['degree']));
$gradientFill->registerXPathNamespace('sml', Namespaces::MAIN);
$fillStyle->getStartColor()->setARGB($this->readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color)); //* @phpstan-ignore-line
$fillStyle->getEndColor()->setARGB($this->readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color)); //* @phpstan-ignore-line
} elseif ($fillStyleXml->patternFill) {
$defaultFillStyle = ($fillStyle->getFillType() !== null) ? Fill::FILL_NONE : '';
$fgFound = false;
$bgFound = false;
if ($fillStyleXml->patternFill->fgColor) {
$fillStyle->getStartColor()->setARGB($this->readColor($fillStyleXml->patternFill->fgColor, true));
if ($fillStyle->getFillType() !== null) {
$defaultFillStyle = Fill::FILL_SOLID;
}
$fgFound = true;
}
if ($fillStyleXml->patternFill->bgColor) {
$fillStyle->getEndColor()->setARGB($this->readColor($fillStyleXml->patternFill->bgColor, true));
if ($fillStyle->getFillType() !== null) {
$defaultFillStyle = Fill::FILL_SOLID;
}
$bgFound = true;
}
$type = '';
if ((string) $fillStyleXml->patternFill['patternType'] !== '') {
$type = (string) $fillStyleXml->patternFill['patternType'];
} else {
$attr = $this->getStyleAttributes($fillStyleXml->patternFill);
$type = (string) $attr['patternType'];
}
$patternType = ($type === '') ? $defaultFillStyle : $type;
$fillStyle->setFillType($patternType);
if (
!$fgFound // no foreground color specified
&& !in_array($patternType, [Fill::FILL_NONE, Fill::FILL_SOLID], true) // these patterns aren't relevant
&& $fillStyle->getStartColor()->getARGB() // not conditional
) {
$fillStyle->getStartColor()
->setARGB('', true);
}
if (
!$bgFound // no background color specified
&& !in_array($patternType, [Fill::FILL_NONE, Fill::FILL_SOLID], true) // these patterns aren't relevant
&& $fillStyle->getEndColor()->getARGB() // not conditional
) {
$fillStyle->getEndColor()
->setARGB('', true);
}
}
}
public function readBorderStyle(Borders $borderStyle, SimpleXMLElement $borderStyleXml): void
{
$diagonalUp = $this->getAttribute($borderStyleXml, 'diagonalUp');
$diagonalUp = self::boolean($diagonalUp);
$diagonalDown = $this->getAttribute($borderStyleXml, 'diagonalDown');
$diagonalDown = self::boolean($diagonalDown);
if ($diagonalUp === false) {
if ($diagonalDown === false) {
$borderStyle->setDiagonalDirection(Borders::DIAGONAL_NONE);
} else {
$borderStyle->setDiagonalDirection(Borders::DIAGONAL_DOWN);
}
} elseif ($diagonalDown === false) {
$borderStyle->setDiagonalDirection(Borders::DIAGONAL_UP);
} else {
$borderStyle->setDiagonalDirection(Borders::DIAGONAL_BOTH);
}
if (isset($borderStyleXml->left)) {
$this->readBorder($borderStyle->getLeft(), $borderStyleXml->left);
}
if (isset($borderStyleXml->right)) {
$this->readBorder($borderStyle->getRight(), $borderStyleXml->right);
}
if (isset($borderStyleXml->top)) {
$this->readBorder($borderStyle->getTop(), $borderStyleXml->top);
}
if (isset($borderStyleXml->bottom)) {
$this->readBorder($borderStyle->getBottom(), $borderStyleXml->bottom);
}
if (isset($borderStyleXml->diagonal)) {
$this->readBorder($borderStyle->getDiagonal(), $borderStyleXml->diagonal);
}
}
private function getAttribute(SimpleXMLElement $xml, string $attribute): string
{
$style = '';
if ((string) $xml[$attribute] !== '') {
$style = (string) $xml[$attribute];
} else {
$attr = $this->getStyleAttributes($xml);
if (isset($attr[$attribute])) {
$style = (string) $attr[$attribute];
}
}
return $style;
}
private function readBorder(Border $border, SimpleXMLElement $borderXml): void
{
$style = $this->getAttribute($borderXml, 'style');
if ($style !== '') {
$border->setBorderStyle((string) $style);
} else {
$border->setBorderStyle(Border::BORDER_NONE);
}
if (isset($borderXml->color)) {
$border->getColor()->setARGB($this->readColor($borderXml->color));
}
}
public function readAlignmentStyle(Alignment $alignment, SimpleXMLElement $alignmentXml): void
{
$horizontal = (string) $this->getAttribute($alignmentXml, 'horizontal');
if ($horizontal !== '') {
$alignment->setHorizontal($horizontal);
}
$justifyLastLine = (string) $this->getAttribute($alignmentXml, 'justifyLastLine');
if ($justifyLastLine !== '') {
$alignment->setJustifyLastLine(
self::boolean($justifyLastLine)
);
}
$vertical = (string) $this->getAttribute($alignmentXml, 'vertical');
if ($vertical !== '') {
$alignment->setVertical($vertical);
}
$textRotation = (int) $this->getAttribute($alignmentXml, 'textRotation');
if ($textRotation > 90) {
$textRotation = 90 - $textRotation;
}
$alignment->setTextRotation($textRotation);
$wrapText = $this->getAttribute($alignmentXml, 'wrapText');
$alignment->setWrapText(self::boolean((string) $wrapText));
$shrinkToFit = $this->getAttribute($alignmentXml, 'shrinkToFit');
$alignment->setShrinkToFit(self::boolean((string) $shrinkToFit));
$indent = (int) $this->getAttribute($alignmentXml, 'indent');
$alignment->setIndent(max($indent, 0));
$readingOrder = (int) $this->getAttribute($alignmentXml, 'readingOrder');
$alignment->setReadOrder(max($readingOrder, 0));
}
private static function formatGeneral(string $formatString): string
{
if ($formatString === 'GENERAL') {
$formatString = NumberFormat::FORMAT_GENERAL;
}
return $formatString;
}
/**
* Read style.
*/
public function readStyle(Style $docStyle, SimpleXMLElement|stdClass $style): void
{
if ($style instanceof SimpleXMLElement) {
$this->readNumberFormat($docStyle->getNumberFormat(), $style->numFmt);
} else {
/** @var SimpleXMLElement */
$temp = $style->numFmt;
$docStyle->getNumberFormat()->setFormatCode(self::formatGeneral((string) $temp));
}
/** @var SimpleXMLElement $style */
if (isset($style->font)) {
$this->readFontStyle($docStyle->getFont(), $style->font);
}
if (isset($style->fill)) {
$this->readFillStyle($docStyle->getFill(), $style->fill);
}
if (isset($style->border)) {
$this->readBorderStyle($docStyle->getBorders(), $style->border);
}
if (isset($style->alignment)) {
$this->readAlignmentStyle($docStyle->getAlignment(), $style->alignment);
}
// protection
if (isset($style->protection)) {
$this->readProtectionLocked($docStyle, $style->protection);
$this->readProtectionHidden($docStyle, $style->protection);
}
// top-level style settings
if (isset($style->quotePrefix)) {
$docStyle->setQuotePrefix((bool) $style->quotePrefix);
}
}
/**
* Read protection locked attribute.
*/
public function readProtectionLocked(Style $docStyle, SimpleXMLElement $style): void
{
$locked = '';
if ((string) $style['locked'] !== '') {
$locked = (string) $style['locked'];
} else {
$attr = $this->getStyleAttributes($style);
if (isset($attr['locked'])) {
$locked = (string) $attr['locked'];
}
}
if ($locked !== '') {
if (self::boolean($locked)) {
$docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
} else {
$docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED);
}
}
}
/**
* Read protection hidden attribute.
*/
public function readProtectionHidden(Style $docStyle, SimpleXMLElement $style): void
{
$hidden = '';
if ((string) $style['hidden'] !== '') {
$hidden = (string) $style['hidden'];
} else {
$attr = $this->getStyleAttributes($style);
if (isset($attr['hidden'])) {
$hidden = (string) $attr['hidden'];
}
}
if ($hidden !== '') {
if (self::boolean((string) $hidden)) {
$docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED);
} else {
$docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED);
}
}
}
public function readColorTheme(SimpleXMLElement $color): int
{
$attr = $this->getStyleAttributes($color);
$retVal = -1;
if (isset($attr['theme']) && is_numeric((string) $attr['theme']) && !isset($attr['tint'])) {
$retVal = (int) $attr['theme'];
}
return $retVal;
}
public function readColor(SimpleXMLElement $color, bool $background = false): string
{
$attr = $this->getStyleAttributes($color);
if (isset($attr['rgb'])) {
return (string) $attr['rgb'];
}
if (isset($attr['indexed'])) {
$indexedColor = (int) $attr['indexed'];
if ($indexedColor >= count($this->workbookPalette)) {
return Color::indexedColor($indexedColor - 7, $background)->getARGB() ?? '';
}
return Color::indexedColor($indexedColor, $background, $this->workbookPalette)->getARGB() ?? '';
}
if (isset($attr['theme'])) {
if ($this->theme !== null) {
$returnColour = $this->theme->getColourByIndex((int) $attr['theme']);
if (isset($attr['tint'])) {
$tintAdjust = (float) $attr['tint'];
$returnColour = Color::changeBrightness($returnColour ?? '', $tintAdjust);
}
return 'FF' . $returnColour;
}
}
return ($background) ? 'FFFFFFFF' : 'FF000000';
}
/** @return Style[] */
public function dxfs(bool $readDataOnly = false): array
{
$dxfs = [];
if (!$readDataOnly && $this->styleXml) {
// Conditional Styles
if ($this->styleXml->dxfs) {
foreach ($this->styleXml->dxfs->dxf as $dxf) {
$style = new Style(false, true);
$this->readStyle($style, $dxf);
$dxfs[] = $style;
}
}
// Cell Styles
if ($this->styleXml->cellStyles) {
foreach ($this->styleXml->cellStyles->cellStyle as $cellStylex) {
$cellStyle = Xlsx::getAttributes($cellStylex);
if ((int) ($cellStyle['builtinId']) == 0) {
if (isset($this->cellStyles[(int) ($cellStyle['xfId'])])) {
// Set default style
$style = new Style();
$this->readStyle($style, $this->cellStyles[(int) ($cellStyle['xfId'])]);
// normal style, currently not using it for anything
}
}
}
}
}
return $dxfs;
}
/** @return TableDxfsStyle[] */
public function tableStyles(bool $readDataOnly = false): array
{
$tableStyles = [];
if (!$readDataOnly && $this->styleXml) {
// Conditional Styles
if ($this->styleXml->tableStyles) {
foreach ($this->styleXml->tableStyles->tableStyle as $s) {
$attrs = Xlsx::getAttributes($s);
if (isset($attrs['name'][0])) {
$style = new TableDxfsStyle((string) ($attrs['name'][0]));
foreach ($s->tableStyleElement as $e) {
$a = Xlsx::getAttributes($e);
if (isset($a['dxfId'][0], $a['type'][0])) {
switch ($a['type'][0]) {
case 'headerRow':
$style->setHeaderRow((int) ($a['dxfId'][0]));
break;
case 'firstRowStripe':
$style->setFirstRowStripe((int) ($a['dxfId'][0]));
break;
case 'secondRowStripe':
$style->setSecondRowStripe((int) ($a['dxfId'][0]));
break;
default:
}
}
}
$tableStyles[] = $style;
}
}
}
}
return $tableStyles;
}
/** @return mixed[] */
public function styles(): array
{
return $this->styles;
}
/**
* Get array item.
*
* @param false|mixed[] $array (usually array, in theory can be false)
*/
private static function getArrayItem(mixed $array): ?SimpleXMLElement
{
return is_array($array) ? ($array[0] ?? null) : null; // @phpstan-ignore-line
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/BaseParserClass.php | src/PhpSpreadsheet/Reader/Xlsx/BaseParserClass.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use Stringable;
class BaseParserClass
{
protected static function boolean(mixed $value): bool
{
if (is_object($value)) {
$value = ($value instanceof Stringable) ? ((string) $value) : 'true';
}
if (is_numeric($value)) {
return (bool) $value;
}
return $value === 'true' || $value === 'TRUE';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php | src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class DataValidations
{
private Worksheet $worksheet;
private SimpleXMLElement $worksheetXml;
public function __construct(Worksheet $workSheet, SimpleXMLElement $worksheetXml)
{
$this->worksheet = $workSheet;
$this->worksheetXml = $worksheetXml;
}
public function load(): void
{
foreach ($this->worksheetXml->dataValidations->dataValidation as $dataValidation) {
// Uppercase coordinate
$range = strtoupper((string) $dataValidation['sqref']);
$rangeSet = explode(' ', $range);
foreach ($rangeSet as $range) {
if (preg_match('/^[A-Z]{1,3}\d{1,7}/', $range, $matches) === 1) {
// Ensure left/top row of range exists, thereby
// adjusting high row/column.
$this->worksheet->getCell($matches[0]);
}
}
}
foreach ($this->worksheetXml->dataValidations->dataValidation as $dataValidation) {
// Uppercase coordinate
$range = strtoupper((string) $dataValidation['sqref']);
$docValidation = new DataValidation();
$docValidation->setType((string) $dataValidation['type']);
$docValidation->setErrorStyle((string) $dataValidation['errorStyle']);
$docValidation->setOperator((string) $dataValidation['operator']);
$docValidation->setAllowBlank(filter_var($dataValidation['allowBlank'], FILTER_VALIDATE_BOOLEAN));
// showDropDown is inverted (works as hideDropDown if true)
$docValidation->setShowDropDown(!filter_var($dataValidation['showDropDown'], FILTER_VALIDATE_BOOLEAN));
$docValidation->setShowInputMessage(filter_var($dataValidation['showInputMessage'], FILTER_VALIDATE_BOOLEAN));
$docValidation->setShowErrorMessage(filter_var($dataValidation['showErrorMessage'], FILTER_VALIDATE_BOOLEAN));
$docValidation->setErrorTitle((string) $dataValidation['errorTitle']);
$docValidation->setError((string) $dataValidation['error']);
$docValidation->setPromptTitle((string) $dataValidation['promptTitle']);
$docValidation->setPrompt((string) $dataValidation['prompt']);
$docValidation->setFormula1(Xlsx::replacePrefixes((string) $dataValidation->formula1));
$docValidation->setFormula2(Xlsx::replacePrefixes((string) $dataValidation->formula2));
$this->worksheet->setDataValidation($range, $docValidation);
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php | src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class Hyperlinks
{
private Worksheet $worksheet;
/** @var string[] */
private array $hyperlinks = [];
public function __construct(Worksheet $workSheet)
{
$this->worksheet = $workSheet;
}
public function readHyperlinks(SimpleXMLElement $relsWorksheet): void
{
foreach ($relsWorksheet->children(Namespaces::RELATIONSHIPS)->Relationship as $elementx) {
$element = Xlsx::getAttributes($elementx);
if ($element->Type == Namespaces::HYPERLINK) {
$this->hyperlinks[(string) $element->Id] = (string) $element->Target;
}
}
}
public function setHyperlinks(SimpleXMLElement $worksheetXml): void
{
foreach ($worksheetXml->children(Namespaces::MAIN)->hyperlink as $hyperlink) {
$this->setHyperlink($hyperlink, $this->worksheet);
}
}
private function setHyperlink(SimpleXMLElement $hyperlink, Worksheet $worksheet): void
{
// Link url
$linkRel = Xlsx::getAttributes($hyperlink, Namespaces::SCHEMA_OFFICE_DOCUMENT);
$attributes = Xlsx::getAttributes($hyperlink);
foreach (Coordinate::extractAllCellReferencesInRange($attributes->ref) as $cellReference) {
$cell = $worksheet->getCell($cellReference);
if (isset($attributes['location'])) {
$cell->getHyperlink()->setUrl('sheet://' . (string) $attributes['location']);
} elseif (isset($linkRel['id'])) {
$hyperlinkUrl = $this->hyperlinks[(string) $linkRel['id']] ?? '';
$cell->getHyperlink()->setUrl($hyperlinkUrl);
}
// Tooltip
if (isset($attributes['tooltip'])) {
$cell->getHyperlink()->setTooltip((string) $attributes['tooltip']);
}
if (isset($attributes['display'])) {
$cell->getHyperlink()->setDisplay((string) $attributes['display']);
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/PageSetup.php | src/PhpSpreadsheet/Reader/Xlsx/PageSetup.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class PageSetup extends BaseParserClass
{
private Worksheet $worksheet;
private ?SimpleXMLElement $worksheetXml;
public function __construct(Worksheet $workSheet, ?SimpleXMLElement $worksheetXml = null)
{
$this->worksheet = $workSheet;
$this->worksheetXml = $worksheetXml;
}
/**
* @param mixed[] $unparsedLoadedData
*
* @return mixed[]
*/
public function load(array $unparsedLoadedData): array
{
$worksheetXml = $this->worksheetXml;
if ($worksheetXml === null) {
return $unparsedLoadedData;
}
$this->margins($worksheetXml, $this->worksheet);
$unparsedLoadedData = $this->pageSetup($worksheetXml, $this->worksheet, $unparsedLoadedData);
$this->headerFooter($worksheetXml, $this->worksheet);
$this->pageBreaks($worksheetXml, $this->worksheet);
return $unparsedLoadedData;
}
private function margins(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void
{
if ($xmlSheet->pageMargins) {
$docPageMargins = $worksheet->getPageMargins();
$docPageMargins->setLeft((float) ($xmlSheet->pageMargins['left']));
$docPageMargins->setRight((float) ($xmlSheet->pageMargins['right']));
$docPageMargins->setTop((float) ($xmlSheet->pageMargins['top']));
$docPageMargins->setBottom((float) ($xmlSheet->pageMargins['bottom']));
$docPageMargins->setHeader((float) ($xmlSheet->pageMargins['header']));
$docPageMargins->setFooter((float) ($xmlSheet->pageMargins['footer']));
}
}
/**
* @param mixed[] $unparsedLoadedData
*
* @return mixed[]
*/
private function pageSetup(SimpleXMLElement $xmlSheet, Worksheet $worksheet, array $unparsedLoadedData): array
{
if ($xmlSheet->pageSetup) {
$docPageSetup = $worksheet->getPageSetup();
if (isset($xmlSheet->pageSetup['orientation'])) {
$docPageSetup->setOrientation((string) $xmlSheet->pageSetup['orientation']);
}
if (isset($xmlSheet->pageSetup['paperSize'])) {
$docPageSetup->setPaperSize((int) ($xmlSheet->pageSetup['paperSize']));
}
if (isset($xmlSheet->pageSetup['scale'])) {
$docPageSetup->setScale((int) ($xmlSheet->pageSetup['scale']), false);
}
if (isset($xmlSheet->pageSetup['fitToHeight']) && (int) ($xmlSheet->pageSetup['fitToHeight']) >= 0) {
$docPageSetup->setFitToHeight((int) ($xmlSheet->pageSetup['fitToHeight']), false);
}
if (isset($xmlSheet->pageSetup['fitToWidth']) && (int) ($xmlSheet->pageSetup['fitToWidth']) >= 0) {
$docPageSetup->setFitToWidth((int) ($xmlSheet->pageSetup['fitToWidth']), false);
}
if (
isset($xmlSheet->pageSetup['firstPageNumber'], $xmlSheet->pageSetup['useFirstPageNumber'])
&& self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber'])
) {
$docPageSetup->setFirstPageNumber((int) ($xmlSheet->pageSetup['firstPageNumber']));
}
if (isset($xmlSheet->pageSetup['pageOrder'])) {
$docPageSetup->setPageOrder((string) $xmlSheet->pageSetup['pageOrder']);
}
$relAttributes = $xmlSheet->pageSetup->attributes(Namespaces::SCHEMA_OFFICE_DOCUMENT);
if (isset($relAttributes['id'])) {
$relid = (string) $relAttributes['id'];
if (!str_ends_with($relid, 'ps')) {
$relid .= 'ps';
}
/** @var mixed[][][] $unparsedLoadedData */
$unparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'] = $relid;
}
}
return $unparsedLoadedData;
}
private function headerFooter(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void
{
if ($xmlSheet->headerFooter) {
$docHeaderFooter = $worksheet->getHeaderFooter();
if (
isset($xmlSheet->headerFooter['differentOddEven'])
&& self::boolean((string) $xmlSheet->headerFooter['differentOddEven'])
) {
$docHeaderFooter->setDifferentOddEven(true);
} else {
$docHeaderFooter->setDifferentOddEven(false);
}
if (
isset($xmlSheet->headerFooter['differentFirst'])
&& self::boolean((string) $xmlSheet->headerFooter['differentFirst'])
) {
$docHeaderFooter->setDifferentFirst(true);
} else {
$docHeaderFooter->setDifferentFirst(false);
}
if (
isset($xmlSheet->headerFooter['scaleWithDoc'])
&& !self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc'])
) {
$docHeaderFooter->setScaleWithDocument(false);
} else {
$docHeaderFooter->setScaleWithDocument(true);
}
if (
isset($xmlSheet->headerFooter['alignWithMargins'])
&& !self::boolean((string) $xmlSheet->headerFooter['alignWithMargins'])
) {
$docHeaderFooter->setAlignWithMargins(false);
} else {
$docHeaderFooter->setAlignWithMargins(true);
}
$docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader);
$docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter);
$docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader);
$docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter);
$docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader);
$docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter);
}
}
private function pageBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void
{
if ($xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk) {
$this->rowBreaks($xmlSheet, $worksheet);
}
if ($xmlSheet->colBreaks && $xmlSheet->colBreaks->brk) {
$this->columnBreaks($xmlSheet, $worksheet);
}
}
private function rowBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void
{
foreach ($xmlSheet->rowBreaks->brk as $brk) {
$rowBreakMax = /*isset($brk['max']) ? ((int) $brk['max']) :*/ -1;
if ($brk['man']) {
$worksheet->setBreak("A{$brk['id']}", Worksheet::BREAK_ROW, $rowBreakMax);
}
}
}
private function columnBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void
{
foreach ($xmlSheet->colBreaks->brk as $brk) {
if ($brk['man']) {
$worksheet->setBreak(
Coordinate::stringFromColumnIndex(((int) $brk['id']) + 1) . '1',
Worksheet::BREAK_COLUMN
);
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/Theme.php | src/PhpSpreadsheet/Reader/Xlsx/Theme.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
class Theme
{
/**
* Theme Name.
*/
private string $themeName;
/**
* Colour Scheme Name.
*/
private string $colourSchemeName;
/**
* Colour Map.
*
* @var string[]
*/
private array $colourMap;
/**
* Create a new Theme.
*
* @param string[] $colourMap
*/
public function __construct(string $themeName, string $colourSchemeName, array $colourMap)
{
// Initialise values
$this->themeName = $themeName;
$this->colourSchemeName = $colourSchemeName;
$this->colourMap = $colourMap;
}
/**
* Not called by Reader, never accessible any other time.
*
* @codeCoverageIgnore
*/
public function getThemeName(): string
{
return $this->themeName;
}
/**
* Not called by Reader, never accessible any other time.
*
* @codeCoverageIgnore
*/
public function getColourSchemeName(): string
{
return $this->colourSchemeName;
}
/**
* Get colour Map Value by Position.
*/
public function getColourByIndex(int $index): ?string
{
return $this->colourMap[$index] ?? null;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/TableReader.php | src/PhpSpreadsheet/Reader/Xlsx/TableReader.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
use PhpOffice\PhpSpreadsheet\Worksheet\Table\TableDxfsStyle;
use PhpOffice\PhpSpreadsheet\Worksheet\Table\TableStyle;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class TableReader
{
private Worksheet $worksheet;
private SimpleXMLElement $tableXml;
/** @var mixed[]|SimpleXMLElement */
private $tableAttributes;
public function __construct(Worksheet $workSheet, SimpleXMLElement $tableXml)
{
$this->worksheet = $workSheet;
$this->tableXml = $tableXml;
}
/**
* Loads Table into the Worksheet.
*
* @param TableDxfsStyle[] $tableStyles
* @param Style[] $dxfs
*/
public function load(array $tableStyles, array $dxfs): void
{
$this->tableAttributes = $this->tableXml->attributes() ?? [];
// Remove all "$" in the table range
$tableRange = (string) preg_replace('/\$/', '', $this->tableAttributes['ref'] ?? '');
if (str_contains($tableRange, ':')) {
$this->readTable($tableRange, $tableStyles, $dxfs);
}
}
/**
* Read Table from xml.
*
* @param TableDxfsStyle[] $tableStyles
* @param Style[] $dxfs
*/
private function readTable(string $tableRange, array $tableStyles, array $dxfs): void
{
$table = new Table($tableRange);
/** @var string[] */
$attributes = $this->tableAttributes;
$table->setName((string) ($attributes['displayName'] ?? ''));
$table->setShowHeaderRow(((string) ($attributes['headerRowCount'] ?? '')) !== '0');
$table->setShowTotalsRow(((string) ($attributes['totalsRowCount'] ?? '')) === '1');
$this->readTableAutoFilter($table, $this->tableXml->autoFilter);
$this->readTableColumns($table, $this->tableXml->tableColumns);
$this->readTableStyle($table, $this->tableXml->tableStyleInfo, $tableStyles, $dxfs);
(new AutoFilter($table, $this->tableXml))->load();
$this->worksheet->addTable($table);
}
/**
* Reads TableAutoFilter from xml.
*/
private function readTableAutoFilter(Table $table, SimpleXMLElement $autoFilterXml): void
{
if ($autoFilterXml->filterColumn === null) {
$table->setAllowFilter(false);
return;
}
foreach ($autoFilterXml->filterColumn as $filterColumn) {
/** @var SimpleXMLElement */
$attributes = $filterColumn->attributes() ?? ['colId' => 0, 'hiddenButton' => 0];
$column = $table->getColumnByOffset((int) $attributes['colId']);
$column->setShowFilterButton(((string) $attributes['hiddenButton']) !== '1');
}
}
/**
* Reads TableColumns from xml.
*/
private function readTableColumns(Table $table, SimpleXMLElement $tableColumnsXml): void
{
$offset = 0;
foreach ($tableColumnsXml->tableColumn as $tableColumn) {
/** @var SimpleXMLElement */
$attributes = $tableColumn->attributes() ?? ['totalsRowLabel' => 0, 'totalsRowFunction' => 0];
$column = $table->getColumnByOffset($offset++);
if ($table->getShowTotalsRow()) {
if ($attributes['totalsRowLabel']) {
$column->setTotalsRowLabel((string) $attributes['totalsRowLabel']);
}
if ($attributes['totalsRowFunction']) {
$column->setTotalsRowFunction((string) $attributes['totalsRowFunction']);
}
}
if ($tableColumn->calculatedColumnFormula) {
$column->setColumnFormula((string) $tableColumn->calculatedColumnFormula);
}
}
}
/**
* Reads TableStyle from xml.
*
* @param TableDxfsStyle[] $tableStyles
* @param Style[] $dxfs
*/
private function readTableStyle(Table $table, SimpleXMLElement $tableStyleInfoXml, array $tableStyles, array $dxfs): void
{
$tableStyle = new TableStyle();
$attributes = $tableStyleInfoXml->attributes();
if ($attributes !== null) {
$tableStyle->setTheme((string) $attributes['name']);
$tableStyle->setShowRowStripes((string) $attributes['showRowStripes'] === '1');
$tableStyle->setShowColumnStripes((string) $attributes['showColumnStripes'] === '1');
$tableStyle->setShowFirstColumn((string) $attributes['showFirstColumn'] === '1');
$tableStyle->setShowLastColumn((string) $attributes['showLastColumn'] === '1');
foreach ($tableStyles as $style) {
if ($style->getName() === (string) $attributes['name']) {
$tableStyle->setTableDxfsStyle($style, $dxfs);
}
}
}
$table->setStyle($tableStyle);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php | src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
class Namespaces
{
const SCHEMAS = 'http://schemas.openxmlformats.org';
const RELATIONSHIPS = 'http://schemas.openxmlformats.org/package/2006/relationships';
// This one used in Reader\Xlsx
const CORE_PROPERTIES = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties';
// This one used in Reader\Xlsx\Properties
const CORE_PROPERTIES2 = 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties';
const THUMBNAIL = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail';
const THEME = 'http://schemas.openxmlformats.org/package/2006/relationships/theme';
const THEME2 = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme';
const COMPATIBILITY = 'http://schemas.openxmlformats.org/markup-compatibility/2006';
const MAIN = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
const RELATIONSHIPS_DRAWING = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing';
const DRAWINGML = 'http://schemas.openxmlformats.org/drawingml/2006/main';
const CHART = 'http://schemas.openxmlformats.org/drawingml/2006/chart';
const CHART_ALTERNATE = 'http://schemas.microsoft.com/office/drawing/2007/8/2/chart';
const RELATIONSHIPS_CHART = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart';
const SPREADSHEET_DRAWING = 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing';
const SCHEMA_OFFICE_DOCUMENT = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
const COMMENTS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments';
const RELATIONSHIPS_CUSTOM_PROPERTIES = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties';
const RELATIONSHIPS_EXTENDED_PROPERTIES = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties';
const RELATIONSHIPS_CTRLPROP = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp';
const CUSTOM_PROPERTIES = 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties';
const EXTENDED_PROPERTIES = 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties';
const PROPERTIES_VTYPES = 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes';
const HYPERLINK = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink';
const OFFICE_DOCUMENT = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument';
const SHARED_STRINGS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings';
const STYLES = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles';
const IMAGE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image';
const VML = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing';
const WORKSHEET = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet';
const CHARTSHEET = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet';
const SCHEMA_MICROSOFT = 'http://schemas.microsoft.com/office/2006/relationships';
const EXTENSIBILITY = 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility';
const VBA = 'http://schemas.microsoft.com/office/2006/relationships/vbaProject';
const VBA_SIGNATURE = 'http://schemas.microsoft.com/office/2006/relationships/vbaProject';
const DATA_VALIDATIONS1 = 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main';
const DATA_VALIDATIONS2 = 'http://schemas.microsoft.com/office/excel/2006/main';
const CONTENT_TYPES = 'http://schemas.openxmlformats.org/package/2006/content-types';
const RELATIONSHIPS_METADATA = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata';
const RELATIONSHIPS_PRINTER_SETTINGS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings';
const RELATIONSHIPS_TABLE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/table';
const SPREADSHEETML_AC = 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac';
const DC_ELEMENTS = 'http://purl.org/dc/elements/1.1/';
const DC_TERMS = 'http://purl.org/dc/terms/';
const DC_DCMITYPE = 'http://purl.org/dc/dcmitype/';
const SCHEMA_INSTANCE = 'http://www.w3.org/2001/XMLSchema-instance';
const URN_EXCEL = 'urn:schemas-microsoft-com:office:excel';
const URN_MSOFFICE = 'urn:schemas-microsoft-com:office:office';
const URN_VML = 'urn:schemas-microsoft-com:vml';
const SCHEMA_PURL = 'http://purl.oclc.org/ooxml';
const PURL_OFFICE_DOCUMENT = 'http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument';
const PURL_RELATIONSHIPS = 'http://purl.oclc.org/ooxml/officeDocument/relationships';
const PURL_MAIN = 'http://purl.oclc.org/ooxml/spreadsheetml/main';
const PURL_DRAWING = 'http://purl.oclc.org/ooxml/drawingml/main';
const PURL_CHART = 'http://purl.oclc.org/ooxml/drawingml/chart';
const PURL_WORKSHEET = 'http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet';
const DYNAMIC_ARRAY = 'http://schemas.microsoft.com/office/spreadsheetml/2017/dynamicarray';
const DYNAMIC_ARRAY_RICHDATA = 'http://schemas.microsoft.com/office/spreadsheetml/2017/richdata';
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/SharedFormula.php | src/PhpSpreadsheet/Reader/Xlsx/SharedFormula.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
class SharedFormula
{
private string $master;
private string $formula;
public function __construct(string $master, string $formula)
{
$this->master = $master;
$this->formula = $formula;
}
public function master(): string
{
return $this->master;
}
public function formula(): string
{
return $this->formula;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/WorkbookView.php | src/PhpSpreadsheet/Reader/Xlsx/WorkbookView.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use SimpleXMLElement;
class WorkbookView
{
private Spreadsheet $spreadsheet;
public function __construct(Spreadsheet $spreadsheet)
{
$this->spreadsheet = $spreadsheet;
}
/** @param array<int, ?int> $mapSheetId */
public function viewSettings(SimpleXMLElement $xmlWorkbook, string $mainNS, array $mapSheetId, bool $readDataOnly): void
{
// Default active sheet index to the first loaded worksheet from the file
$this->spreadsheet->setActiveSheetIndex(0);
$workbookView = $xmlWorkbook->children($mainNS)->bookViews->workbookView;
if ($readDataOnly !== true && !empty($workbookView)) {
$workbookViewAttributes = self::testSimpleXml(self::getAttributes($workbookView));
// active sheet index
$activeTab = (int) $workbookViewAttributes->activeTab; // refers to old sheet index
// keep active sheet index if sheet is still loaded, else first sheet is set as the active worksheet
if (isset($mapSheetId[$activeTab])) {
$this->spreadsheet->setActiveSheetIndex($mapSheetId[$activeTab]);
}
$this->horizontalScroll($workbookViewAttributes);
$this->verticalScroll($workbookViewAttributes);
$this->sheetTabs($workbookViewAttributes);
$this->minimized($workbookViewAttributes);
$this->autoFilterDateGrouping($workbookViewAttributes);
$this->firstSheet($workbookViewAttributes);
$this->visibility($workbookViewAttributes);
$this->tabRatio($workbookViewAttributes);
}
}
public static function testSimpleXml(mixed $value): SimpleXMLElement
{
return ($value instanceof SimpleXMLElement)
? $value
: new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>');
}
public static function getAttributes(?SimpleXMLElement $value, string $ns = ''): SimpleXMLElement
{
return self::testSimpleXml($value === null ? $value : $value->attributes($ns));
}
/**
* Convert an 'xsd:boolean' XML value to a PHP boolean value.
* A valid 'xsd:boolean' XML value can be one of the following
* four values: 'true', 'false', '1', '0'. It is case-sensitive.
*
* Note that just doing '(bool) $xsdBoolean' is not safe,
* since '(bool) "false"' returns true.
*
* @see https://www.w3.org/TR/xmlschema11-2/#boolean
*
* @param string $xsdBoolean An XML string value of type 'xsd:boolean'
*
* @return bool Boolean value
*/
private function castXsdBooleanToBool(string $xsdBoolean): bool
{
if ($xsdBoolean === 'false') {
return false;
}
return (bool) $xsdBoolean;
}
private function horizontalScroll(SimpleXMLElement $workbookViewAttributes): void
{
if (isset($workbookViewAttributes->showHorizontalScroll)) {
$showHorizontalScroll = (string) $workbookViewAttributes->showHorizontalScroll;
$this->spreadsheet->setShowHorizontalScroll($this->castXsdBooleanToBool($showHorizontalScroll));
}
}
private function verticalScroll(SimpleXMLElement $workbookViewAttributes): void
{
if (isset($workbookViewAttributes->showVerticalScroll)) {
$showVerticalScroll = (string) $workbookViewAttributes->showVerticalScroll;
$this->spreadsheet->setShowVerticalScroll($this->castXsdBooleanToBool($showVerticalScroll));
}
}
private function sheetTabs(SimpleXMLElement $workbookViewAttributes): void
{
if (isset($workbookViewAttributes->showSheetTabs)) {
$showSheetTabs = (string) $workbookViewAttributes->showSheetTabs;
$this->spreadsheet->setShowSheetTabs($this->castXsdBooleanToBool($showSheetTabs));
}
}
private function minimized(SimpleXMLElement $workbookViewAttributes): void
{
if (isset($workbookViewAttributes->minimized)) {
$minimized = (string) $workbookViewAttributes->minimized;
$this->spreadsheet->setMinimized($this->castXsdBooleanToBool($minimized));
}
}
private function autoFilterDateGrouping(SimpleXMLElement $workbookViewAttributes): void
{
if (isset($workbookViewAttributes->autoFilterDateGrouping)) {
$autoFilterDateGrouping = (string) $workbookViewAttributes->autoFilterDateGrouping;
$this->spreadsheet->setAutoFilterDateGrouping($this->castXsdBooleanToBool($autoFilterDateGrouping));
}
}
private function firstSheet(SimpleXMLElement $workbookViewAttributes): void
{
if (isset($workbookViewAttributes->firstSheet)) {
$firstSheet = (string) $workbookViewAttributes->firstSheet;
$this->spreadsheet->setFirstSheetIndex((int) $firstSheet);
}
}
private function visibility(SimpleXMLElement $workbookViewAttributes): void
{
if (isset($workbookViewAttributes->visibility)) {
$visibility = (string) $workbookViewAttributes->visibility;
$this->spreadsheet->setVisibility($visibility);
}
}
private function tabRatio(SimpleXMLElement $workbookViewAttributes): void
{
if (isset($workbookViewAttributes->tabRatio)) {
$tabRatio = (string) $workbookViewAttributes->tabRatio;
$this->spreadsheet->setTabRatio((int) $tabRatio);
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/Properties.php | src/PhpSpreadsheet/Reader/Xlsx/Properties.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Document\Properties as DocumentProperties;
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
use SimpleXMLElement;
class Properties
{
private XmlScanner $securityScanner;
private DocumentProperties $docProps;
public function __construct(XmlScanner $securityScanner, DocumentProperties $docProps)
{
$this->securityScanner = $securityScanner;
$this->docProps = $docProps;
}
private function extractPropertyData(string $propertyData): ?SimpleXMLElement
{
// okay to omit namespace because everything will be processed by xpath
$obj = simplexml_load_string(
$this->securityScanner->scan($propertyData)
);
return $obj === false ? null : $obj;
}
public function readCoreProperties(string $propertyData): void
{
$xmlCore = $this->extractPropertyData($propertyData);
if (is_object($xmlCore)) {
$xmlCore->registerXPathNamespace('dc', Namespaces::DC_ELEMENTS);
$xmlCore->registerXPathNamespace('dcterms', Namespaces::DC_TERMS);
$xmlCore->registerXPathNamespace('cp', Namespaces::CORE_PROPERTIES2);
$this->docProps->setCreator($this->getArrayItem($xmlCore->xpath('dc:creator')));
$this->docProps->setLastModifiedBy($this->getArrayItem($xmlCore->xpath('cp:lastModifiedBy')));
$this->docProps->setCreated($this->getArrayItem($xmlCore->xpath('dcterms:created'))); //! respect xsi:type
$this->docProps->setModified($this->getArrayItem($xmlCore->xpath('dcterms:modified'))); //! respect xsi:type
$this->docProps->setTitle($this->getArrayItem($xmlCore->xpath('dc:title')));
$this->docProps->setDescription($this->getArrayItem($xmlCore->xpath('dc:description')));
$this->docProps->setSubject($this->getArrayItem($xmlCore->xpath('dc:subject')));
$this->docProps->setKeywords($this->getArrayItem($xmlCore->xpath('cp:keywords')));
$this->docProps->setCategory($this->getArrayItem($xmlCore->xpath('cp:category')));
}
}
public function readExtendedProperties(string $propertyData): void
{
$xmlCore = $this->extractPropertyData($propertyData);
if (is_object($xmlCore)) {
if (isset($xmlCore->Company)) {
$this->docProps->setCompany((string) $xmlCore->Company);
}
if (isset($xmlCore->Manager)) {
$this->docProps->setManager((string) $xmlCore->Manager);
}
if (isset($xmlCore->HyperlinkBase)) {
$this->docProps->setHyperlinkBase((string) $xmlCore->HyperlinkBase);
}
}
}
public function readCustomProperties(string $propertyData): void
{
$xmlCore = $this->extractPropertyData($propertyData);
if (is_object($xmlCore)) {
foreach ($xmlCore as $xmlProperty) {
/** @var SimpleXMLElement $xmlProperty */
$cellDataOfficeAttributes = $xmlProperty->attributes();
if (isset($cellDataOfficeAttributes['name'])) {
$propertyName = (string) $cellDataOfficeAttributes['name'];
$cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes');
$attributeType = $cellDataOfficeChildren->getName();
/** @var SimpleXMLElement */
$attributeValue = $cellDataOfficeChildren->{$attributeType};
$attributeValue = (string) $attributeValue;
$attributeValue = DocumentProperties::convertProperty($attributeValue, $attributeType);
$attributeType = DocumentProperties::convertPropertyType($attributeType);
$this->docProps->setCustomProperty($propertyName, $attributeValue, $attributeType);
}
}
}
}
/** @param null|false|scalar[] $array */
private function getArrayItem(null|array|false $array): string
{
return is_array($array) ? (string) ($array[0] ?? '') : '';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php | src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column;
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule;
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class AutoFilter
{
private Table|Worksheet $parent;
private SimpleXMLElement $worksheetXml;
public function __construct(Table|Worksheet $parent, SimpleXMLElement $worksheetXml)
{
$this->parent = $parent;
$this->worksheetXml = $worksheetXml;
}
public function load(): void
{
// Remove all "$" in the auto filter range
$attrs = $this->worksheetXml->autoFilter->attributes() ?? [];
$autoFilterRange = (string) preg_replace('/\$/', '', $attrs['ref'] ?? '');
if (str_contains($autoFilterRange, ':')) {
$this->readAutoFilter($autoFilterRange);
}
}
private function readAutoFilter(string $autoFilterRange): void
{
$autoFilter = $this->parent->getAutoFilter();
$autoFilter->setRange($autoFilterRange);
foreach ($this->worksheetXml->autoFilter->filterColumn as $filterColumn) {
$attributes = $filterColumn->attributes() ?? [];
$column = $autoFilter->getColumnByOffset((int) ($attributes['colId'] ?? 0));
// Check for standard filters
if ($filterColumn->filters) {
$column->setFilterType(Column::AUTOFILTER_FILTERTYPE_FILTER);
$filters = Xlsx::testSimpleXml($filterColumn->filters->attributes());
if ((isset($filters['blank'])) && ((int) $filters['blank'] == 1)) {
// Operator is undefined, but always treated as EQUAL
$column->createRule()->setRule('', '')->setRuleType(Rule::AUTOFILTER_RULETYPE_FILTER);
}
// Standard filters are always an OR join, so no join rule needs to be set
// Entries can be either filter elements
foreach ($filterColumn->filters->filter as $filterRule) {
// Operator is undefined, but always treated as EQUAL
/** @var SimpleXMLElement */
$attr2 = $filterRule->attributes() ?? ['val' => ''];
$column->createRule()->setRule('', (string) $attr2['val'])->setRuleType(Rule::AUTOFILTER_RULETYPE_FILTER);
}
// Or Date Group elements
$this->readDateRangeAutoFilter($filterColumn->filters, $column);
}
// Check for custom filters
$this->readCustomAutoFilter($filterColumn, $column);
// Check for dynamic filters
$this->readDynamicAutoFilter($filterColumn, $column);
// Check for dynamic filters
$this->readTopTenAutoFilter($filterColumn, $column);
}
$autoFilter->setEvaluated(true);
}
private function readDateRangeAutoFilter(SimpleXMLElement $filters, Column $column): void
{
foreach ($filters->dateGroupItem as $dateGroupItemx) {
// Operator is undefined, but always treated as EQUAL
$dateGroupItem = $dateGroupItemx->attributes();
if ($dateGroupItem !== null) {
$column->createRule()->setRule(
'',
[
'year' => (string) $dateGroupItem['year'],
'month' => (string) $dateGroupItem['month'],
'day' => (string) $dateGroupItem['day'],
'hour' => (string) $dateGroupItem['hour'],
'minute' => (string) $dateGroupItem['minute'],
'second' => (string) $dateGroupItem['second'],
],
(string) $dateGroupItem['dateTimeGrouping']
)->setRuleType(Rule::AUTOFILTER_RULETYPE_DATEGROUP);
}
}
}
private function readCustomAutoFilter(?SimpleXMLElement $filterColumn, Column $column): void
{
if (isset($filterColumn, $filterColumn->customFilters)) {
$column->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER);
$customFilters = $filterColumn->customFilters;
$attributes = $customFilters->attributes();
// Custom filters can an AND or an OR join;
// and there should only ever be one or two entries
if ((isset($attributes['and'])) && ((string) $attributes['and'] === '1')) {
$column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND);
}
foreach ($customFilters->customFilter as $filterRule) {
/** @var SimpleXMLElement */
$attr2 = $filterRule->attributes() ?? ['operator' => '', 'val' => ''];
$column->createRule()->setRule(
(string) $attr2['operator'],
(string) $attr2['val']
)->setRuleType(Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER);
}
}
}
private function readDynamicAutoFilter(?SimpleXMLElement $filterColumn, Column $column): void
{
if (isset($filterColumn, $filterColumn->dynamicFilter)) {
$column->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER);
// We should only ever have one dynamic filter
foreach ($filterColumn->dynamicFilter as $filterRule) {
// Operator is undefined, but always treated as EQUAL
$attr2 = $filterRule->attributes() ?? [];
$column->createRule()->setRule(
'',
(string) ($attr2['val'] ?? ''),
(string) ($attr2['type'] ?? '')
)->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER);
if (isset($attr2['val'])) {
$column->setAttribute('val', (string) $attr2['val']);
}
if (isset($attr2['maxVal'])) {
$column->setAttribute('maxVal', (string) $attr2['maxVal']);
}
}
}
}
private function readTopTenAutoFilter(?SimpleXMLElement $filterColumn, Column $column): void
{
if (isset($filterColumn, $filterColumn->top10)) {
$column->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER);
// We should only ever have one top10 filter
foreach ($filterColumn->top10 as $filterRule) {
$attr2 = $filterRule->attributes() ?? [];
$column->createRule()->setRule(
(
((isset($attr2['percent'])) && ((string) $attr2['percent'] === '1'))
? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT
: Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE
),
(string) ($attr2['val'] ?? ''),
(
((isset($attr2['top'])) && ((string) $attr2['top'] === '1'))
? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
: Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
)
)->setRuleType(Rule::AUTOFILTER_RULETYPE_TOPTENFILTER);
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/Chart.php | src/PhpSpreadsheet/Reader/Xlsx/Chart.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
use PhpOffice\PhpSpreadsheet\Chart\Axis;
use PhpOffice\PhpSpreadsheet\Chart\AxisText;
use PhpOffice\PhpSpreadsheet\Chart\ChartColor;
use PhpOffice\PhpSpreadsheet\Chart\DataSeries;
use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues;
use PhpOffice\PhpSpreadsheet\Chart\GridLines;
use PhpOffice\PhpSpreadsheet\Chart\Layout;
use PhpOffice\PhpSpreadsheet\Chart\Legend;
use PhpOffice\PhpSpreadsheet\Chart\PlotArea;
use PhpOffice\PhpSpreadsheet\Chart\Properties as ChartProperties;
use PhpOffice\PhpSpreadsheet\Chart\Title;
use PhpOffice\PhpSpreadsheet\Chart\TrendLine;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Style\Font;
use SimpleXMLElement;
class Chart
{
private string $cNamespace;
private string $aNamespace;
public function __construct(string $cNamespace = Namespaces::CHART, string $aNamespace = Namespaces::DRAWINGML)
{
$this->cNamespace = $cNamespace;
$this->aNamespace = $aNamespace;
}
private static function getAttributeString(SimpleXMLElement $component, string $name): string|null
{
$attributes = $component->attributes();
if (@isset($attributes[$name])) {
return (string) $attributes[$name];
}
return null;
}
private static function getAttributeInteger(SimpleXMLElement $component, string $name): int|null
{
$attributes = $component->attributes();
if (@isset($attributes[$name])) {
return (int) $attributes[$name];
}
return null;
}
private static function getAttributeBoolean(SimpleXMLElement $component, string $name): bool|null
{
$attributes = $component->attributes();
if (@isset($attributes[$name])) {
$value = (string) $attributes[$name];
return $value === 'true' || $value === '1';
}
return null;
}
private static function getAttributeFloat(SimpleXMLElement $component, string $name): float|null
{
$attributes = $component->attributes();
if (@isset($attributes[$name])) {
return (float) $attributes[$name];
}
return null;
}
public function readChart(SimpleXMLElement $chartElements, string $chartName): \PhpOffice\PhpSpreadsheet\Chart\Chart
{
$chartElementsC = $chartElements->children($this->cNamespace);
$XaxisLabel = $YaxisLabel = $legend = $title = null;
$dispBlanksAs = null;
$plotVisOnly = false;
$plotArea = null;
$rotX = $rotY = $rAngAx = $perspective = null;
$xAxis = new Axis();
$yAxis = new Axis();
$autoTitleDeleted = null;
$chartNoFill = false;
$chartBorderLines = null;
$chartFillColor = null;
$gradientArray = [];
$gradientLin = null;
$roundedCorners = false;
$gapWidth = null;
$useUpBars = null;
$useDownBars = null;
$noBorder = false;
foreach ($chartElementsC as $chartElementKey => $chartElement) {
switch ($chartElementKey) {
case 'spPr':
$children = $chartElementsC->spPr->children($this->aNamespace);
if (isset($children->noFill)) {
$chartNoFill = true;
}
if (isset($children->solidFill)) {
$chartFillColor = $this->readColor($children->solidFill);
}
if (isset($children->ln)) {
$chartBorderLines = new GridLines();
$this->readLineStyle($chartElementsC, $chartBorderLines);
if (isset($children->ln->noFill)) {
$noBorder = true;
}
}
break;
case 'roundedCorners':
/** @var bool $roundedCorners */
$roundedCorners = self::getAttributeBoolean($chartElementsC->roundedCorners, 'val');
break;
case 'chart':
foreach ($chartElement as $chartDetailsKey => $chartDetails) {
$chartDetails = Xlsx::testSimpleXml($chartDetails);
switch ($chartDetailsKey) {
case 'autoTitleDeleted':
/** @var bool $autoTitleDeleted */
$autoTitleDeleted = self::getAttributeBoolean($chartElementsC->chart->autoTitleDeleted, 'val');
break;
case 'view3D':
$rotX = self::getAttributeInteger($chartDetails->rotX, 'val');
$rotY = self::getAttributeInteger($chartDetails->rotY, 'val');
$rAngAx = self::getAttributeInteger($chartDetails->rAngAx, 'val');
$perspective = self::getAttributeInteger($chartDetails->perspective, 'val');
break;
case 'plotArea':
$plotAreaLayout = $XaxisLabel = $YaxisLabel = null;
$plotSeries = $plotAttributes = [];
$catAxRead = false;
$plotNoFill = false;
foreach ($chartDetails as $chartDetailKey => $chartDetail) {
$chartDetail = Xlsx::testSimpleXml($chartDetail);
switch ($chartDetailKey) {
case 'spPr':
$possibleNoFill = $chartDetails->spPr->children($this->aNamespace);
if (isset($possibleNoFill->noFill)) {
$plotNoFill = true;
}
if (isset($possibleNoFill->gradFill->gsLst)) {
foreach ($possibleNoFill->gradFill->gsLst->gs as $gradient) {
$gradient = Xlsx::testSimpleXml($gradient);
/** @var float $pos */
$pos = self::getAttributeFloat($gradient, 'pos');
$gradientArray[] = [
$pos / ChartProperties::PERCENTAGE_MULTIPLIER,
new ChartColor($this->readColor($gradient)),
];
}
}
if (isset($possibleNoFill->gradFill->lin)) {
$gradientLin = ChartProperties::XmlToAngle((string) self::getAttributeString($possibleNoFill->gradFill->lin, 'ang'));
}
break;
case 'layout':
$plotAreaLayout = $this->chartLayoutDetails($chartDetail);
break;
case Axis::AXIS_TYPE_CATEGORY:
case Axis::AXIS_TYPE_DATE:
$catAxRead = true;
if (isset($chartDetail->title)) {
$XaxisLabel = $this->chartTitle($chartDetail->title->children($this->cNamespace));
}
$xAxis->setAxisType($chartDetailKey);
$this->readEffects($chartDetail, $xAxis);
$this->readLineStyle($chartDetail, $xAxis);
if (isset($chartDetail->spPr)) {
$sppr = $chartDetail->spPr->children($this->aNamespace);
if (isset($sppr->solidFill)) {
$axisColorArray = $this->readColor($sppr->solidFill);
$xAxis->setFillParameters($axisColorArray['value'], $axisColorArray['alpha'], $axisColorArray['type']);
}
if (isset($chartDetail->spPr->ln->noFill)) {
$xAxis->setNoFill(true);
}
}
if (isset($chartDetail->majorGridlines)) {
$majorGridlines = new GridLines();
if (isset($chartDetail->majorGridlines->spPr)) {
$this->readEffects($chartDetail->majorGridlines, $majorGridlines);
$this->readLineStyle($chartDetail->majorGridlines, $majorGridlines);
}
$xAxis->setMajorGridlines($majorGridlines);
}
if (isset($chartDetail->minorGridlines)) {
$minorGridlines = new GridLines();
$minorGridlines->activateObject();
if (isset($chartDetail->minorGridlines->spPr)) {
$this->readEffects($chartDetail->minorGridlines, $minorGridlines);
$this->readLineStyle($chartDetail->minorGridlines, $minorGridlines);
}
$xAxis->setMinorGridlines($minorGridlines);
}
$this->setAxisProperties($chartDetail, $xAxis);
break;
case Axis::AXIS_TYPE_VALUE:
$whichAxis = null;
$axPos = null;
if (isset($chartDetail->axPos)) {
$axPos = self::getAttributeString($chartDetail->axPos, 'val');
}
if ($catAxRead) {
$whichAxis = $yAxis;
$yAxis->setAxisType($chartDetailKey);
} elseif (!empty($axPos)) {
switch ($axPos) {
case 't':
case 'b':
$whichAxis = $xAxis;
$xAxis->setAxisType($chartDetailKey);
break;
case 'r':
case 'l':
$whichAxis = $yAxis;
$yAxis->setAxisType($chartDetailKey);
break;
}
}
if (isset($chartDetail->title)) {
$axisLabel = $this->chartTitle($chartDetail->title->children($this->cNamespace));
switch ($axPos) {
case 't':
case 'b':
$XaxisLabel = $axisLabel;
break;
case 'r':
case 'l':
$YaxisLabel = $axisLabel;
break;
}
}
$this->readEffects($chartDetail, $whichAxis);
$this->readLineStyle($chartDetail, $whichAxis);
if ($whichAxis !== null && isset($chartDetail->spPr)) {
$sppr = $chartDetail->spPr->children($this->aNamespace);
if (isset($sppr->solidFill)) {
$axisColorArray = $this->readColor($sppr->solidFill);
$whichAxis->setFillParameters($axisColorArray['value'], $axisColorArray['alpha'], $axisColorArray['type']);
}
if (isset($sppr->ln->noFill)) {
$whichAxis->setNoFill(true);
}
}
if ($whichAxis !== null && isset($chartDetail->majorGridlines)) {
$majorGridlines = new GridLines();
if (isset($chartDetail->majorGridlines->spPr)) {
$this->readEffects($chartDetail->majorGridlines, $majorGridlines);
$this->readLineStyle($chartDetail->majorGridlines, $majorGridlines);
}
$whichAxis->setMajorGridlines($majorGridlines);
}
if ($whichAxis !== null && isset($chartDetail->minorGridlines)) {
$minorGridlines = new GridLines();
$minorGridlines->activateObject();
if (isset($chartDetail->minorGridlines->spPr)) {
$this->readEffects($chartDetail->minorGridlines, $minorGridlines);
$this->readLineStyle($chartDetail->minorGridlines, $minorGridlines);
}
$whichAxis->setMinorGridlines($minorGridlines);
}
$this->setAxisProperties($chartDetail, $whichAxis);
break;
case 'barChart':
case 'bar3DChart':
$barDirection = self::getAttributeString($chartDetail->barDir, 'val');
$plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey);
$plotSer->setPlotDirection("$barDirection");
$plotSeries[] = $plotSer;
$plotAttributes = $this->readChartAttributes($chartDetail);
break;
case 'lineChart':
case 'line3DChart':
$plotSeries[] = $this->chartDataSeries($chartDetail, $chartDetailKey);
$plotAttributes = $this->readChartAttributes($chartDetail);
break;
case 'areaChart':
case 'area3DChart':
$plotSeries[] = $this->chartDataSeries($chartDetail, $chartDetailKey);
$plotAttributes = $this->readChartAttributes($chartDetail);
break;
case 'doughnutChart':
case 'pieChart':
case 'pie3DChart':
$explosion = self::getAttributeString($chartDetail->ser->explosion, 'val');
$plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey);
$plotSer->setPlotStyle("$explosion");
$plotSeries[] = $plotSer;
$plotAttributes = $this->readChartAttributes($chartDetail);
break;
case 'scatterChart':
/** @var string $scatterStyle */
$scatterStyle = self::getAttributeString($chartDetail->scatterStyle, 'val');
$plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey);
$plotSer->setPlotStyle($scatterStyle);
$plotSeries[] = $plotSer;
$plotAttributes = $this->readChartAttributes($chartDetail);
break;
case 'bubbleChart':
$bubbleScale = self::getAttributeInteger($chartDetail->bubbleScale, 'val');
$plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey);
$plotSer->setPlotStyle("$bubbleScale");
$plotSeries[] = $plotSer;
$plotAttributes = $this->readChartAttributes($chartDetail);
break;
case 'radarChart':
/** @var string $radarStyle */
$radarStyle = self::getAttributeString($chartDetail->radarStyle, 'val');
$plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey);
$plotSer->setPlotStyle($radarStyle);
$plotSeries[] = $plotSer;
$plotAttributes = $this->readChartAttributes($chartDetail);
break;
case 'surfaceChart':
case 'surface3DChart':
$wireFrame = self::getAttributeBoolean($chartDetail->wireframe, 'val');
$plotSer = $this->chartDataSeries($chartDetail, $chartDetailKey);
$plotSer->setPlotStyle("$wireFrame");
$plotSeries[] = $plotSer;
$plotAttributes = $this->readChartAttributes($chartDetail);
break;
case 'stockChart':
$plotSeries[] = $this->chartDataSeries($chartDetail, $chartDetailKey);
if (isset($chartDetail->upDownBars->gapWidth)) {
$gapWidth = self::getAttributeInteger($chartDetail->upDownBars->gapWidth, 'val');
}
if (isset($chartDetail->upDownBars->upBars)) {
$useUpBars = true;
}
if (isset($chartDetail->upDownBars->downBars)) {
$useDownBars = true;
}
$plotAttributes = $this->readChartAttributes($chartDetail);
break;
}
}
if ($plotAreaLayout == null) {
$plotAreaLayout = new Layout();
}
$plotArea = new PlotArea($plotAreaLayout, $plotSeries);
$this->setChartAttributes($plotAreaLayout, $plotAttributes);
if ($plotNoFill) {
$plotArea->setNoFill(true);
}
if (!empty($gradientArray)) {
$plotArea->setGradientFillProperties($gradientArray, $gradientLin);
}
if (is_int($gapWidth)) {
$plotArea->setGapWidth($gapWidth);
}
if ($useUpBars === true) {
$plotArea->setUseUpBars(true);
}
if ($useDownBars === true) {
$plotArea->setUseDownBars(true);
}
break;
case 'plotVisOnly':
$plotVisOnly = (bool) self::getAttributeString($chartDetails, 'val');
break;
case 'dispBlanksAs':
$dispBlanksAs = self::getAttributeString($chartDetails, 'val');
break;
case 'title':
$title = $this->chartTitle($chartDetails);
break;
case 'legend':
$legendPos = 'r';
$legendLayout = null;
$legendOverlay = false;
$legendBorderLines = null;
$legendFillColor = null;
$legendText = null;
$addLegendText = false;
foreach ($chartDetails as $chartDetailKey => $chartDetail) {
$chartDetail = Xlsx::testSimpleXml($chartDetail);
switch ($chartDetailKey) {
case 'legendPos':
$legendPos = self::getAttributeString($chartDetail, 'val');
break;
case 'overlay':
$legendOverlay = self::getAttributeBoolean($chartDetail, 'val');
break;
case 'layout':
$legendLayout = $this->chartLayoutDetails($chartDetail);
break;
case 'spPr':
$children = $chartDetails->spPr->children($this->aNamespace);
if (isset($children->solidFill)) {
$legendFillColor = $this->readColor($children->solidFill);
}
if (isset($children->ln)) {
$legendBorderLines = new GridLines();
$this->readLineStyle($chartDetails, $legendBorderLines);
}
break;
case 'txPr':
$children = $chartDetails->txPr->children($this->aNamespace);
$addLegendText = false;
$legendText = new AxisText();
if (isset($children->p->pPr->defRPr->solidFill)) {
$colorArray = $this->readColor($children->p->pPr->defRPr->solidFill);
$legendText->getFillColorObject()->setColorPropertiesArray($colorArray);
$addLegendText = true;
}
if (isset($children->p->pPr->defRPr->effectLst)) {
$this->readEffects($children->p->pPr->defRPr, $legendText, false);
$addLegendText = true;
}
break;
}
}
$legend = new Legend("$legendPos", $legendLayout, (bool) $legendOverlay);
if ($legendFillColor !== null) {
$legend->getFillColor()->setColorPropertiesArray($legendFillColor);
}
if ($legendBorderLines !== null) {
$legend->setBorderLines($legendBorderLines);
}
if ($addLegendText) {
$legend->setLegendText($legendText);
}
break;
}
}
}
}
$chart = new \PhpOffice\PhpSpreadsheet\Chart\Chart($chartName, $title, $legend, $plotArea, $plotVisOnly, (string) $dispBlanksAs, $XaxisLabel, $YaxisLabel, $xAxis, $yAxis);
if ($chartNoFill) {
$chart->setNoFill(true);
}
if ($chartFillColor !== null) {
$chart->getFillColor()->setColorPropertiesArray($chartFillColor);
}
if ($chartBorderLines !== null) {
$chart->setBorderLines($chartBorderLines);
}
$chart->setNoBorder($noBorder);
$chart->setRoundedCorners($roundedCorners);
if (is_bool($autoTitleDeleted)) {
$chart->setAutoTitleDeleted($autoTitleDeleted);
}
if (is_int($rotX)) {
$chart->setRotX($rotX);
}
if (is_int($rotY)) {
$chart->setRotY($rotY);
}
if (is_int($rAngAx)) {
$chart->setRAngAx($rAngAx);
}
if (is_int($perspective)) {
$chart->setPerspective($perspective);
}
return $chart;
}
private function chartTitle(SimpleXMLElement $titleDetails): Title
{
$caption = '';
$titleLayout = null;
$titleOverlay = false;
$titleFormula = null;
$titleFont = null;
foreach ($titleDetails as $titleDetailKey => $chartDetail) {
$chartDetail = Xlsx::testSimpleXml($chartDetail);
switch ($titleDetailKey) {
case 'tx':
$caption = [];
if (isset($chartDetail->rich)) {
$titleDetails = $chartDetail->rich->children($this->aNamespace);
foreach ($titleDetails as $titleKey => $titleDetail) {
$titleDetail = Xlsx::testSimpleXml($titleDetail);
switch ($titleKey) {
case 'p':
$titleDetailPart = $titleDetail->children($this->aNamespace);
$caption[] = $this->parseRichText($titleDetailPart);
}
}
} elseif (isset($chartDetail->strRef->strCache)) {
foreach ($chartDetail->strRef->strCache->pt as $pt) {
if (isset($pt->v)) {
$caption[] = (string) $pt->v;
}
}
if (isset($chartDetail->strRef->f)) {
$titleFormula = (string) $chartDetail->strRef->f;
}
}
break;
case 'overlay':
$titleOverlay = self::getAttributeBoolean($chartDetail, 'val');
break;
case 'layout':
$titleLayout = $this->chartLayoutDetails($chartDetail);
break;
case 'txPr':
if (isset($chartDetail->children($this->aNamespace)->p)) {
$titleFont = $this->parseFont($chartDetail->children($this->aNamespace)->p);
}
break;
}
}
$title = new Title($caption, $titleLayout, (bool) $titleOverlay);
if (!empty($titleFormula)) {
$title->setCellReference($titleFormula);
}
if ($titleFont !== null) {
$title->setFont($titleFont);
}
return $title;
}
private function chartLayoutDetails(SimpleXMLElement $chartDetail): ?Layout
{
if (!isset($chartDetail->manualLayout)) {
return null;
}
$details = $chartDetail->manualLayout->children($this->cNamespace);
if ($details === null) {
return null;
}
$layout = [];
foreach ($details as $detailKey => $detail) {
$detail = Xlsx::testSimpleXml($detail);
$layout[$detailKey] = self::getAttributeString($detail, 'val');
}
return new Layout($layout);
}
private function chartDataSeries(SimpleXMLElement $chartDetail, string $plotType): DataSeries
{
$multiSeriesType = null;
$smoothLine = false;
$seriesLabel = $seriesCategory = $seriesValues = $plotOrder = $seriesBubbles = [];
$plotDirection = null;
$seriesDetailSet = $chartDetail->children($this->cNamespace);
foreach ($seriesDetailSet as $seriesDetailKey => $seriesDetails) {
switch ($seriesDetailKey) {
case 'grouping':
$multiSeriesType = self::getAttributeString($chartDetail->grouping, 'val');
break;
case 'ser':
$marker = null;
$seriesIndex = '';
$fillColor = null;
$pointSize = null;
$noFill = false;
$bubble3D = false;
$dptColors = [];
$markerFillColor = null;
$markerBorderColor = null;
$lineStyle = null;
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | true |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php | src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class SheetViewOptions extends BaseParserClass
{
private Worksheet $worksheet;
private ?SimpleXMLElement $worksheetXml;
public function __construct(Worksheet $workSheet, ?SimpleXMLElement $worksheetXml = null)
{
$this->worksheet = $workSheet;
$this->worksheetXml = $worksheetXml;
}
public function load(bool $readDataOnly, Styles $styleReader): void
{
if ($this->worksheetXml === null) {
return;
}
if (isset($this->worksheetXml->sheetPr)) {
$sheetPr = $this->worksheetXml->sheetPr;
$this->tabColor($sheetPr, $styleReader);
$this->codeName($sheetPr);
$this->outlines($sheetPr);
$this->pageSetup($sheetPr);
}
if (isset($this->worksheetXml->sheetFormatPr)) {
$this->sheetFormat($this->worksheetXml->sheetFormatPr);
}
if (!$readDataOnly && isset($this->worksheetXml->printOptions)) {
$this->printOptions($this->worksheetXml->printOptions);
}
}
private function tabColor(SimpleXMLElement $sheetPr, Styles $styleReader): void
{
if (isset($sheetPr->tabColor)) {
$this->worksheet->getTabColor()->setARGB($styleReader->readColor($sheetPr->tabColor));
}
}
private function codeName(SimpleXMLElement $sheetPrx): void
{
$sheetPr = $sheetPrx->attributes() ?? [];
if (isset($sheetPr['codeName'])) {
$this->worksheet->setCodeName((string) $sheetPr['codeName'], false);
}
}
private function outlines(SimpleXMLElement $sheetPr): void
{
if (isset($sheetPr->outlinePr)) {
$attr = $sheetPr->outlinePr->attributes() ?? [];
if (
isset($attr['summaryRight'])
&& !self::boolean((string) $attr['summaryRight'])
) {
$this->worksheet->setShowSummaryRight(false);
} else {
$this->worksheet->setShowSummaryRight(true);
}
if (
isset($attr['summaryBelow'])
&& !self::boolean((string) $attr['summaryBelow'])
) {
$this->worksheet->setShowSummaryBelow(false);
} else {
$this->worksheet->setShowSummaryBelow(true);
}
}
}
private function pageSetup(SimpleXMLElement $sheetPr): void
{
if (isset($sheetPr->pageSetUpPr)) {
$attr = $sheetPr->pageSetUpPr->attributes() ?? [];
if (
isset($attr['fitToPage'])
&& !self::boolean((string) $attr['fitToPage'])
) {
$this->worksheet->getPageSetup()->setFitToPage(false);
} else {
$this->worksheet->getPageSetup()->setFitToPage(true);
}
}
}
private function sheetFormat(SimpleXMLElement $sheetFormatPrx): void
{
$sheetFormatPr = $sheetFormatPrx->attributes() ?? [];
if (
isset($sheetFormatPr['customHeight'])
&& self::boolean((string) $sheetFormatPr['customHeight'])
&& isset($sheetFormatPr['defaultRowHeight'])
) {
$this->worksheet->getDefaultRowDimension()
->setRowHeight((float) $sheetFormatPr['defaultRowHeight']);
}
if (isset($sheetFormatPr['defaultColWidth'])) {
$this->worksheet->getDefaultColumnDimension()
->setWidth((float) $sheetFormatPr['defaultColWidth']);
}
if (
isset($sheetFormatPr['zeroHeight'])
&& ((string) $sheetFormatPr['zeroHeight'] === '1')
) {
$this->worksheet->getDefaultRowDimension()->setZeroHeight(true);
}
}
private function printOptions(SimpleXMLElement $printOptionsx): void
{
$printOptions = $printOptionsx->attributes() ?? [];
// Spec is weird. gridLines (default false)
// and gridLinesSet (default true) must both be true.
if (isset($printOptions['gridLines']) && self::boolean((string) $printOptions['gridLines'])) {
if (!isset($printOptions['gridLinesSet']) || self::boolean((string) $printOptions['gridLinesSet'])) {
$this->worksheet->setPrintGridlines(true);
}
}
if (isset($printOptions['horizontalCentered']) && self::boolean((string) $printOptions['horizontalCentered'])) {
$this->worksheet->getPageSetup()->setHorizontalCentered(true);
}
if (isset($printOptions['verticalCentered']) && self::boolean((string) $printOptions['verticalCentered'])) {
$this->worksheet->getPageSetup()->setVerticalCentered(true);
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php | src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter;
use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class ColumnAndRowAttributes extends BaseParserClass
{
private Worksheet $worksheet;
private ?SimpleXMLElement $worksheetXml;
public function __construct(Worksheet $workSheet, ?SimpleXMLElement $worksheetXml = null)
{
$this->worksheet = $workSheet;
$this->worksheetXml = $worksheetXml;
}
/**
* Set Worksheet column attributes by attributes array passed.
*
* @param string $columnAddress A, B, ... DX, ...
* @param array{xfIndex?: int, visible?: bool, collapsed?: bool, collapsed?: bool, outlineLevel?: int, rowHeight?: float, width?: int} $columnAttributes array of attributes (indexes are attribute name, values are value)
*/
private function setColumnAttributes(string $columnAddress, array $columnAttributes): void
{
if (isset($columnAttributes['xfIndex'])) {
$this->worksheet->getColumnDimension($columnAddress)->setXfIndex($columnAttributes['xfIndex']);
}
if (isset($columnAttributes['visible'])) {
$this->worksheet->getColumnDimension($columnAddress)->setVisible($columnAttributes['visible']);
}
if (isset($columnAttributes['collapsed'])) {
$this->worksheet->getColumnDimension($columnAddress)->setCollapsed($columnAttributes['collapsed']);
}
if (isset($columnAttributes['outlineLevel'])) {
$this->worksheet->getColumnDimension($columnAddress)->setOutlineLevel($columnAttributes['outlineLevel']);
}
if (isset($columnAttributes['width'])) {
$this->worksheet->getColumnDimension($columnAddress)->setWidth($columnAttributes['width']);
}
}
/**
* Set Worksheet row attributes by attributes array passed.
*
* @param int $rowNumber 1, 2, 3, ... 99, ...
* @param array{xfIndex?: int, visible?: bool, collapsed?: bool, collapsed?: bool, outlineLevel?: int, rowHeight?: float, customFormat?: bool, ht?: float} $rowAttributes array of attributes (indexes are attribute name, values are value)
* 'xfIndex', 'visible', 'collapsed', 'outlineLevel', 'rowHeight', ... ?
*/
private function setRowAttributes(int $rowNumber, array $rowAttributes): void
{
if (isset($rowAttributes['xfIndex'])) {
$this->worksheet->getRowDimension($rowNumber)
->setXfIndex($rowAttributes['xfIndex']);
}
if (isset($rowAttributes['visible'])) {
$this->worksheet->getRowDimension($rowNumber)
->setVisible($rowAttributes['visible']);
}
if (isset($rowAttributes['collapsed'])) {
$this->worksheet->getRowDimension($rowNumber)
->setCollapsed($rowAttributes['collapsed']);
}
if (isset($rowAttributes['outlineLevel'])) {
$this->worksheet->getRowDimension($rowNumber)
->setOutlineLevel($rowAttributes['outlineLevel']);
}
if (isset($rowAttributes['customFormat'], $rowAttributes['rowHeight'])) {
$this->worksheet->getRowDimension($rowNumber)
->setCustomFormat($rowAttributes['customFormat'], $rowAttributes['rowHeight']);
} elseif (isset($rowAttributes['rowHeight'])) {
$this->worksheet->getRowDimension($rowNumber)
->setRowHeight($rowAttributes['rowHeight']);
}
}
public function load(?IReadFilter $readFilter = null, bool $readDataOnly = false, bool $ignoreRowsWithNoCells = false): bool
{
if ($this->worksheetXml === null) {
return false;
}
if ($readFilter !== null && $readFilter::class === DefaultReadFilter::class) {
$readFilter = null;
}
$columnsAttributes = [];
$rowsAttributes = [];
if (isset($this->worksheetXml->cols)) {
$columnsAttributes = $this->readColumnAttributes($this->worksheetXml->cols, $readDataOnly);
}
if ($this->worksheetXml->sheetData && $this->worksheetXml->sheetData->row) {
$rowsAttributes = $this->readRowAttributes($this->worksheetXml->sheetData->row, $readDataOnly, $ignoreRowsWithNoCells, $readFilter !== null);
}
// set columns/rows attributes
$columnsAttributesAreSet = [];
foreach ($columnsAttributes as $columnCoordinate => $columnAttributes) {
if (
$readFilter === null
|| !$this->isFilteredColumn($readFilter, $columnCoordinate, $rowsAttributes)
) {
if (!isset($columnsAttributesAreSet[$columnCoordinate])) {
/** @var array{xfIndex?: int, visible?: bool, collapsed?: bool, collapsed?: bool, outlineLevel?: int, rowHeight?: float, width?: int} $columnAttributes */
$this->setColumnAttributes($columnCoordinate, $columnAttributes);
$columnsAttributesAreSet[$columnCoordinate] = true;
}
}
}
$rowsAttributesAreSet = [];
foreach ($rowsAttributes as $rowCoordinate => $rowAttributes) {
if (
$readFilter === null
|| !$this->isFilteredRow($readFilter, $rowCoordinate, $columnsAttributes)
) {
if (!isset($rowsAttributesAreSet[$rowCoordinate])) {
/** @var array{xfIndex?: int, visible?: bool, collapsed?: bool, collapsed?: bool, outlineLevel?: int, rowHeight?: float} $rowAttributes */
$this->setRowAttributes($rowCoordinate, $rowAttributes);
$rowsAttributesAreSet[$rowCoordinate] = true;
}
}
}
return true;
}
/** @param mixed[] $rowsAttributes */
private function isFilteredColumn(IReadFilter $readFilter, string $columnCoordinate, array $rowsAttributes): bool
{
foreach ($rowsAttributes as $rowCoordinate => $rowAttributes) {
if ($readFilter->readCell($columnCoordinate, $rowCoordinate, $this->worksheet->getTitle())) {
return false;
}
}
return true;
}
/** @return mixed[] */
private function readColumnAttributes(SimpleXMLElement $worksheetCols, bool $readDataOnly): array
{
$columnAttributes = [];
foreach ($worksheetCols->col as $columnx) {
$column = $columnx->attributes();
if ($column !== null) {
$startColumn = Coordinate::stringFromColumnIndex((int) $column['min']);
$endColumn = Coordinate::stringFromColumnIndex((int) $column['max']);
StringHelper::stringIncrement($endColumn);
for ($columnAddress = $startColumn; $columnAddress !== $endColumn; StringHelper::stringIncrement($columnAddress)) {
$columnAttributes[$columnAddress] = $this->readColumnRangeAttributes($column, $readDataOnly);
if ((int) ($column['max']) == 16384) {
break;
}
}
}
}
return $columnAttributes;
}
/** @return mixed[] */
private function readColumnRangeAttributes(?SimpleXMLElement $column, bool $readDataOnly): array
{
$columnAttributes = [];
if ($column !== null) {
if (isset($column['style']) && !$readDataOnly) {
$columnAttributes['xfIndex'] = (int) $column['style'];
}
if (isset($column['hidden']) && self::boolean($column['hidden'])) {
$columnAttributes['visible'] = false;
}
if (isset($column['collapsed']) && self::boolean($column['collapsed'])) {
$columnAttributes['collapsed'] = true;
}
if (isset($column['outlineLevel']) && ((int) $column['outlineLevel']) > 0) {
$columnAttributes['outlineLevel'] = (int) $column['outlineLevel'];
}
if (isset($column['width'])) {
$columnAttributes['width'] = (float) $column['width'];
}
}
return $columnAttributes;
}
/** @param mixed[] $columnsAttributes */
private function isFilteredRow(IReadFilter $readFilter, int $rowCoordinate, array $columnsAttributes): bool
{
foreach ($columnsAttributes as $columnCoordinate => $columnAttributes) {
if (!$readFilter->readCell($columnCoordinate, $rowCoordinate, $this->worksheet->getTitle())) {
return true;
}
}
return false;
}
/** @return mixed[] */
private function readRowAttributes(SimpleXMLElement $worksheetRow, bool $readDataOnly, bool $ignoreRowsWithNoCells, bool $readFilterIsNotNull): array
{
$rowAttributes = [];
foreach ($worksheetRow as $rowx) {
$row = $rowx->attributes();
if ($row !== null && (!$ignoreRowsWithNoCells || isset($rowx->c))) {
$rowIndex = (int) $row['r'];
if (!$readDataOnly) {
if (isset($row['ht'])) {
$rowAttributes[$rowIndex]['rowHeight'] = (float) $row['ht'];
}
if (isset($row['customFormat']) && self::boolean($row['customFormat'])) {
$rowAttributes[$rowIndex]['customFormat'] = true;
}
if (isset($row['hidden']) && self::boolean($row['hidden'])) {
$rowAttributes[$rowIndex]['visible'] = false;
}
if (isset($row['collapsed']) && self::boolean($row['collapsed'])) {
$rowAttributes[$rowIndex]['collapsed'] = true;
}
if (isset($row['outlineLevel']) && (int) $row['outlineLevel'] > 0) {
$rowAttributes[$rowIndex]['outlineLevel'] = (int) $row['outlineLevel'];
}
if (isset($row['s'])) {
$rowAttributes[$rowIndex]['xfIndex'] = (int) $row['s'];
}
}
if ($readFilterIsNotNull && empty($rowAttributes[$rowIndex])) {
$rowAttributes[$rowIndex]['exists'] = true;
}
}
}
return $rowAttributes;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php | src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Styles as StyleReader;
use PhpOffice\PhpSpreadsheet\Style\Color;
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\ConditionalFormatValueObject;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalIconSet;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\IconSetValues;
use PhpOffice\PhpSpreadsheet\Style\Style as Style;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
use stdClass;
class ConditionalStyles
{
private Worksheet $worksheet;
private SimpleXMLElement $worksheetXml;
/** @var string[] */
private array $ns;
/** @var Style[] */
private array $dxfs;
private StyleReader $styleReader;
/** @param Style[] $dxfs */
public function __construct(Worksheet $workSheet, SimpleXMLElement $worksheetXml, array $dxfs, StyleReader $styleReader)
{
$this->worksheet = $workSheet;
$this->worksheetXml = $worksheetXml;
$this->dxfs = $dxfs;
$this->styleReader = $styleReader;
}
public function load(): void
{
$selectedCells = $this->worksheet->getSelectedCells();
$this->setConditionalStyles(
$this->worksheet,
$this->readConditionalStyles($this->worksheetXml),
$this->worksheetXml->extLst
);
$this->worksheet->setSelectedCells($selectedCells);
}
public function loadFromExt(): void
{
$selectedCells = $this->worksheet->getSelectedCells();
$this->ns = $this->worksheetXml->getNamespaces(true);
$this->setConditionalsFromExt(
$this->readConditionalsFromExt($this->worksheetXml->extLst)
);
$this->worksheet->setSelectedCells($selectedCells);
}
/** @param Conditional[][] $conditionals */
private function setConditionalsFromExt(array $conditionals): void
{
foreach ($conditionals as $conditionalRange => $cfRules) {
ksort($cfRules);
// Priority is used as the key for sorting; but may not start at 0,
// so we use array_values to reset the index after sorting.
$existing = $this->worksheet->getConditionalStylesCollection();
if (array_key_exists($conditionalRange, $existing)) {
$conditionalStyle = $existing[$conditionalRange];
$cfRules = array_merge($conditionalStyle, $cfRules);
}
$this->worksheet->getStyle($conditionalRange)
->setConditionalStyles(array_values($cfRules));
}
}
/** @return array<string, array<int, Conditional>> */
private function readConditionalsFromExt(SimpleXMLElement $extLst): array
{
$conditionals = [];
if (!isset($extLst->ext)) {
return $conditionals;
}
foreach ($extLst->ext as $extlstcond) {
$extAttrs = $extlstcond->attributes() ?? [];
$extUri = (string) ($extAttrs['uri'] ?? '');
if ($extUri !== '{78C0D931-6437-407d-A8EE-F0AAD7539E65}') {
continue;
}
$conditionalFormattingRuleXml = $extlstcond->children($this->ns['x14']);
if (!$conditionalFormattingRuleXml->conditionalFormattings) {
return [];
}
foreach ($conditionalFormattingRuleXml->children($this->ns['x14']) as $extFormattingXml) {
$extFormattingRangeXml = $extFormattingXml->children($this->ns['xm']);
if (!$extFormattingRangeXml->sqref) {
continue;
}
$sqref = (string) $extFormattingRangeXml->sqref;
$extCfRuleXml = $extFormattingXml->cfRule;
$attributes = $extCfRuleXml->attributes();
if (!$attributes) {
continue;
}
$conditionType = (string) $attributes->type;
if (
!Conditional::isValidConditionType($conditionType)
|| $conditionType === Conditional::CONDITION_DATABAR
) {
continue;
}
$priority = (int) $attributes->priority;
$conditional = $this->readConditionalRuleFromExt($extCfRuleXml, $attributes);
$cfStyle = $this->readStyleFromExt($extCfRuleXml);
$conditional->setStyle($cfStyle);
$conditionals[$sqref][$priority] = $conditional;
}
}
return $conditionals;
}
private function readConditionalRuleFromExt(SimpleXMLElement $cfRuleXml, SimpleXMLElement $attributes): Conditional
{
$conditionType = (string) $attributes->type;
$operatorType = (string) $attributes->operator;
$priority = (int) (string) $attributes->priority;
$stopIfTrue = (int) (string) $attributes->stopIfTrue;
$operands = [];
foreach ($cfRuleXml->children($this->ns['xm']) as $cfRuleOperandsXml) {
$operands[] = (string) $cfRuleOperandsXml;
}
$conditional = new Conditional();
$conditional->setConditionType($conditionType);
$conditional->setOperatorType($operatorType);
$conditional->setPriority($priority);
$conditional->setStopIfTrue($stopIfTrue === 1);
if (
$conditionType === Conditional::CONDITION_CONTAINSTEXT
|| $conditionType === Conditional::CONDITION_NOTCONTAINSTEXT
|| $conditionType === Conditional::CONDITION_BEGINSWITH
|| $conditionType === Conditional::CONDITION_ENDSWITH
|| $conditionType === Conditional::CONDITION_TIMEPERIOD
) {
$conditional->setText(array_pop($operands) ?? '');
}
$conditional->setConditions($operands);
return $conditional;
}
private function readStyleFromExt(SimpleXMLElement $extCfRuleXml): Style
{
$cfStyle = new Style(false, true);
if ($extCfRuleXml->dxf) {
$styleXML = $extCfRuleXml->dxf->children();
if ($styleXML->borders) {
$this->styleReader->readBorderStyle($cfStyle->getBorders(), $styleXML->borders);
}
if ($styleXML->fill) {
$this->styleReader->readFillStyle($cfStyle->getFill(), $styleXML->fill);
}
if ($styleXML->font) {
$this->styleReader->readFontStyle($cfStyle->getFont(), $styleXML->font);
}
}
return $cfStyle;
}
/** @return mixed[] */
private function readConditionalStyles(SimpleXMLElement $xmlSheet): array
{
$conditionals = [];
foreach ($xmlSheet->conditionalFormatting as $conditional) {
foreach ($conditional->cfRule as $cfRule) {
if (Conditional::isValidConditionType((string) $cfRule['type']) && (!isset($cfRule['dxfId']) || isset($this->dxfs[(int) ($cfRule['dxfId'])]))) {
$conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule;
} elseif ((string) $cfRule['type'] == Conditional::CONDITION_DATABAR) {
$conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule;
}
}
}
return $conditionals;
}
/** @param mixed[] $conditionals */
private function setConditionalStyles(Worksheet $worksheet, array $conditionals, SimpleXMLElement $xmlExtLst): void
{
foreach ($conditionals as $cellRangeReference => $cfRules) {
/** @var mixed[] $cfRules */
ksort($cfRules); // no longer needed for Xlsx, but helps Xls
$conditionalStyles = $this->readStyleRules($cfRules, $xmlExtLst);
// Extract all cell references in $cellRangeReference
// N.B. In Excel UI, intersection is space and union is comma.
// But in Xml, intersection is comma and union is space.
$cellRangeReference = str_replace(['$', ' ', ',', '^'], ['', '^', ' ', ','], strtoupper($cellRangeReference));
foreach ($conditionalStyles as $cs) {
$scale = $cs->getColorScale();
if ($scale !== null) {
$scale->setSqRef($cellRangeReference, $worksheet);
}
}
$worksheet->getStyle($cellRangeReference)->setConditionalStyles($conditionalStyles);
}
}
/**
* @param mixed[] $cfRules
*
* @return Conditional[]
*/
private function readStyleRules(array $cfRules, SimpleXMLElement $extLst): array
{
/** @var ConditionalFormattingRuleExtension[] */
$conditionalFormattingRuleExtensions = ConditionalFormattingRuleExtension::parseExtLstXml($extLst);
$conditionalStyles = [];
/** @var SimpleXMLElement $cfRule */
foreach ($cfRules as $cfRule) {
$objConditional = new Conditional();
$objConditional->setConditionType((string) $cfRule['type']);
$objConditional->setOperatorType((string) $cfRule['operator']);
$objConditional->setPriority((int) (string) $cfRule['priority']);
$objConditional->setNoFormatSet(!isset($cfRule['dxfId']));
if ((string) $cfRule['text'] != '') {
$objConditional->setText((string) $cfRule['text']);
} elseif ((string) $cfRule['timePeriod'] != '') {
$objConditional->setText((string) $cfRule['timePeriod']);
}
if (isset($cfRule['stopIfTrue']) && (int) $cfRule['stopIfTrue'] === 1) {
$objConditional->setStopIfTrue(true);
}
if (count($cfRule->formula) >= 1) {
foreach ($cfRule->formula as $formulax) {
$formula = (string) $formulax;
$formula = str_replace(['_xlfn.', '_xlws.'], '', $formula);
if ($formula === 'TRUE') {
$objConditional->addCondition(true);
} elseif ($formula === 'FALSE') {
$objConditional->addCondition(false);
} else {
$objConditional->addCondition($formula);
}
}
} else {
$objConditional->addCondition('');
}
if (isset($cfRule->dataBar)) {
$objConditional->setDataBar(
$this->readDataBarOfConditionalRule($cfRule, $conditionalFormattingRuleExtensions)
);
} elseif (isset($cfRule->colorScale)) {
$objConditional->setColorScale(
$this->readColorScale($cfRule)
);
} elseif (isset($cfRule->iconSet)) {
$objConditional->setIconSet($this->readIconSet($cfRule));
} elseif (isset($cfRule['dxfId'])) {
$objConditional->setStyle(clone $this->dxfs[(int) ($cfRule['dxfId'])]);
}
$conditionalStyles[] = $objConditional;
}
return $conditionalStyles;
}
/** @param ConditionalFormattingRuleExtension[] $conditionalFormattingRuleExtensions */
private function readDataBarOfConditionalRule(SimpleXMLElement $cfRule, array $conditionalFormattingRuleExtensions): ConditionalDataBar
{
$dataBar = new ConditionalDataBar();
//dataBar attribute
if (isset($cfRule->dataBar['showValue'])) {
$dataBar->setShowValue((bool) $cfRule->dataBar['showValue']);
}
//dataBar children
//conditionalFormatValueObjects
$cfvoXml = $cfRule->dataBar->cfvo;
$cfvoIndex = 0;
foreach ((count($cfvoXml) > 1 ? $cfvoXml : [$cfvoXml]) as $cfvo) { //* @phpstan-ignore-line
/** @var SimpleXMLElement $cfvo */
if ($cfvoIndex === 0) {
$dataBar->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $cfvo['type'], (string) $cfvo['val']));
}
if ($cfvoIndex === 1) {
$dataBar->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $cfvo['type'], (string) $cfvo['val']));
}
++$cfvoIndex;
}
//color
if (isset($cfRule->dataBar->color)) {
$dataBar->setColor($this->styleReader->readColor($cfRule->dataBar->color));
}
//extLst
$this->readDataBarExtLstOfConditionalRule($dataBar, $cfRule, $conditionalFormattingRuleExtensions);
return $dataBar;
}
private function readColorScale(SimpleXMLElement|stdClass $cfRule): ConditionalColorScale
{
$colorScale = new ConditionalColorScale();
/** @var SimpleXMLElement $cfRule */
$count = count($cfRule->colorScale->cfvo);
$idx = 0;
foreach ($cfRule->colorScale->cfvo as $cfvoXml) {
$attr = $cfvoXml->attributes() ?? [];
$type = (string) ($attr['type'] ?? '');
$val = $attr['val'] ?? null;
if ($idx === 0) {
$method = 'setMinimumConditionalFormatValueObject';
} elseif ($idx === 1 && $count === 3) {
$method = 'setMidpointConditionalFormatValueObject';
} else {
$method = 'setMaximumConditionalFormatValueObject';
}
if ($type !== 'formula') {
$colorScale->$method(new ConditionalFormatValueObject($type, $val));
} else {
$colorScale->$method(new ConditionalFormatValueObject($type, null, $val));
}
++$idx;
}
$idx = 0;
foreach ($cfRule->colorScale->color as $color) {
$rgb = $this->styleReader->readColor($color);
if ($idx === 0) {
$colorScale->setMinimumColor(new Color($rgb));
} elseif ($idx === 1 && $count === 3) {
$colorScale->setMidpointColor(new Color($rgb));
} else {
$colorScale->setMaximumColor(new Color($rgb));
}
++$idx;
}
return $colorScale;
}
private function readIconSet(SimpleXMLElement $cfRule): ConditionalIconSet
{
$iconSet = new ConditionalIconSet();
if (isset($cfRule->iconSet['iconSet'])) {
$iconSet->setIconSetType(IconSetValues::from($cfRule->iconSet['iconSet']));
}
if (isset($cfRule->iconSet['reverse'])) {
$iconSet->setReverse('1' === (string) $cfRule->iconSet['reverse']);
}
if (isset($cfRule->iconSet['showValue'])) {
$iconSet->setShowValue('1' === (string) $cfRule->iconSet['showValue']);
}
if (isset($cfRule->iconSet['custom'])) {
$iconSet->setCustom('1' === (string) $cfRule->iconSet['custom']);
}
$cfvos = [];
foreach ($cfRule->iconSet->cfvo as $cfvoXml) {
$type = (string) $cfvoXml['type'];
$value = (string) ($cfvoXml['val'] ?? '');
$cfvo = new ConditionalFormatValueObject($type, $value);
if (isset($cfvoXml['gte'])) {
$cfvo->setGreaterThanOrEqual('1' === (string) $cfvoXml['gte']);
}
$cfvos[] = $cfvo;
}
$iconSet->setCfvos($cfvos);
// TODO: The cfIcon element is not implemented yet.
return $iconSet;
}
/** @param ConditionalFormattingRuleExtension[] $conditionalFormattingRuleExtensions */
private function readDataBarExtLstOfConditionalRule(ConditionalDataBar $dataBar, SimpleXMLElement $cfRule, array $conditionalFormattingRuleExtensions): void
{
if (isset($cfRule->extLst)) {
$ns = $cfRule->extLst->getNamespaces(true);
foreach ((count($cfRule->extLst) > 0 ? $cfRule->extLst->ext : [$cfRule->extLst->ext]) as $ext) { //* @phpstan-ignore-line
/** @var SimpleXMLElement $ext */
$extId = (string) $ext->children($ns['x14'])->id;
if (isset($conditionalFormattingRuleExtensions[$extId]) && (string) $ext['uri'] === '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}') {
$dataBar->setConditionalFormattingRuleExt($conditionalFormattingRuleExtensions[$extId]);
}
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php | src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Pane;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class SheetViews extends BaseParserClass
{
private SimpleXMLElement $sheetViewXml;
private SimpleXMLElement $sheetViewAttributes;
private Worksheet $worksheet;
private string $activePane = '';
public function __construct(SimpleXMLElement $sheetViewXml, Worksheet $workSheet)
{
$this->sheetViewXml = $sheetViewXml;
$this->sheetViewAttributes = Xlsx::testSimpleXml($sheetViewXml->attributes());
$this->worksheet = $workSheet;
}
public function load(): void
{
$this->topLeft();
$this->zoomScale();
$this->view();
$this->gridLines();
$this->headers();
$this->direction();
$this->showZeros();
$usesPanes = false;
if (isset($this->sheetViewXml->pane)) {
$this->pane();
$usesPanes = true;
}
if (isset($this->sheetViewXml->selection)) {
foreach ($this->sheetViewXml->selection as $selection) {
$this->selection($selection, $usesPanes);
}
}
}
private function zoomScale(): void
{
if (isset($this->sheetViewAttributes->zoomScale)) {
$zoomScale = (int) ($this->sheetViewAttributes->zoomScale);
if ($zoomScale <= 0) {
// setZoomScale will throw an Exception if the scale is less than or equals 0
// that is OK when manually creating documents, but we should be able to read all documents
$zoomScale = 100;
}
$this->worksheet->getSheetView()->setZoomScale($zoomScale);
}
if (isset($this->sheetViewAttributes->zoomScaleNormal)) {
$zoomScaleNormal = (int) ($this->sheetViewAttributes->zoomScaleNormal);
if ($zoomScaleNormal <= 0) {
// setZoomScaleNormal will throw an Exception if the scale is less than or equals 0
// that is OK when manually creating documents, but we should be able to read all documents
$zoomScaleNormal = 100;
}
$this->worksheet->getSheetView()->setZoomScaleNormal($zoomScaleNormal);
}
if (isset($this->sheetViewAttributes->zoomScalePageLayoutView)) {
$zoomScaleNormal = (int) ($this->sheetViewAttributes->zoomScalePageLayoutView);
if ($zoomScaleNormal > 0) {
$this->worksheet->getSheetView()->setZoomScalePageLayoutView($zoomScaleNormal);
}
}
if (isset($this->sheetViewAttributes->zoomScaleSheetLayoutView)) {
$zoomScaleNormal = (int) ($this->sheetViewAttributes->zoomScaleSheetLayoutView);
if ($zoomScaleNormal > 0) {
$this->worksheet->getSheetView()->setZoomScaleSheetLayoutView($zoomScaleNormal);
}
}
}
private function view(): void
{
if (isset($this->sheetViewAttributes->view)) {
$this->worksheet->getSheetView()->setView((string) $this->sheetViewAttributes->view);
}
}
private function topLeft(): void
{
if (isset($this->sheetViewAttributes->topLeftCell)) {
$this->worksheet->setTopLeftCell($this->sheetViewAttributes->topLeftCell);
}
}
private function gridLines(): void
{
if (isset($this->sheetViewAttributes->showGridLines)) {
$this->worksheet->setShowGridLines(
self::boolean((string) $this->sheetViewAttributes->showGridLines)
);
}
}
private function headers(): void
{
if (isset($this->sheetViewAttributes->showRowColHeaders)) {
$this->worksheet->setShowRowColHeaders(
self::boolean((string) $this->sheetViewAttributes->showRowColHeaders)
);
}
}
private function direction(): void
{
if (isset($this->sheetViewAttributes->rightToLeft)) {
$this->worksheet->setRightToLeft(
self::boolean((string) $this->sheetViewAttributes->rightToLeft)
);
}
}
private function showZeros(): void
{
if (isset($this->sheetViewAttributes->showZeros)) {
$this->worksheet->getSheetView()->setShowZeros(
self::boolean((string) $this->sheetViewAttributes->showZeros)
);
}
}
private function pane(): void
{
$xSplit = 0;
$ySplit = 0;
$topLeftCell = null;
$paneAttributes = $this->sheetViewXml->pane->attributes();
if (isset($paneAttributes->xSplit)) {
$xSplit = (int) ($paneAttributes->xSplit);
$this->worksheet->setXSplit($xSplit);
}
if (isset($paneAttributes->ySplit)) {
$ySplit = (int) ($paneAttributes->ySplit);
$this->worksheet->setYSplit($ySplit);
}
$paneState = isset($paneAttributes->state) ? ((string) $paneAttributes->state) : '';
$this->worksheet->setPaneState($paneState);
if (isset($paneAttributes->topLeftCell)) {
$topLeftCell = (string) $paneAttributes->topLeftCell;
$this->worksheet->setPaneTopLeftCell($topLeftCell);
if ($paneState === Worksheet::PANE_FROZEN) {
$this->worksheet->setTopLeftCell($topLeftCell);
}
}
$activePane = isset($paneAttributes->activePane) ? ((string) $paneAttributes->activePane) : 'topLeft';
$this->worksheet->setActivePane($activePane);
$this->activePane = $activePane;
if ($paneState === Worksheet::PANE_FROZEN || $paneState === Worksheet::PANE_FROZENSPLIT) {
$this->worksheet->freezePane(
Coordinate::stringFromColumnIndex($xSplit + 1) . ($ySplit + 1),
$topLeftCell,
$paneState === Worksheet::PANE_FROZENSPLIT
);
}
}
private function selection(?SimpleXMLElement $selection, bool $usesPanes): void
{
$attributes = ($selection === null) ? null : $selection->attributes();
if ($attributes !== null) {
$position = (string) $attributes->pane;
if ($usesPanes && $position === '') {
$position = 'topLeft';
}
$activeCell = (string) $attributes->activeCell;
$sqref = (string) $attributes->sqref;
$sqref = explode(' ', $sqref);
$sqref = $sqref[0];
if ($position === '') {
$this->worksheet->setSelectedCells($sqref);
} else {
$pane = new Pane($position, $sqref, $activeCell);
$this->worksheet->setPane($position, $pane);
if ($position === $this->activePane && $sqref !== '') {
$this->worksheet->setSelectedCells($sqref);
}
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Reader/Security/XmlScanner.php | src/PhpSpreadsheet/Reader/Security/XmlScanner.php | <?php
namespace PhpOffice\PhpSpreadsheet\Reader\Security;
use PhpOffice\PhpSpreadsheet\Reader;
class XmlScanner
{
private const ENCODING_PATTERN = '/encoding\s*=\s*(["\'])(.+?)\1/s';
private const ENCODING_UTF7 = '/encoding\s*=\s*(["\'])UTF-7\1/si';
private string $pattern;
/** @var ?callable */
private $callback;
public function __construct(string $pattern = '<!DOCTYPE')
{
$this->pattern = $pattern;
}
public static function getInstance(Reader\IReader $reader): self
{
$pattern = ($reader instanceof Reader\Html) ? '<!ENTITY' : '<!DOCTYPE';
return new self($pattern);
}
public function setAdditionalCallback(callable $callback): void
{
$this->callback = $callback;
}
private static function forceString(mixed $arg): string
{
return is_string($arg) ? $arg : '';
}
private function toUtf8(string $xml): string
{
$charset = $this->findCharSet($xml);
$foundUtf7 = $charset === 'UTF-7';
if ($charset !== 'UTF-8') {
$testStart = '/^.{0,4}\s*<?xml/s';
$startWithXml1 = preg_match($testStart, $xml);
$xml = self::forceString(mb_convert_encoding($xml, 'UTF-8', $charset));
if ($startWithXml1 === 1 && preg_match($testStart, $xml) !== 1) {
throw new Reader\Exception('Double encoding not permitted');
}
$foundUtf7 = $foundUtf7 || (preg_match(self::ENCODING_UTF7, $xml) === 1);
$xml = preg_replace(self::ENCODING_PATTERN, '', $xml) ?? $xml;
} else {
$foundUtf7 = $foundUtf7 || (preg_match(self::ENCODING_UTF7, $xml) === 1);
}
if ($foundUtf7) {
throw new Reader\Exception('UTF-7 encoding not permitted');
}
if (substr($xml, 0, Reader\Csv::UTF8_BOM_LEN) === Reader\Csv::UTF8_BOM) {
$xml = substr($xml, Reader\Csv::UTF8_BOM_LEN);
}
return $xml;
}
private function findCharSet(string $xml): string
{
if (str_starts_with($xml, "\x4c\x6f\xa7\x94")) {
throw new Reader\Exception('EBCDIC encoding not permitted');
}
$encoding = Reader\Csv::guessEncodingBom('', $xml);
if ($encoding !== '') {
return $encoding;
}
$xml = str_replace("\0", '', $xml);
if (preg_match(self::ENCODING_PATTERN, $xml, $matches)) {
return strtoupper($matches[2]);
}
return 'UTF-8';
}
/**
* Scan the XML for use of <!ENTITY to prevent XXE/XEE attacks.
*
* @param false|string $xml
*/
public function scan($xml): string
{
// Don't rely purely on libxml_disable_entity_loader()
$pattern = '/\0*' . implode('\0*', mb_str_split($this->pattern, 1, 'UTF-8')) . '\0*/';
$xml = "$xml";
if (preg_match($pattern, $xml)) {
throw new Reader\Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks');
}
$xml = $this->toUtf8($xml);
if (preg_match($pattern, $xml)) {
throw new Reader\Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks');
}
if ($this->callback !== null) {
$xml = call_user_func($this->callback, $xml);
}
/** @var string $xml */
return $xml;
}
/**
* Scan the XML for use of <!ENTITY to prevent XXE/XEE attacks.
*/
public function scanFile(string $filestream): string
{
return $this->scan(file_get_contents($filestream));
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/RowCellIterator.php | src/PhpSpreadsheet/Worksheet/RowCellIterator.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
/**
* @extends CellIterator<string>
*/
class RowCellIterator extends CellIterator
{
/**
* Current iterator position.
*/
private int $currentColumnIndex;
/**
* Row index.
*/
private int $rowIndex;
/**
* Start position.
*/
private int $startColumnIndex = 1;
/**
* End position.
*/
private int $endColumnIndex = 1;
/**
* Create a new column iterator.
*
* @param Worksheet $worksheet The worksheet to iterate over
* @param int $rowIndex The row that we want to iterate
* @param string $startColumn The column address at which to start iterating
* @param ?string $endColumn Optionally, the column address at which to stop iterating
*/
public function __construct(Worksheet $worksheet, int $rowIndex = 1, string $startColumn = 'A', ?string $endColumn = null, bool $iterateOnlyExistingCells = false)
{
// Set subject and row index
$this->worksheet = $worksheet;
$this->cellCollection = $worksheet->getCellCollection();
$this->rowIndex = $rowIndex;
$this->resetEnd($endColumn);
$this->resetStart($startColumn);
$this->setIterateOnlyExistingCells($iterateOnlyExistingCells);
}
/**
* (Re)Set the start column and the current column pointer.
*
* @param string $startColumn The column address at which to start iterating
*
* @return $this
*/
public function resetStart(string $startColumn = 'A'): static
{
$this->startColumnIndex = Coordinate::columnIndexFromString($startColumn);
$this->adjustForExistingOnlyRange();
$this->seek(Coordinate::stringFromColumnIndex($this->startColumnIndex));
return $this;
}
/**
* (Re)Set the end column.
*
* @param ?string $endColumn The column address at which to stop iterating
*
* @return $this
*/
public function resetEnd(?string $endColumn = null): static
{
$endColumn = $endColumn ?: $this->worksheet->getHighestColumn();
$this->endColumnIndex = Coordinate::columnIndexFromString($endColumn);
$this->adjustForExistingOnlyRange();
return $this;
}
/**
* Set the column pointer to the selected column.
*
* @param string $column The column address to set the current pointer at
*
* @return $this
*/
public function seek(string $column = 'A'): static
{
$columnId = Coordinate::columnIndexFromString($column);
if ($this->onlyExistingCells && !($this->cellCollection->has($column . $this->rowIndex))) {
throw new PhpSpreadsheetException('In "IterateOnlyExistingCells" mode and Cell does not exist');
}
if (($columnId < $this->startColumnIndex) || ($columnId > $this->endColumnIndex)) {
throw new PhpSpreadsheetException("Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})");
}
$this->currentColumnIndex = $columnId;
return $this;
}
/**
* Rewind the iterator to the starting column.
*/
public function rewind(): void
{
$this->currentColumnIndex = $this->startColumnIndex;
}
/**
* Return the current cell in this worksheet row.
*/
public function current(): ?Cell
{
$cellAddress = Coordinate::stringFromColumnIndex($this->currentColumnIndex) . $this->rowIndex;
return $this->cellCollection->has($cellAddress)
? $this->cellCollection->get($cellAddress)
: (
$this->ifNotExists === self::IF_NOT_EXISTS_CREATE_NEW
? $this->worksheet->createNewCell($cellAddress)
: null
);
}
/**
* Return the current iterator key.
*/
public function key(): string
{
return Coordinate::stringFromColumnIndex($this->currentColumnIndex);
}
/**
* Set the iterator to its next value.
*/
public function next(): void
{
do {
++$this->currentColumnIndex;
} while (($this->onlyExistingCells) && (!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->currentColumnIndex) . $this->rowIndex)) && ($this->currentColumnIndex <= $this->endColumnIndex));
}
/**
* Set the iterator to its previous value.
*/
public function prev(): void
{
do {
--$this->currentColumnIndex;
} while (($this->onlyExistingCells) && (!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->currentColumnIndex) . $this->rowIndex)) && ($this->currentColumnIndex >= $this->startColumnIndex));
}
/**
* Indicate if more columns exist in the worksheet range of columns that we're iterating.
*/
public function valid(): bool
{
return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex;
}
/**
* Return the current iterator position.
*/
public function getCurrentColumnIndex(): int
{
return $this->currentColumnIndex;
}
/**
* Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary.
*/
protected function adjustForExistingOnlyRange(): void
{
if ($this->onlyExistingCells) {
while ((!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->startColumnIndex) . $this->rowIndex)) && ($this->startColumnIndex <= $this->endColumnIndex)) {
++$this->startColumnIndex;
}
while ((!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->endColumnIndex) . $this->rowIndex)) && ($this->endColumnIndex >= $this->startColumnIndex)) {
--$this->endColumnIndex;
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Drawing.php | src/PhpSpreadsheet/Worksheet/Drawing.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use ZipArchive;
class Drawing extends BaseDrawing
{
const IMAGE_TYPES_CONVERTION_MAP = [
IMAGETYPE_GIF => IMAGETYPE_PNG,
IMAGETYPE_JPEG => IMAGETYPE_JPEG,
IMAGETYPE_PNG => IMAGETYPE_PNG,
IMAGETYPE_BMP => IMAGETYPE_PNG,
];
/**
* Path.
*/
private string $path;
/**
* Whether or not we are dealing with a URL.
*/
private bool $isUrl;
/**
* Create a new Drawing.
*/
public function __construct()
{
// Initialise values
$this->path = '';
$this->isUrl = false;
// Initialize parent
parent::__construct();
}
/**
* Get Filename.
*/
public function getFilename(): string
{
return basename($this->path);
}
/**
* Get indexed filename (using image index).
*/
public function getIndexedFilename(): string
{
return md5($this->path) . '.' . $this->getExtension();
}
/**
* Get Extension.
*/
public function getExtension(): string
{
$exploded = explode('.', basename($this->path));
return $exploded[count($exploded) - 1];
}
/**
* Get full filepath to store drawing in zip archive.
*/
public function getMediaFilename(): string
{
if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
}
return sprintf('image%d%s', $this->getImageIndex(), $this->getImageFileExtensionForSave());
}
/**
* Get Path.
*/
public function getPath(): string
{
return $this->path;
}
/**
* Set Path.
*
* @param string $path File path
* @param bool $verifyFile Verify file
* @param ?ZipArchive $zip Zip archive instance
*
* @return $this
*/
public function setPath(string $path, bool $verifyFile = true, ?ZipArchive $zip = null, bool $allowExternal = true): static
{
$this->isUrl = false;
if (preg_match('~^data:image/[a-z]+;base64,~', $path) === 1) {
$this->path = $path;
return $this;
}
$this->path = '';
// Check if a URL has been passed. https://stackoverflow.com/a/2058596/1252979
if (filter_var($path, FILTER_VALIDATE_URL) || (preg_match('/^([\w\s\x00-\x1f]+):/u', $path) && !preg_match('/^([\w]+):/u', $path))) {
if (!preg_match('/^(http|https|file|ftp|s3):/', $path)) {
throw new PhpSpreadsheetException('Invalid protocol for linked drawing');
}
if (!$allowExternal) {
return $this;
}
// Implicit that it is a URL, rather store info than running check above on value in other places.
$this->isUrl = true;
$ctx = null;
// https://github.com/php/php-src/issues/16023
// https://github.com/php/php-src/issues/17121
if (str_starts_with($path, 'https:') || str_starts_with($path, 'http:')) {
$ctxArray = [
'http' => [
'user_agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'header' => [
//'Connection: keep-alive', // unacceptable performance
'Accept: image/*;q=0.9,*/*;q=0.8',
],
],
];
if (str_starts_with($path, 'https:')) {
$ctxArray['ssl'] = ['crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT];
}
$ctx = stream_context_create($ctxArray);
}
$imageContents = @file_get_contents($path, false, $ctx);
if ($imageContents !== false) {
$filePath = tempnam(sys_get_temp_dir(), 'Drawing');
if ($filePath) {
$put = @file_put_contents($filePath, $imageContents);
if ($put !== false) {
if ($this->isImage($filePath)) {
$this->path = $path;
$this->setSizesAndType($filePath);
}
unlink($filePath);
}
}
}
} elseif ($zip instanceof ZipArchive) {
$zipPath = explode('#', $path)[1];
$locate = @$zip->locateName($zipPath);
if ($locate !== false) {
if ($this->isImage($path)) {
$this->path = $path;
$this->setSizesAndType($path);
}
}
} else {
$exists = @file_exists($path);
if ($exists !== false && $this->isImage($path)) {
$this->path = $path;
$this->setSizesAndType($path);
}
}
if ($this->path === '' && $verifyFile) {
throw new PhpSpreadsheetException("File $path not found!");
}
if ($this->worksheet !== null) {
if ($this->path !== '') {
$this->worksheet->getCell($this->coordinates);
}
}
return $this;
}
private function isImage(string $path): bool
{
$mime = (string) @mime_content_type($path);
$retVal = false;
if (str_starts_with($mime, 'image/')) {
$retVal = true;
} elseif ($mime === 'application/octet-stream') {
$extension = pathinfo($path, PATHINFO_EXTENSION);
$retVal = in_array($extension, ['bin', 'emf'], true);
}
return $retVal;
}
/**
* Get isURL.
*/
public function getIsURL(): bool
{
return $this->isUrl;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
return md5(
$this->path
. parent::getHashCode()
. __CLASS__
);
}
/**
* Get Image Type for Save.
*/
public function getImageTypeForSave(): int
{
if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
}
return self::IMAGE_TYPES_CONVERTION_MAP[$this->type];
}
/**
* Get Image file extension for Save.
*/
public function getImageFileExtensionForSave(bool $includeDot = true): string
{
if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
}
$result = image_type_to_extension(self::IMAGE_TYPES_CONVERTION_MAP[$this->type], $includeDot);
return "$result";
}
/**
* Get Image mime type.
*/
public function getImageMimeType(): string
{
if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
}
return image_type_to_mime_type(self::IMAGE_TYPES_CONVERTION_MAP[$this->type]);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php | src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
/**
* @extends CellIterator<int>
*/
class ColumnCellIterator extends CellIterator
{
/**
* Current iterator position.
*/
private int $currentRow;
/**
* Column index.
*/
private int $columnIndex;
/**
* Start position.
*/
private int $startRow = 1;
/**
* End position.
*/
private int $endRow = 1;
/**
* Create a new row iterator.
*
* @param Worksheet $worksheet The worksheet to iterate over
* @param string $columnIndex The column that we want to iterate
* @param int $startRow The row number at which to start iterating
* @param ?int $endRow Optionally, the row number at which to stop iterating
*/
public function __construct(Worksheet $worksheet, string $columnIndex = 'A', int $startRow = 1, ?int $endRow = null, bool $iterateOnlyExistingCells = false)
{
// Set subject
$this->worksheet = $worksheet;
$this->cellCollection = $worksheet->getCellCollection();
$this->columnIndex = Coordinate::columnIndexFromString($columnIndex);
$this->resetEnd($endRow);
$this->resetStart($startRow);
$this->setIterateOnlyExistingCells($iterateOnlyExistingCells);
}
/**
* (Re)Set the start row and the current row pointer.
*
* @param int $startRow The row number at which to start iterating
*
* @return $this
*/
public function resetStart(int $startRow = 1): static
{
$this->startRow = $startRow;
$this->adjustForExistingOnlyRange();
$this->seek($startRow);
return $this;
}
/**
* (Re)Set the end row.
*
* @param ?int $endRow The row number at which to stop iterating
*
* @return $this
*/
public function resetEnd(?int $endRow = null): static
{
$this->endRow = $endRow ?: $this->worksheet->getHighestRow();
$this->adjustForExistingOnlyRange();
return $this;
}
/**
* Set the row pointer to the selected row.
*
* @param int $row The row number to set the current pointer at
*
* @return $this
*/
public function seek(int $row = 1): static
{
if (
$this->onlyExistingCells
&& (!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->columnIndex) . $row))
) {
throw new PhpSpreadsheetException('In "IterateOnlyExistingCells" mode and Cell does not exist');
}
if (($row < $this->startRow) || ($row > $this->endRow)) {
throw new PhpSpreadsheetException("Row $row is out of range ({$this->startRow} - {$this->endRow})");
}
$this->currentRow = $row;
return $this;
}
/**
* Rewind the iterator to the starting row.
*/
public function rewind(): void
{
$this->currentRow = $this->startRow;
}
/**
* Return the current cell in this worksheet column.
*/
public function current(): ?Cell
{
$cellAddress = Coordinate::stringFromColumnIndex($this->columnIndex) . $this->currentRow;
return $this->cellCollection->has($cellAddress)
? $this->cellCollection->get($cellAddress)
: (
$this->ifNotExists === self::IF_NOT_EXISTS_CREATE_NEW
? $this->worksheet->createNewCell($cellAddress)
: null
);
}
/**
* Return the current iterator key.
*/
public function key(): int
{
return $this->currentRow;
}
/**
* Set the iterator to its next value.
*/
public function next(): void
{
$columnAddress = Coordinate::stringFromColumnIndex($this->columnIndex);
do {
++$this->currentRow;
} while (
($this->onlyExistingCells)
&& ($this->currentRow <= $this->endRow)
&& (!$this->cellCollection->has($columnAddress . $this->currentRow))
);
}
/**
* Set the iterator to its previous value.
*/
public function prev(): void
{
$columnAddress = Coordinate::stringFromColumnIndex($this->columnIndex);
do {
--$this->currentRow;
} while (
($this->onlyExistingCells)
&& ($this->currentRow >= $this->startRow)
&& (!$this->cellCollection->has($columnAddress . $this->currentRow))
);
}
/**
* Indicate if more rows exist in the worksheet range of rows that we're iterating.
*/
public function valid(): bool
{
return $this->currentRow <= $this->endRow && $this->currentRow >= $this->startRow;
}
/**
* Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary.
*/
protected function adjustForExistingOnlyRange(): void
{
if ($this->onlyExistingCells) {
$columnAddress = Coordinate::stringFromColumnIndex($this->columnIndex);
while (
(!$this->cellCollection->has($columnAddress . $this->startRow))
&& ($this->startRow <= $this->endRow)
) {
++$this->startRow;
}
while (
(!$this->cellCollection->has($columnAddress . $this->endRow))
&& ($this->endRow >= $this->startRow)
) {
--$this->endRow;
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/ProtectedRange.php | src/PhpSpreadsheet/Worksheet/ProtectedRange.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
class ProtectedRange
{
private string $name = '';
private string $password = '';
private string $sqref;
private string $securityDescriptor = '';
/**
* No setters aside from constructor.
*/
public function __construct(string $sqref, string $password = '', string $name = '', string $securityDescriptor = '')
{
$this->sqref = $sqref;
$this->name = $name;
$this->password = $password;
$this->securityDescriptor = $securityDescriptor;
}
public function getSqref(): string
{
return $this->sqref;
}
public function getName(): string
{
return $this->name ?: ('p' . md5($this->sqref));
}
public function getPassword(): string
{
return $this->password;
}
public function getSecurityDescriptor(): string
{
return $this->securityDescriptor;
}
/**
* Split range into coordinate strings.
*
* @return array<array<string>> Array containing one or more arrays containing one or two coordinate strings
* e.g. ['B4','D9'] or [['B4','D9'], ['H2','O11']]
* or ['B4']
*/
public function allRanges(): array
{
return Coordinate::allRanges($this->sqref, false);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Dimension.php | src/PhpSpreadsheet/Worksheet/Dimension.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
abstract class Dimension
{
/**
* Visible?
*/
private bool $visible = true;
/**
* Outline level.
*/
private int $outlineLevel = 0;
/**
* Collapsed.
*/
private bool $collapsed = false;
/**
* Index to cellXf. Null value means row has no explicit cellXf format.
*/
private ?int $xfIndex;
/**
* Create a new Dimension.
*
* @param ?int $initialValue Numeric row index
*/
public function __construct(?int $initialValue = null)
{
// set dimension as unformatted by default
$this->xfIndex = $initialValue;
}
/**
* Get Visible.
*/
public function getVisible(): bool
{
return $this->visible;
}
/**
* Set Visible.
*
* @return $this
*/
public function setVisible(bool $visible)
{
$this->visible = $visible;
return $this;
}
/**
* Get Outline Level.
*/
public function getOutlineLevel(): int
{
return $this->outlineLevel;
}
/**
* Set Outline Level.
* Value must be between 0 and 7.
*
* @return $this
*/
public function setOutlineLevel(int $level)
{
if ($level < 0 || $level > 7) {
throw new PhpSpreadsheetException('Outline level must range between 0 and 7.');
}
$this->outlineLevel = $level;
return $this;
}
/**
* Get Collapsed.
*/
public function getCollapsed(): bool
{
return $this->collapsed;
}
/**
* Set Collapsed.
*
* @return $this
*/
public function setCollapsed(bool $collapsed)
{
$this->collapsed = $collapsed;
return $this;
}
/**
* Get index to cellXf.
*/
public function getXfIndex(): ?int
{
return $this->xfIndex;
}
/**
* Set index to cellXf.
*
* @return $this
*/
public function setXfIndex(int $XfIndex)
{
$this->xfIndex = $XfIndex;
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/PageSetup.php | src/PhpSpreadsheet/Worksheet/PageSetup.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
/**
* <code>
* Paper size taken from Office Open XML Part 4 - Markup Language Reference, page 1988:.
*
* 1 = Letter paper (8.5 in. by 11 in.)
* 2 = Letter small paper (8.5 in. by 11 in.)
* 3 = Tabloid paper (11 in. by 17 in.)
* 4 = Ledger paper (17 in. by 11 in.)
* 5 = Legal paper (8.5 in. by 14 in.)
* 6 = Statement paper (5.5 in. by 8.5 in.)
* 7 = Executive paper (7.25 in. by 10.5 in.)
* 8 = A3 paper (297 mm by 420 mm)
* 9 = A4 paper (210 mm by 297 mm)
* 10 = A4 small paper (210 mm by 297 mm)
* 11 = A5 paper (148 mm by 210 mm)
* 12 = B4 paper (250 mm by 353 mm)
* 13 = B5 paper (176 mm by 250 mm)
* 14 = Folio paper (8.5 in. by 13 in.)
* 15 = Quarto paper (215 mm by 275 mm)
* 16 = Standard paper (10 in. by 14 in.)
* 17 = Standard paper (11 in. by 17 in.)
* 18 = Note paper (8.5 in. by 11 in.)
* 19 = #9 envelope (3.875 in. by 8.875 in.)
* 20 = #10 envelope (4.125 in. by 9.5 in.)
* 21 = #11 envelope (4.5 in. by 10.375 in.)
* 22 = #12 envelope (4.75 in. by 11 in.)
* 23 = #14 envelope (5 in. by 11.5 in.)
* 24 = C paper (17 in. by 22 in.)
* 25 = D paper (22 in. by 34 in.)
* 26 = E paper (34 in. by 44 in.)
* 27 = DL envelope (110 mm by 220 mm)
* 28 = C5 envelope (162 mm by 229 mm)
* 29 = C3 envelope (324 mm by 458 mm)
* 30 = C4 envelope (229 mm by 324 mm)
* 31 = C6 envelope (114 mm by 162 mm)
* 32 = C65 envelope (114 mm by 229 mm)
* 33 = B4 envelope (250 mm by 353 mm)
* 34 = B5 envelope (176 mm by 250 mm)
* 35 = B6 envelope (176 mm by 125 mm)
* 36 = Italy envelope (110 mm by 230 mm)
* 37 = Monarch envelope (3.875 in. by 7.5 in.).
* 38 = 6 3/4 envelope (3.625 in. by 6.5 in.)
* 39 = US standard fanfold (14.875 in. by 11 in.)
* 40 = German standard fanfold (8.5 in. by 12 in.)
* 41 = German legal fanfold (8.5 in. by 13 in.)
* 42 = ISO B4 (250 mm by 353 mm)
* 43 = Japanese double postcard (200 mm by 148 mm)
* 44 = Standard paper (9 in. by 11 in.)
* 45 = Standard paper (10 in. by 11 in.)
* 46 = Standard paper (15 in. by 11 in.)
* 47 = Invite envelope (220 mm by 220 mm)
* 50 = Letter extra paper (9.275 in. by 12 in.)
* 51 = Legal extra paper (9.275 in. by 15 in.)
* 52 = Tabloid extra paper (11.69 in. by 18 in.)
* 53 = A4 extra paper (236 mm by 322 mm)
* 54 = Letter transverse paper (8.275 in. by 11 in.)
* 55 = A4 transverse paper (210 mm by 297 mm)
* 56 = Letter extra transverse paper (9.275 in. by 12 in.)
* 57 = SuperA/SuperA/A4 paper (227 mm by 356 mm)
* 58 = SuperB/SuperB/A3 paper (305 mm by 487 mm)
* 59 = Letter plus paper (8.5 in. by 12.69 in.)
* 60 = A4 plus paper (210 mm by 330 mm)
* 61 = A5 transverse paper (148 mm by 210 mm)
* 62 = JIS B5 transverse paper (182 mm by 257 mm)
* 63 = A3 extra paper (322 mm by 445 mm)
* 64 = A5 extra paper (174 mm by 235 mm)
* 65 = ISO B5 extra paper (201 mm by 276 mm)
* 66 = A2 paper (420 mm by 594 mm)
* 67 = A3 transverse paper (297 mm by 420 mm)
* 68 = A3 extra transverse paper (322 mm by 445 mm)
* </code>
*/
class PageSetup
{
// Paper size
const PAPERSIZE_LETTER = 1;
const PAPERSIZE_LETTER_SMALL = 2;
const PAPERSIZE_TABLOID = 3;
const PAPERSIZE_LEDGER = 4;
const PAPERSIZE_LEGAL = 5;
const PAPERSIZE_STATEMENT = 6;
const PAPERSIZE_EXECUTIVE = 7;
const PAPERSIZE_A3 = 8;
const PAPERSIZE_A4 = 9;
const PAPERSIZE_A4_SMALL = 10;
const PAPERSIZE_A5 = 11;
const PAPERSIZE_B4 = 12;
const PAPERSIZE_B5 = 13;
const PAPERSIZE_FOLIO = 14;
const PAPERSIZE_QUARTO = 15;
const PAPERSIZE_STANDARD_1 = 16;
const PAPERSIZE_STANDARD_2 = 17;
const PAPERSIZE_NOTE = 18;
const PAPERSIZE_NO9_ENVELOPE = 19;
const PAPERSIZE_NO10_ENVELOPE = 20;
const PAPERSIZE_NO11_ENVELOPE = 21;
const PAPERSIZE_NO12_ENVELOPE = 22;
const PAPERSIZE_NO14_ENVELOPE = 23;
const PAPERSIZE_C = 24;
const PAPERSIZE_D = 25;
const PAPERSIZE_E = 26;
const PAPERSIZE_DL_ENVELOPE = 27;
const PAPERSIZE_C5_ENVELOPE = 28;
const PAPERSIZE_C3_ENVELOPE = 29;
const PAPERSIZE_C4_ENVELOPE = 30;
const PAPERSIZE_C6_ENVELOPE = 31;
const PAPERSIZE_C65_ENVELOPE = 32;
const PAPERSIZE_B4_ENVELOPE = 33;
const PAPERSIZE_B5_ENVELOPE = 34;
const PAPERSIZE_B6_ENVELOPE = 35;
const PAPERSIZE_ITALY_ENVELOPE = 36;
const PAPERSIZE_MONARCH_ENVELOPE = 37;
const PAPERSIZE_6_3_4_ENVELOPE = 38;
const PAPERSIZE_US_STANDARD_FANFOLD = 39;
const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40;
const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41;
const PAPERSIZE_ISO_B4 = 42;
const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43;
const PAPERSIZE_STANDARD_PAPER_1 = 44;
const PAPERSIZE_STANDARD_PAPER_2 = 45;
const PAPERSIZE_STANDARD_PAPER_3 = 46;
const PAPERSIZE_INVITE_ENVELOPE = 47;
const PAPERSIZE_LETTER_EXTRA_PAPER = 48;
const PAPERSIZE_LEGAL_EXTRA_PAPER = 49;
const PAPERSIZE_TABLOID_EXTRA_PAPER = 50;
const PAPERSIZE_A4_EXTRA_PAPER = 51;
const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52;
const PAPERSIZE_A4_TRANSVERSE_PAPER = 53;
const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54;
const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55;
const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56;
const PAPERSIZE_LETTER_PLUS_PAPER = 57;
const PAPERSIZE_A4_PLUS_PAPER = 58;
const PAPERSIZE_A5_TRANSVERSE_PAPER = 59;
const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60;
const PAPERSIZE_A3_EXTRA_PAPER = 61;
const PAPERSIZE_A5_EXTRA_PAPER = 62;
const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63;
const PAPERSIZE_A2_PAPER = 64;
const PAPERSIZE_A3_TRANSVERSE_PAPER = 65;
const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66;
// Page orientation
const ORIENTATION_DEFAULT = 'default';
const ORIENTATION_LANDSCAPE = 'landscape';
const ORIENTATION_PORTRAIT = 'portrait';
// Print Range Set Method
const SETPRINTRANGE_OVERWRITE = 'O';
const SETPRINTRANGE_INSERT = 'I';
const PAGEORDER_OVER_THEN_DOWN = 'overThenDown';
const PAGEORDER_DOWN_THEN_OVER = 'downThenOver';
/**
* Paper size default.
*/
private static int $paperSizeDefault = self::PAPERSIZE_LETTER;
/**
* Paper size.
*/
private ?int $paperSize = null;
/**
* Orientation default.
*/
private static string $orientationDefault = self::ORIENTATION_DEFAULT;
/**
* Orientation.
*/
private string $orientation;
/**
* Scale (Print Scale).
*
* Print scaling. Valid values range from 10 to 400
* This setting is overridden when fitToWidth and/or fitToHeight are in use
*/
private ?int $scale = 100;
/**
* Fit To Page
* Whether scale or fitToWith / fitToHeight applies.
*/
private bool $fitToPage = false;
/**
* Fit To Height
* Number of vertical pages to fit on.
*/
private ?int $fitToHeight = 1;
/**
* Fit To Width
* Number of horizontal pages to fit on.
*/
private ?int $fitToWidth = 1;
/**
* Columns to repeat at left.
*
* @var array{string, string} Containing start column and end column, empty array if option unset
*/
private array $columnsToRepeatAtLeft = ['', ''];
/**
* Rows to repeat at top.
*
* @var int[] Containing start row number and end row number, empty array if option unset
*/
private array $rowsToRepeatAtTop = [0, 0];
/**
* Center page horizontally.
*/
private bool $horizontalCentered = false;
/**
* Center page vertically.
*/
private bool $verticalCentered = false;
/**
* Print area.
*/
private ?string $printArea = null;
/**
* First page number.
*/
private ?int $firstPageNumber = null;
private string $pageOrder = self::PAGEORDER_DOWN_THEN_OVER;
/**
* Create a new PageSetup.
*/
public function __construct()
{
$this->orientation = self::$orientationDefault;
}
/**
* Get Paper Size.
*/
public function getPaperSize(): int
{
return $this->paperSize ?? self::$paperSizeDefault;
}
/**
* Set Paper Size.
*
* @param int $paperSize see self::PAPERSIZE_*
*
* @return $this
*/
public function setPaperSize(int $paperSize): static
{
$this->paperSize = $paperSize;
return $this;
}
/**
* Get Paper Size default.
*/
public static function getPaperSizeDefault(): int
{
return self::$paperSizeDefault;
}
/**
* Set Paper Size Default.
*/
public static function setPaperSizeDefault(int $paperSize): void
{
self::$paperSizeDefault = $paperSize;
}
/**
* Get Orientation.
*/
public function getOrientation(): string
{
return $this->orientation;
}
/**
* Set Orientation.
*
* @param string $orientation see self::ORIENTATION_*
*
* @return $this
*/
public function setOrientation(string $orientation): static
{
if ($orientation === self::ORIENTATION_LANDSCAPE || $orientation === self::ORIENTATION_PORTRAIT || $orientation === self::ORIENTATION_DEFAULT) {
$this->orientation = $orientation;
}
return $this;
}
public static function getOrientationDefault(): string
{
return self::$orientationDefault;
}
public static function setOrientationDefault(string $orientation): void
{
if ($orientation === self::ORIENTATION_LANDSCAPE || $orientation === self::ORIENTATION_PORTRAIT || $orientation === self::ORIENTATION_DEFAULT) {
self::$orientationDefault = $orientation;
}
}
/**
* Get Scale.
*/
public function getScale(): ?int
{
return $this->scale;
}
/**
* Set Scale.
* Print scaling. Valid values range from 10 to 400
* This setting is overridden when fitToWidth and/or fitToHeight are in use.
*
* @param bool $update Update fitToPage so scaling applies rather than fitToHeight / fitToWidth
*
* @return $this
*/
public function setScale(?int $scale, bool $update = true): static
{
// Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface,
// but it is apparently still able to handle any scale >= 0, where 0 results in 100
if ($scale === null || $scale >= 0) {
$this->scale = $scale;
if ($update) {
$this->fitToPage = false;
}
} else {
throw new PhpSpreadsheetException('Scale must not be negative');
}
return $this;
}
/**
* Get Fit To Page.
*/
public function getFitToPage(): bool
{
return $this->fitToPage;
}
/**
* Set Fit To Page.
*
* @return $this
*/
public function setFitToPage(bool $fitToPage): static
{
$this->fitToPage = $fitToPage;
return $this;
}
/**
* Get Fit To Height.
*/
public function getFitToHeight(): ?int
{
return $this->fitToHeight;
}
/**
* Set Fit To Height.
*
* @param bool $update Update fitToPage so it applies rather than scaling
*
* @return $this
*/
public function setFitToHeight(?int $fitToHeight, bool $update = true): static
{
$this->fitToHeight = $fitToHeight;
if ($update) {
$this->fitToPage = true;
}
return $this;
}
/**
* Get Fit To Width.
*/
public function getFitToWidth(): ?int
{
return $this->fitToWidth;
}
/**
* Set Fit To Width.
*
* @param bool $update Update fitToPage so it applies rather than scaling
*
* @return $this
*/
public function setFitToWidth(?int $value, bool $update = true): static
{
$this->fitToWidth = $value;
if ($update) {
$this->fitToPage = true;
}
return $this;
}
/**
* Is Columns to repeat at left set?
*/
public function isColumnsToRepeatAtLeftSet(): bool
{
if (!empty($this->columnsToRepeatAtLeft)) {
if ($this->columnsToRepeatAtLeft[0] != '' && $this->columnsToRepeatAtLeft[1] != '') {
return true;
}
}
return false;
}
/**
* Get Columns to repeat at left.
*
* @return array{string, string} Containing start column and end column, empty array if option unset
*/
public function getColumnsToRepeatAtLeft(): array
{
return $this->columnsToRepeatAtLeft;
}
/**
* Set Columns to repeat at left.
*
* @param array{string, string} $columnsToRepeatAtLeft Containing start column and end column, empty array if option unset
*
* @return $this
*/
public function setColumnsToRepeatAtLeft(array $columnsToRepeatAtLeft): static
{
$this->columnsToRepeatAtLeft = $columnsToRepeatAtLeft;
return $this;
}
/**
* Set Columns to repeat at left by start and end.
*
* @param string $start eg: 'A'
* @param string $end eg: 'B'
*
* @return $this
*/
public function setColumnsToRepeatAtLeftByStartAndEnd(string $start, string $end): static
{
$this->columnsToRepeatAtLeft = [$start, $end];
return $this;
}
/**
* Is Rows to repeat at top set?
*/
public function isRowsToRepeatAtTopSet(): bool
{
if (!empty($this->rowsToRepeatAtTop)) {
if ($this->rowsToRepeatAtTop[0] != 0 && $this->rowsToRepeatAtTop[1] != 0) {
return true;
}
}
return false;
}
/**
* Get Rows to repeat at top.
*
* @return int[] Containing start column and end column, empty array if option unset
*/
public function getRowsToRepeatAtTop(): array
{
return $this->rowsToRepeatAtTop;
}
/**
* Set Rows to repeat at top.
*
* @param int[] $rowsToRepeatAtTop Containing start column and end column, empty array if option unset
*
* @return $this
*/
public function setRowsToRepeatAtTop(array $rowsToRepeatAtTop): static
{
$this->rowsToRepeatAtTop = $rowsToRepeatAtTop;
return $this;
}
/**
* Set Rows to repeat at top by start and end.
*
* @param int $start eg: 1
* @param int $end eg: 1
*
* @return $this
*/
public function setRowsToRepeatAtTopByStartAndEnd(int $start, int $end): static
{
$this->rowsToRepeatAtTop = [$start, $end];
return $this;
}
/**
* Get center page horizontally.
*/
public function getHorizontalCentered(): bool
{
return $this->horizontalCentered;
}
/**
* Set center page horizontally.
*
* @return $this
*/
public function setHorizontalCentered(bool $value): static
{
$this->horizontalCentered = $value;
return $this;
}
/**
* Get center page vertically.
*/
public function getVerticalCentered(): bool
{
return $this->verticalCentered;
}
/**
* Set center page vertically.
*
* @return $this
*/
public function setVerticalCentered(bool $value): static
{
$this->verticalCentered = $value;
return $this;
}
/**
* Get print area.
*
* @param int $index Identifier for a specific print area range if several ranges have been set
* Default behaviour, or an index value of 0, will return all ranges as a comma-separated string
* Otherwise, the specific range identified by the value of $index will be returned
* Print areas are numbered from 1
*/
public function getPrintArea(int $index = 0): string
{
if ($index == 0) {
return (string) $this->printArea;
}
$printAreas = explode(',', (string) $this->printArea);
if (isset($printAreas[$index - 1])) {
return $printAreas[$index - 1];
}
throw new PhpSpreadsheetException('Requested Print Area does not exist');
}
/**
* Is print area set?
*
* @param int $index Identifier for a specific print area range if several ranges have been set
* Default behaviour, or an index value of 0, will identify whether any print range is set
* Otherwise, existence of the range identified by the value of $index will be returned
* Print areas are numbered from 1
*/
public function isPrintAreaSet(int $index = 0): bool
{
if ($index == 0) {
return $this->printArea !== null;
}
$printAreas = explode(',', (string) $this->printArea);
return isset($printAreas[$index - 1]);
}
/**
* Clear a print area.
*
* @param int $index Identifier for a specific print area range if several ranges have been set
* Default behaviour, or an index value of 0, will clear all print ranges that are set
* Otherwise, the range identified by the value of $index will be removed from the series
* Print areas are numbered from 1
*
* @return $this
*/
public function clearPrintArea(int $index = 0): static
{
if ($index == 0) {
$this->printArea = null;
} else {
$printAreas = explode(',', (string) $this->printArea);
if (isset($printAreas[$index - 1])) {
unset($printAreas[$index - 1]);
$this->printArea = implode(',', $printAreas);
}
}
return $this;
}
/**
* Set print area. e.g. 'A1:D10' or 'A1:D10,G5:M20'.
*
* @param int $index Identifier for a specific print area range allowing several ranges to be set
* When the method is "O"verwrite, then a positive integer index will overwrite that indexed
* entry in the print areas list; a negative index value will identify which entry to
* overwrite working backward through the print area to the list, with the last entry as -1.
* Specifying an index value of 0, will overwrite <b>all</b> existing print ranges.
* When the method is "I"nsert, then a positive index will insert after that indexed entry in
* the print areas list, while a negative index will insert before the indexed entry.
* Specifying an index value of 0, will always append the new print range at the end of the
* list.
* Print areas are numbered from 1
* @param string $method Determines the method used when setting multiple print areas
* Default behaviour, or the "O" method, overwrites existing print area
* The "I" method, inserts the new print area before any specified index, or at the end of the list
*
* @return $this
*/
public function setPrintArea(string $value, int $index = 0, string $method = self::SETPRINTRANGE_OVERWRITE): static
{
if (str_contains($value, '!')) {
throw new PhpSpreadsheetException('Cell coordinate must not specify a worksheet.');
} elseif (!str_contains($value, ':')) {
throw new PhpSpreadsheetException('Cell coordinate must be a range of cells.');
} elseif (str_contains($value, '$')) {
throw new PhpSpreadsheetException('Cell coordinate must not be absolute.');
}
$value = strtoupper($value);
if (!$this->printArea) {
$index = 0;
}
if ($method == self::SETPRINTRANGE_OVERWRITE) {
if ($index == 0) {
$this->printArea = $value;
} else {
$printAreas = explode(',', (string) $this->printArea);
if ($index < 0) {
$index = count($printAreas) - abs($index) + 1;
}
if (($index <= 0) || ($index > count($printAreas))) {
throw new PhpSpreadsheetException('Invalid index for setting print range.');
}
$printAreas[$index - 1] = $value;
$this->printArea = implode(',', $printAreas);
}
} elseif ($method == self::SETPRINTRANGE_INSERT) {
if ($index == 0) {
$this->printArea = $this->printArea ? ($this->printArea . ',' . $value) : $value;
} else {
$printAreas = explode(',', (string) $this->printArea);
if ($index < 0) {
$index = (int) abs($index) - 1;
}
if ($index > count($printAreas)) {
throw new PhpSpreadsheetException('Invalid index for setting print range.');
}
$printAreas = array_merge(array_slice($printAreas, 0, $index), [$value], array_slice($printAreas, $index));
$this->printArea = implode(',', $printAreas);
}
} else {
throw new PhpSpreadsheetException('Invalid method for setting print range.');
}
return $this;
}
/**
* Add a new print area (e.g. 'A1:D10' or 'A1:D10,G5:M20') to the list of print areas.
*
* @param int $index Identifier for a specific print area range allowing several ranges to be set
* A positive index will insert after that indexed entry in the print areas list, while a
* negative index will insert before the indexed entry.
* Specifying an index value of 0, will always append the new print range at the end of the
* list.
* Print areas are numbered from 1
*
* @return $this
*/
public function addPrintArea(string $value, int $index = -1): static
{
return $this->setPrintArea($value, $index, self::SETPRINTRANGE_INSERT);
}
/**
* Set print area.
*
* @param int $column1 Column 1
* @param int $row1 Row 1
* @param int $column2 Column 2
* @param int $row2 Row 2
* @param int $index Identifier for a specific print area range allowing several ranges to be set
* When the method is "O"verwrite, then a positive integer index will overwrite that indexed
* entry in the print areas list; a negative index value will identify which entry to
* overwrite working backward through the print area to the list, with the last entry as -1.
* Specifying an index value of 0, will overwrite <b>all</b> existing print ranges.
* When the method is "I"nsert, then a positive index will insert after that indexed entry in
* the print areas list, while a negative index will insert before the indexed entry.
* Specifying an index value of 0, will always append the new print range at the end of the
* list.
* Print areas are numbered from 1
* @param string $method Determines the method used when setting multiple print areas
* Default behaviour, or the "O" method, overwrites existing print area
* The "I" method, inserts the new print area before any specified index, or at the end of the list
*
* @return $this
*/
public function setPrintAreaByColumnAndRow(int $column1, int $row1, int $column2, int $row2, int $index = 0, string $method = self::SETPRINTRANGE_OVERWRITE): static
{
return $this->setPrintArea(
Coordinate::stringFromColumnIndex($column1) . $row1 . ':' . Coordinate::stringFromColumnIndex($column2) . $row2,
$index,
$method
);
}
/**
* Add a new print area to the list of print areas.
*
* @param int $column1 Start Column for the print area
* @param int $row1 Start Row for the print area
* @param int $column2 End Column for the print area
* @param int $row2 End Row for the print area
* @param int $index Identifier for a specific print area range allowing several ranges to be set
* A positive index will insert after that indexed entry in the print areas list, while a
* negative index will insert before the indexed entry.
* Specifying an index value of 0, will always append the new print range at the end of the
* list.
* Print areas are numbered from 1
*
* @return $this
*/
public function addPrintAreaByColumnAndRow(int $column1, int $row1, int $column2, int $row2, int $index = -1): static
{
return $this->setPrintArea(
Coordinate::stringFromColumnIndex($column1) . $row1 . ':' . Coordinate::stringFromColumnIndex($column2) . $row2,
$index,
self::SETPRINTRANGE_INSERT
);
}
/**
* Get first page number.
*/
public function getFirstPageNumber(): ?int
{
return $this->firstPageNumber;
}
/**
* Set first page number.
*
* @return $this
*/
public function setFirstPageNumber(?int $value): static
{
$this->firstPageNumber = $value;
return $this;
}
/**
* Reset first page number.
*
* @return $this
*/
public function resetFirstPageNumber(): static
{
return $this->setFirstPageNumber(null);
}
public function getPageOrder(): string
{
return $this->pageOrder;
}
public function setPageOrder(?string $pageOrder): self
{
if ($pageOrder === null || $pageOrder === self::PAGEORDER_DOWN_THEN_OVER || $pageOrder === self::PAGEORDER_OVER_THEN_DOWN) {
$this->pageOrder = $pageOrder ?? self::PAGEORDER_DOWN_THEN_OVER;
}
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Table.php | src/PhpSpreadsheet/Worksheet/Table.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Table\TableStyle;
use Stringable;
class Table implements Stringable
{
/**
* Table Name.
*/
private string $name;
/**
* Show Header Row.
*/
private bool $showHeaderRow = true;
/**
* Show Totals Row.
*/
private bool $showTotalsRow = false;
/**
* Table Range.
*/
private string $range = '';
/**
* Table Worksheet.
*/
private ?Worksheet $workSheet = null;
/**
* Table allow filter.
*/
private bool $allowFilter = true;
/**
* Table Column.
*
* @var Table\Column[]
*/
private array $columns = [];
/**
* Table Style.
*/
private TableStyle $style;
/**
* Table AutoFilter.
*/
private AutoFilter $autoFilter;
/**
* Create a new Table.
*
* @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range
* A simple string containing a Cell range like 'A1:E10' is permitted
* or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
* or an AddressRange object.
* @param string $name (e.g. Table1)
*/
public function __construct(AddressRange|string|array $range = '', string $name = '')
{
$this->style = new TableStyle();
$this->autoFilter = new AutoFilter($range);
$this->setRange($range);
$this->setName($name);
}
/**
* Code to execute when this table is unset().
*/
public function __destruct()
{
$this->workSheet = null;
}
/**
* Get Table name.
*/
public function getName(): string
{
return $this->name;
}
/**
* Set Table name.
*
* @throws PhpSpreadsheetException
*/
public function setName(string $name): self
{
$name = trim($name);
if (!empty($name)) {
if (strlen($name) === 1 && in_array($name, ['C', 'c', 'R', 'r'])) {
throw new PhpSpreadsheetException('The table name is invalid');
}
if (StringHelper::countCharacters($name) > 255) {
throw new PhpSpreadsheetException('The table name cannot be longer than 255 characters');
}
// Check for A1 or R1C1 cell reference notation
if (
preg_match(Coordinate::A1_COORDINATE_REGEX, $name)
|| preg_match('/^R\[?\-?[0-9]*\]?C\[?\-?[0-9]*\]?$/i', $name)
) {
throw new PhpSpreadsheetException('The table name can\'t be the same as a cell reference');
}
if (!preg_match('/^[\p{L}_\\\]/iu', $name)) {
throw new PhpSpreadsheetException('The table name must begin a name with a letter, an underscore character (_), or a backslash (\)');
}
if (!preg_match('/^[\p{L}_\\\][\p{L}\p{M}0-9\._]*$/iu', $name)) {
throw new PhpSpreadsheetException('The table name contains invalid characters');
}
$this->checkForDuplicateTableNames($name, $this->workSheet);
$this->updateStructuredReferences($name);
}
$this->name = $name;
return $this;
}
/**
* @throws PhpSpreadsheetException
*/
private function checkForDuplicateTableNames(string $name, ?Worksheet $worksheet): void
{
// Remember that table names are case-insensitive
$tableName = StringHelper::strToLower($name);
if ($worksheet !== null && StringHelper::strToLower($this->name) !== $name) {
$spreadsheet = $worksheet->getParentOrThrow();
foreach ($spreadsheet->getWorksheetIterator() as $sheet) {
foreach ($sheet->getTableCollection() as $table) {
if (StringHelper::strToLower($table->getName()) === $tableName && $table != $this) {
throw new PhpSpreadsheetException("Spreadsheet already contains a table named '{$this->name}'");
}
}
}
}
}
private function updateStructuredReferences(string $name): void
{
if (!$this->workSheet || !$this->name) {
return;
}
// Remember that table names are case-insensitive
if (StringHelper::strToLower($this->name) !== StringHelper::strToLower($name)) {
// We need to check all formula cells that might contain fully-qualified Structured References
// that refer to this table, and update those formulae to reference the new table name
$spreadsheet = $this->workSheet->getParentOrThrow();
foreach ($spreadsheet->getWorksheetIterator() as $sheet) {
$this->updateStructuredReferencesInCells($sheet, $name);
}
$this->updateStructuredReferencesInNamedFormulae($spreadsheet, $name);
}
}
private function updateStructuredReferencesInCells(Worksheet $worksheet, string $newName): void
{
$pattern = '/' . preg_quote($this->name, '/') . '\[/mui';
foreach ($worksheet->getCoordinates(false) as $coordinate) {
$cell = $worksheet->getCell($coordinate);
if ($cell->getDataType() === DataType::TYPE_FORMULA) {
$formula = $cell->getValueString();
if (preg_match($pattern, $formula) === 1) {
$formula = preg_replace($pattern, "{$newName}[", $formula);
$cell->setValueExplicit($formula, DataType::TYPE_FORMULA);
}
}
}
}
private function updateStructuredReferencesInNamedFormulae(Spreadsheet $spreadsheet, string $newName): void
{
$pattern = '/' . preg_quote($this->name, '/') . '\[/mui';
foreach ($spreadsheet->getNamedFormulae() as $namedFormula) {
$formula = $namedFormula->getValue();
if (preg_match($pattern, $formula) === 1) {
$formula = preg_replace($pattern, "{$newName}[", $formula) ?? '';
$namedFormula->setValue($formula);
}
}
}
/**
* Get show Header Row.
*/
public function getShowHeaderRow(): bool
{
return $this->showHeaderRow;
}
/**
* Set show Header Row.
*/
public function setShowHeaderRow(bool $showHeaderRow): self
{
$this->showHeaderRow = $showHeaderRow;
return $this;
}
/**
* Get show Totals Row.
*/
public function getShowTotalsRow(): bool
{
return $this->showTotalsRow;
}
/**
* Set show Totals Row.
*/
public function setShowTotalsRow(bool $showTotalsRow): self
{
$this->showTotalsRow = $showTotalsRow;
return $this;
}
/**
* Get allow filter.
* If false, autofiltering is disabled for the table, if true it is enabled.
*/
public function getAllowFilter(): bool
{
return $this->allowFilter;
}
/**
* Set show Autofiltering.
* Disabling autofiltering has the same effect as hiding the filter button on all the columns in the table.
*/
public function setAllowFilter(bool $allowFilter): self
{
$this->allowFilter = $allowFilter;
return $this;
}
/**
* Get Table Range.
*/
public function getRange(): string
{
return $this->range;
}
/**
* Set Table Cell Range.
*
* @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range
* A simple string containing a Cell range like 'A1:E10' is permitted
* or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
* or an AddressRange object.
*/
public function setRange(AddressRange|string|array $range = ''): self
{
// extract coordinate
if ($range !== '') {
[, $range] = Worksheet::extractSheetTitle(Validations::validateCellRange($range), true);
}
if (empty($range)) {
// Discard all column rules
$this->columns = [];
$this->range = '';
return $this;
}
if (!str_contains($range, ':')) {
throw new PhpSpreadsheetException('Table must be set on a range of cells.');
}
[$width, $height] = Coordinate::rangeDimension($range);
if ($width < 1 || $height < 1) {
throw new PhpSpreadsheetException('The table range must be at least 1 column and row');
}
$this->range = $range;
$this->autoFilter->setRange($range);
// Discard any column rules that are no longer valid within this range
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range);
foreach ($this->columns as $key => $value) {
$colIndex = Coordinate::columnIndexFromString($key);
if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) {
unset($this->columns[$key]);
}
}
return $this;
}
/**
* Set Table Cell Range to max row.
*/
public function setRangeToMaxRow(): self
{
if ($this->workSheet !== null) {
$thisrange = $this->range;
$range = (string) preg_replace('/\d+$/', (string) $this->workSheet->getHighestRow(), $thisrange);
if ($range !== $thisrange) {
$this->setRange($range);
}
}
return $this;
}
/**
* Get Table's Worksheet.
*/
public function getWorksheet(): ?Worksheet
{
return $this->workSheet;
}
/**
* Set Table's Worksheet.
*/
public function setWorksheet(?Worksheet $worksheet = null): self
{
if ($this->name !== '' && $worksheet !== null) {
$spreadsheet = $worksheet->getParentOrThrow();
$tableName = StringHelper::strToUpper($this->name);
foreach ($spreadsheet->getWorksheetIterator() as $sheet) {
foreach ($sheet->getTableCollection() as $table) {
if (StringHelper::strToUpper($table->getName()) === $tableName) {
throw new PhpSpreadsheetException("Workbook already contains a table named '{$this->name}'");
}
}
}
}
$this->workSheet = $worksheet;
$this->autoFilter->setParent($worksheet);
return $this;
}
/**
* Get all Table Columns.
*
* @return Table\Column[]
*/
public function getColumns(): array
{
return $this->columns;
}
/**
* Validate that the specified column is in the Table range.
*
* @param string $column Column name (e.g. A)
*
* @return int The column offset within the table range
*/
public function isColumnInRange(string $column): int
{
if (empty($this->range)) {
throw new PhpSpreadsheetException('No table range is defined.');
}
$columnIndex = Coordinate::columnIndexFromString($column);
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range);
if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) {
throw new PhpSpreadsheetException('Column is outside of current table range.');
}
return $columnIndex - $rangeStart[0];
}
/**
* Get a specified Table Column Offset within the defined Table range.
*
* @param string $column Column name (e.g. A)
*
* @return int The offset of the specified column within the table range
*/
public function getColumnOffset(string $column): int
{
return $this->isColumnInRange($column);
}
/**
* Get a specified Table Column.
*
* @param string $column Column name (e.g. A)
*/
public function getColumn(string $column): Table\Column
{
$this->isColumnInRange($column);
if (!isset($this->columns[$column])) {
$this->columns[$column] = new Table\Column($column, $this);
}
return $this->columns[$column];
}
/**
* Get a specified Table Column by its offset.
*
* @param int $columnOffset Column offset within range (starting from 0)
*/
public function getColumnByOffset(int $columnOffset): Table\Column
{
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range);
$pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $columnOffset);
return $this->getColumn($pColumn);
}
/**
* Set Table.
*
* @param string|Table\Column $columnObjectOrString
* A simple string containing a Column ID like 'A' is permitted
*/
public function setColumn(string|Table\Column $columnObjectOrString): self
{
if ((is_string($columnObjectOrString)) && (!empty($columnObjectOrString))) {
$column = $columnObjectOrString;
} elseif ($columnObjectOrString instanceof Table\Column) {
$column = $columnObjectOrString->getColumnIndex();
} else {
throw new PhpSpreadsheetException('Column is not within the table range.');
}
$this->isColumnInRange($column);
if (is_string($columnObjectOrString)) {
$this->columns[$columnObjectOrString] = new Table\Column($columnObjectOrString, $this);
} else {
$columnObjectOrString->setTable($this);
$this->columns[$column] = $columnObjectOrString;
}
ksort($this->columns);
return $this;
}
/**
* Clear a specified Table Column.
*
* @param string $column Column name (e.g. A)
*/
public function clearColumn(string $column): self
{
$this->isColumnInRange($column);
if (isset($this->columns[$column])) {
unset($this->columns[$column]);
}
return $this;
}
/**
* Shift a Table Column Rule to a different column.
*
* Note: This method bypasses validation of the destination column to ensure it is within this Table range.
* Nor does it verify whether any column rule already exists at $toColumn, but will simply override any existing value.
* Use with caution.
*
* @param string $fromColumn Column name (e.g. A)
* @param string $toColumn Column name (e.g. B)
*/
public function shiftColumn(string $fromColumn, string $toColumn): self
{
$fromColumn = strtoupper($fromColumn);
$toColumn = strtoupper($toColumn);
if (isset($this->columns[$fromColumn])) {
$this->columns[$fromColumn]->setTable();
$this->columns[$fromColumn]->setColumnIndex($toColumn);
$this->columns[$toColumn] = $this->columns[$fromColumn];
$this->columns[$toColumn]->setTable($this);
unset($this->columns[$fromColumn]);
ksort($this->columns);
}
return $this;
}
/**
* Get table Style.
*/
public function getStyle(): TableStyle
{
return $this->style;
}
/**
* Set table Style.
*/
public function setStyle(TableStyle $style): self
{
$this->style = $style;
return $this;
}
/**
* Get AutoFilter.
*/
public function getAutoFilter(): AutoFilter
{
return $this->autoFilter;
}
/**
* Set AutoFilter.
*/
public function setAutoFilter(AutoFilter $autoFilter): self
{
$this->autoFilter = $autoFilter;
return $this;
}
/**
* Get the row number on this table for given coordinates.
*/
public function getRowNumber(string $coordinate): int
{
$range = $this->getRange();
$coords = Coordinate::splitRange($range);
$firstCell = Coordinate::coordinateFromString($coords[0][0]);
$thisCell = Coordinate::coordinateFromString($coordinate);
return (int) $thisCell[1] - (int) $firstCell[1];
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
if ($key === 'workSheet') {
// Detach from worksheet
$this->{$key} = null;
} else {
$this->{$key} = clone $value;
}
} elseif ((is_array($value)) && ($key === 'columns')) {
// The columns array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\Table objects
$this->{$key} = [];
foreach ($value as $k => $v) {
/** @var Table\Column $v */
$this->{$key}[$k] = clone $v;
// attach the new cloned Column to this new cloned Table object
$this->{$key}[$k]->setTable($this);
}
} else {
$this->{$key} = $value;
}
}
}
/**
* toString method replicates previous behavior by returning the range if object is
* referenced as a property of its worksheet.
*/
public function __toString(): string
{
return (string) $this->range;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Row.php | src/PhpSpreadsheet/Worksheet/Row.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
class Row
{
private Worksheet $worksheet;
/**
* Row index.
*/
private int $rowIndex;
/**
* Create a new row.
*/
public function __construct(Worksheet $worksheet, int $rowIndex = 1)
{
// Set parent and row index
$this->worksheet = $worksheet;
$this->rowIndex = $rowIndex;
}
/**
* Destructor.
*/
public function __destruct()
{
unset($this->worksheet);
}
/**
* Get row index.
*/
public function getRowIndex(): int
{
return $this->rowIndex;
}
/**
* Get cell iterator.
*
* @param string $startColumn The column address at which to start iterating
* @param ?string $endColumn Optionally, the column address at which to stop iterating
*/
public function getCellIterator(string $startColumn = 'A', ?string $endColumn = null, bool $iterateOnlyExistingCells = false): RowCellIterator
{
return new RowCellIterator($this->worksheet, $this->rowIndex, $startColumn, $endColumn, $iterateOnlyExistingCells);
}
/**
* Get column iterator. Synonym for getCellIterator().
*
* @param string $startColumn The column address at which to start iterating
* @param ?string $endColumn Optionally, the column address at which to stop iterating
*/
public function getColumnIterator(string $startColumn = 'A', ?string $endColumn = null, bool $iterateOnlyExistingCells = false): RowCellIterator
{
return $this->getCellIterator($startColumn, $endColumn, $iterateOnlyExistingCells);
}
/**
* Returns a boolean true if the row contains no cells. By default, this means that no cell records exist in the
* collection for this row. false will be returned otherwise.
* This rule can be modified by passing a $definitionOfEmptyFlags value:
* 1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
* cells, then the row will be considered empty.
* 2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
* string value cells, then the row will be considered empty.
* 3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
* If the only cells in the collection are null value or empty string value cells, then the row
* will be considered empty.
*
* @param int $definitionOfEmptyFlags
* Possible Flag Values are:
* CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
* CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
* @param string $startColumn The column address at which to start checking if cells are empty
* @param ?string $endColumn Optionally, the column address at which to stop checking if cells are empty
*/
public function isEmpty(int $definitionOfEmptyFlags = 0, string $startColumn = 'A', ?string $endColumn = null): bool
{
$nullValueCellIsEmpty = (bool) ($definitionOfEmptyFlags & CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL);
$emptyStringCellIsEmpty = (bool) ($definitionOfEmptyFlags & CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL);
$cellIterator = $this->getCellIterator($startColumn, $endColumn);
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $cell) {
$value = $cell->getValue();
if ($value === null && $nullValueCellIsEmpty === true) {
continue;
}
if ($value === '' && $emptyStringCellIsEmpty === true) {
continue;
}
return false;
}
return true;
}
/**
* Returns bound worksheet.
*/
public function getWorksheet(): Worksheet
{
return $this->worksheet;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/ColumnIterator.php | src/PhpSpreadsheet/Worksheet/ColumnIterator.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use Iterator as NativeIterator;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
/**
* @implements NativeIterator<string, Column>
*/
class ColumnIterator implements NativeIterator
{
/**
* Worksheet to iterate.
*/
private Worksheet $worksheet;
/**
* Current iterator position.
*/
private int $currentColumnIndex = 1;
/**
* Start position.
*/
private int $startColumnIndex = 1;
/**
* End position.
*/
private int $endColumnIndex = 1;
/**
* Create a new column iterator.
*
* @param Worksheet $worksheet The worksheet to iterate over
* @param string $startColumn The column address at which to start iterating
* @param ?string $endColumn Optionally, the column address at which to stop iterating
*/
public function __construct(Worksheet $worksheet, string $startColumn = 'A', ?string $endColumn = null)
{
// Set subject
$this->worksheet = $worksheet;
$this->resetEnd($endColumn);
$this->resetStart($startColumn);
}
/**
* Destructor.
*/
public function __destruct()
{
unset($this->worksheet);
}
/**
* (Re)Set the start column and the current column pointer.
*
* @param string $startColumn The column address at which to start iterating
*
* @return $this
*/
public function resetStart(string $startColumn = 'A'): static
{
$startColumnIndex = Coordinate::columnIndexFromString($startColumn);
if ($startColumnIndex > Coordinate::columnIndexFromString($this->worksheet->getHighestColumn())) {
throw new Exception(
"Start column ({$startColumn}) is beyond highest column ({$this->worksheet->getHighestColumn()})"
);
}
$this->startColumnIndex = $startColumnIndex;
if ($this->endColumnIndex < $this->startColumnIndex) {
$this->endColumnIndex = $this->startColumnIndex;
}
$this->seek($startColumn);
return $this;
}
/**
* (Re)Set the end column.
*
* @param ?string $endColumn The column address at which to stop iterating
*
* @return $this
*/
public function resetEnd(?string $endColumn = null): static
{
$endColumn = $endColumn ?: $this->worksheet->getHighestColumn();
$this->endColumnIndex = Coordinate::columnIndexFromString($endColumn);
return $this;
}
/**
* Set the column pointer to the selected column.
*
* @param string $column The column address to set the current pointer at
*
* @return $this
*/
public function seek(string $column = 'A'): static
{
$column = Coordinate::columnIndexFromString($column);
if (($column < $this->startColumnIndex) || ($column > $this->endColumnIndex)) {
throw new PhpSpreadsheetException(
"Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})"
);
}
$this->currentColumnIndex = $column;
return $this;
}
/**
* Rewind the iterator to the starting column.
*/
public function rewind(): void
{
$this->currentColumnIndex = $this->startColumnIndex;
}
/**
* Return the current column in this worksheet.
*/
public function current(): Column
{
return new Column($this->worksheet, Coordinate::stringFromColumnIndex($this->currentColumnIndex));
}
/**
* Return the current iterator key.
*/
public function key(): string
{
return Coordinate::stringFromColumnIndex($this->currentColumnIndex);
}
/**
* Set the iterator to its next value.
*/
public function next(): void
{
++$this->currentColumnIndex;
}
/**
* Set the iterator to its previous value.
*/
public function prev(): void
{
--$this->currentColumnIndex;
}
/**
* Indicate if more columns exist in the worksheet range of columns that we're iterating.
*/
public function valid(): bool
{
return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php | src/PhpSpreadsheet/Worksheet/MemoryDrawing.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use GdImage;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Shared\File;
class MemoryDrawing extends BaseDrawing
{
// Rendering functions
const RENDERING_DEFAULT = 'imagepng';
const RENDERING_PNG = 'imagepng';
const RENDERING_GIF = 'imagegif';
const RENDERING_JPEG = 'imagejpeg';
// MIME types
const MIMETYPE_DEFAULT = 'image/png';
const MIMETYPE_PNG = 'image/png';
const MIMETYPE_GIF = 'image/gif';
const MIMETYPE_JPEG = 'image/jpeg';
const SUPPORTED_MIME_TYPES = [
self::MIMETYPE_GIF,
self::MIMETYPE_JPEG,
self::MIMETYPE_PNG,
];
/**
* Image resource.
*/
private null|GdImage $imageResource = null;
/**
* Rendering function.
*
* @var callable-string
*/
private string $renderingFunction;
/**
* Mime type.
*/
private string $mimeType;
/**
* Unique name.
*/
private string $uniqueName;
/**
* Create a new MemoryDrawing.
*/
public function __construct()
{
// Initialise values
$this->renderingFunction = self::RENDERING_DEFAULT;
$this->mimeType = self::MIMETYPE_DEFAULT;
$this->uniqueName = md5(mt_rand(0, 9999) . time() . mt_rand(0, 9999));
// Initialize parent
parent::__construct();
}
public function __destruct()
{
$this->imageResource = null;
$this->worksheet = null;
}
public function __clone()
{
parent::__clone();
$this->cloneResource();
}
private function cloneResource(): void
{
if (!$this->imageResource) {
return;
}
$width = (int) imagesx($this->imageResource);
$height = (int) imagesy($this->imageResource);
if (imageistruecolor($this->imageResource)) {
$clone = imagecreatetruecolor($width, $height);
if (!$clone) {
throw new Exception('Could not clone image resource');
}
imagealphablending($clone, false);
imagesavealpha($clone, true);
} else {
$clone = imagecreate($width, $height);
if (!$clone) {
throw new Exception('Could not clone image resource');
}
// If the image has transparency...
$transparent = imagecolortransparent($this->imageResource);
if ($transparent >= 0) {
// Starting with Php8.0, next function throws rather than return false
$rgb = imagecolorsforindex($this->imageResource, $transparent);
imagesavealpha($clone, true);
$color = imagecolorallocatealpha($clone, $rgb['red'], $rgb['green'], $rgb['blue'], $rgb['alpha']);
if ($color === false) {
throw new Exception('Could not get image alpha color');
}
imagefill($clone, 0, 0, $color);
}
}
//Create the Clone!!
imagecopy($clone, $this->imageResource, 0, 0, 0, 0, $width, $height);
$this->imageResource = $clone;
}
/**
* @param resource $imageStream Stream data to be converted to a Memory Drawing
*
* @throws Exception
*/
public static function fromStream($imageStream): self
{
$streamValue = stream_get_contents($imageStream);
return self::fromString($streamValue);
}
/**
* @param string $imageString String data to be converted to a Memory Drawing
*
* @throws Exception
*/
public static function fromString(string $imageString): self
{
$gdImage = @imagecreatefromstring($imageString);
if ($gdImage === false) {
throw new Exception('Value cannot be converted to an image');
}
$mimeType = self::identifyMimeType($imageString);
if (imageistruecolor($gdImage) || imagecolortransparent($gdImage) >= 0) {
imagesavealpha($gdImage, true);
}
$renderingFunction = self::identifyRenderingFunction($mimeType);
$drawing = new self();
$drawing->setImageResource($gdImage);
$drawing->setRenderingFunction($renderingFunction);
$drawing->setMimeType($mimeType);
return $drawing;
}
/** @return callable-string */
private static function identifyRenderingFunction(string $mimeType): string
{
return match ($mimeType) {
self::MIMETYPE_PNG => self::RENDERING_PNG,
self::MIMETYPE_JPEG => self::RENDERING_JPEG,
self::MIMETYPE_GIF => self::RENDERING_GIF,
default => self::RENDERING_DEFAULT,
};
}
/**
* @throws Exception
*/
private static function identifyMimeType(string $imageString): string
{
$temporaryFileName = File::temporaryFilename();
file_put_contents($temporaryFileName, $imageString);
$mimeType = self::identifyMimeTypeUsingGd($temporaryFileName);
if ($mimeType !== null) {
unlink($temporaryFileName);
return $mimeType;
}
unlink($temporaryFileName);
return self::MIMETYPE_DEFAULT;
}
/** @internal */
protected static string $getImageSize = 'getImageSize';
private static function identifyMimeTypeUsingGd(string $temporaryFileName): ?string
{
if (function_exists(static::$getImageSize)) {
$imageSize = @getimagesize($temporaryFileName);
if (is_array($imageSize)) {
$mimeType = $imageSize['mime'];
return self::supportedMimeTypes($mimeType);
}
}
return null;
}
private static function supportedMimeTypes(?string $mimeType = null): ?string
{
if (in_array($mimeType, self::SUPPORTED_MIME_TYPES, true)) {
return $mimeType;
}
return null;
}
/**
* Get image resource.
*/
public function getImageResource(): ?GdImage
{
return $this->imageResource;
}
/**
* Set image resource.
*
* @return $this
*/
public function setImageResource(?GdImage $value): static
{
$this->imageResource = $value;
if ($this->imageResource !== null) {
// Get width/height
$this->width = (int) imagesx($this->imageResource);
$this->height = (int) imagesy($this->imageResource);
}
return $this;
}
/**
* Get rendering function.
*
* @return callable-string
*/
public function getRenderingFunction(): string
{
return $this->renderingFunction;
}
/**
* Set rendering function.
*
* @param callable-string $value see self::RENDERING_*
*
* @return $this
*/
public function setRenderingFunction(string $value): static
{
$this->renderingFunction = $value;
return $this;
}
/**
* Get mime type.
*/
public function getMimeType(): string
{
return $this->mimeType;
}
/**
* Set mime type.
*
* @param string $value see self::MIMETYPE_*
*
* @return $this
*/
public function setMimeType(string $value): static
{
$this->mimeType = $value;
return $this;
}
/**
* Get indexed filename (using image index).
*/
public function getIndexedFilename(): string
{
$extension = strtolower($this->getMimeType());
$extension = explode('/', $extension);
$extension = $extension[1];
return $this->uniqueName . $this->getImageIndex() . '.' . $extension;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
return md5(
$this->renderingFunction
. $this->mimeType
. $this->uniqueName
. parent::getHashCode()
. __CLASS__
);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/CellIterator.php | src/PhpSpreadsheet/Worksheet/CellIterator.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use Iterator as NativeIterator;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Collection\Cells;
/**
* @template TKey
*
* @implements NativeIterator<TKey, Cell>
*/
abstract class CellIterator implements NativeIterator
{
public const TREAT_NULL_VALUE_AS_EMPTY_CELL = 1;
public const TREAT_EMPTY_STRING_AS_EMPTY_CELL = 2;
public const IF_NOT_EXISTS_RETURN_NULL = false;
public const IF_NOT_EXISTS_CREATE_NEW = true;
/**
* Worksheet to iterate.
*/
protected Worksheet $worksheet;
/**
* Cell Collection to iterate.
*/
protected Cells $cellCollection;
/**
* Iterate only existing cells.
*/
protected bool $onlyExistingCells = false;
/**
* If iterating all cells, and a cell doesn't exist, identifies whether a new cell should be created,
* or if the iterator should return a null value.
*/
protected bool $ifNotExists = self::IF_NOT_EXISTS_CREATE_NEW;
/**
* Destructor.
*/
public function __destruct()
{
unset($this->worksheet, $this->cellCollection);
}
public function getIfNotExists(): bool
{
return $this->ifNotExists;
}
public function setIfNotExists(bool $ifNotExists = self::IF_NOT_EXISTS_CREATE_NEW): void
{
$this->ifNotExists = $ifNotExists;
}
/**
* Get loop only existing cells.
*/
public function getIterateOnlyExistingCells(): bool
{
return $this->onlyExistingCells;
}
/**
* Validate start/end values for 'IterateOnlyExistingCells' mode, and adjust if necessary.
*/
abstract protected function adjustForExistingOnlyRange(): void;
/**
* Set the iterator to loop only existing cells.
*/
public function setIterateOnlyExistingCells(bool $value): void
{
$this->onlyExistingCells = (bool) $value;
$this->adjustForExistingOnlyRange();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/PageBreak.php | src/PhpSpreadsheet/Worksheet/PageBreak.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
class PageBreak
{
private int $breakType;
private string $coordinate;
private int $maxColOrRow;
/**
* @param array{0: int, 1: int}|CellAddress|string $coordinate
*/
public function __construct(int $breakType, CellAddress|string|array $coordinate, int $maxColOrRow = -1)
{
$coordinate = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
$this->breakType = $breakType;
$this->coordinate = $coordinate;
$this->maxColOrRow = $maxColOrRow;
}
public function getBreakType(): int
{
return $this->breakType;
}
public function getCoordinate(): string
{
return $this->coordinate;
}
public function getMaxColOrRow(): int
{
return $this->maxColOrRow;
}
public function getColumnInt(): int
{
return Coordinate::indexesFromString($this->coordinate)[0];
}
public function getRow(): int
{
return Coordinate::indexesFromString($this->coordinate)[1];
}
public function getColumnString(): string
{
return Coordinate::indexesFromString($this->coordinate)[2];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Worksheet.php | src/PhpSpreadsheet/Worksheet/Worksheet.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use ArrayObject;
use Composer\Pcre\Preg;
use Generator;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
use PhpOffice\PhpSpreadsheet\Cell\IValueBinder;
use PhpOffice\PhpSpreadsheet\Chart\Chart;
use PhpOffice\PhpSpreadsheet\Collection\Cells;
use PhpOffice\PhpSpreadsheet\Collection\CellsFactory;
use PhpOffice\PhpSpreadsheet\Comment;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Protection as StyleProtection;
use PhpOffice\PhpSpreadsheet\Style\Style;
class Worksheet
{
// Break types
public const BREAK_NONE = 0;
public const BREAK_ROW = 1;
public const BREAK_COLUMN = 2;
// Maximum column for row break
public const BREAK_ROW_MAX_COLUMN = 16383;
// Sheet state
public const SHEETSTATE_VISIBLE = 'visible';
public const SHEETSTATE_HIDDEN = 'hidden';
public const SHEETSTATE_VERYHIDDEN = 'veryHidden';
public const MERGE_CELL_CONTENT_EMPTY = 'empty';
public const MERGE_CELL_CONTENT_HIDE = 'hide';
public const MERGE_CELL_CONTENT_MERGE = 'merge';
public const FUNCTION_LIKE_GROUPBY = '/\b(groupby|_xleta)\b/i'; // weird new syntax
protected const SHEET_NAME_REQUIRES_NO_QUOTES = '/^[_\p{L}][_\p{L}\p{N}]*$/mui';
/**
* Maximum 31 characters allowed for sheet title.
*
* @var int
*/
const SHEET_TITLE_MAXIMUM_LENGTH = 31;
/**
* Invalid characters in sheet title.
*/
private const INVALID_CHARACTERS = ['*', ':', '/', '\\', '?', '[', ']'];
/**
* Parent spreadsheet.
*/
private ?Spreadsheet $parent = null;
/**
* Collection of cells.
*/
private Cells $cellCollection;
/**
* Collection of row dimensions.
*
* @var RowDimension[]
*/
private array $rowDimensions = [];
/**
* Default row dimension.
*/
private RowDimension $defaultRowDimension;
/**
* Collection of column dimensions.
*
* @var ColumnDimension[]
*/
private array $columnDimensions = [];
/**
* Default column dimension.
*/
private ColumnDimension $defaultColumnDimension;
/**
* Collection of drawings.
*
* @var ArrayObject<int, BaseDrawing>
*/
private ArrayObject $drawingCollection;
/**
* Collection of Chart objects.
*
* @var ArrayObject<int, Chart>
*/
private ArrayObject $chartCollection;
/**
* Collection of Table objects.
*
* @var ArrayObject<int, Table>
*/
private ArrayObject $tableCollection;
/**
* Worksheet title.
*/
private string $title = '';
/**
* Sheet state.
*/
private string $sheetState;
/**
* Page setup.
*/
private PageSetup $pageSetup;
/**
* Page margins.
*/
private PageMargins $pageMargins;
/**
* Page header/footer.
*/
private HeaderFooter $headerFooter;
/**
* Sheet view.
*/
private SheetView $sheetView;
/**
* Protection.
*/
private Protection $protection;
/**
* Conditional styles. Indexed by cell coordinate, e.g. 'A1'.
*
* @var Conditional[][]
*/
private array $conditionalStylesCollection = [];
/**
* Collection of row breaks.
*
* @var PageBreak[]
*/
private array $rowBreaks = [];
/**
* Collection of column breaks.
*
* @var PageBreak[]
*/
private array $columnBreaks = [];
/**
* Collection of merged cell ranges.
*
* @var string[]
*/
private array $mergeCells = [];
/**
* Collection of protected cell ranges.
*
* @var ProtectedRange[]
*/
private array $protectedCells = [];
/**
* Autofilter Range and selection.
*/
private AutoFilter $autoFilter;
/**
* Freeze pane.
*/
private ?string $freezePane = null;
/**
* Default position of the right bottom pane.
*/
private ?string $topLeftCell = null;
private string $paneTopLeftCell = '';
private string $activePane = '';
private int $xSplit = 0;
private int $ySplit = 0;
private string $paneState = '';
/**
* Properties of the 4 panes.
*
* @var (null|Pane)[]
*/
private array $panes = [
'bottomRight' => null,
'bottomLeft' => null,
'topRight' => null,
'topLeft' => null,
];
/**
* Show gridlines?
*/
private bool $showGridlines = true;
/**
* Print gridlines?
*/
private bool $printGridlines = false;
/**
* Show row and column headers?
*/
private bool $showRowColHeaders = true;
/**
* Show summary below? (Row/Column outline).
*/
private bool $showSummaryBelow = true;
/**
* Show summary right? (Row/Column outline).
*/
private bool $showSummaryRight = true;
/**
* Collection of comments.
*
* @var Comment[]
*/
private array $comments = [];
/**
* Active cell. (Only one!).
*/
private string $activeCell = 'A1';
/**
* Selected cells.
*/
private string $selectedCells = 'A1';
/**
* Cached highest column.
*/
private int $cachedHighestColumn = 1;
/**
* Cached highest row.
*/
private int $cachedHighestRow = 1;
/**
* Right-to-left?
*/
private bool $rightToLeft = false;
/**
* Hyperlinks. Indexed by cell coordinate, e.g. 'A1'.
*
* @var Hyperlink[]
*/
private array $hyperlinkCollection = [];
/**
* Data validation objects. Indexed by cell coordinate, e.g. 'A1'.
* Index can include ranges, and multiple cells/ranges.
*
* @var DataValidation[]
*/
private array $dataValidationCollection = [];
/**
* Tab color.
*/
private ?Color $tabColor = null;
/**
* CodeName.
*/
private ?string $codeName = null;
/**
* Create a new worksheet.
*/
public function __construct(?Spreadsheet $parent = null, string $title = 'Worksheet')
{
// Set parent and title
$this->parent = $parent;
$this->setTitle($title, false);
// setTitle can change $pTitle
$this->setCodeName($this->getTitle());
$this->setSheetState(self::SHEETSTATE_VISIBLE);
$this->cellCollection = CellsFactory::getInstance($this);
// Set page setup
$this->pageSetup = new PageSetup();
// Set page margins
$this->pageMargins = new PageMargins();
// Set page header/footer
$this->headerFooter = new HeaderFooter();
// Set sheet view
$this->sheetView = new SheetView();
// Drawing collection
$this->drawingCollection = new ArrayObject();
// Chart collection
$this->chartCollection = new ArrayObject();
// Protection
$this->protection = new Protection();
// Default row dimension
$this->defaultRowDimension = new RowDimension(null);
// Default column dimension
$this->defaultColumnDimension = new ColumnDimension(null);
// AutoFilter
$this->autoFilter = new AutoFilter('', $this);
// Table collection
$this->tableCollection = new ArrayObject();
}
/**
* Disconnect all cells from this Worksheet object,
* typically so that the worksheet object can be unset.
*/
public function disconnectCells(): void
{
if (isset($this->cellCollection)) { //* @phpstan-ignore-line
$this->cellCollection->unsetWorksheetCells();
unset($this->cellCollection);
}
// detach ourself from the workbook, so that it can then delete this worksheet successfully
$this->parent = null;
}
/**
* Code to execute when this worksheet is unset().
*/
public function __destruct()
{
Calculation::getInstanceOrNull($this->parent)
?->clearCalculationCacheForWorksheet($this->title);
$this->disconnectCells();
unset($this->rowDimensions, $this->columnDimensions, $this->tableCollection, $this->drawingCollection, $this->chartCollection, $this->autoFilter);
}
/**
* Return the cell collection.
*/
public function getCellCollection(): Cells
{
return $this->cellCollection;
}
/**
* Get array of invalid characters for sheet title.
*
* @return string[]
*/
public static function getInvalidCharacters(): array
{
return self::INVALID_CHARACTERS;
}
/**
* Check sheet code name for valid Excel syntax.
*
* @param string $sheetCodeName The string to check
*
* @return string The valid string
*/
private static function checkSheetCodeName(string $sheetCodeName): string
{
$charCount = StringHelper::countCharacters($sheetCodeName);
if ($charCount == 0) {
throw new Exception('Sheet code name cannot be empty.');
}
// Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'"
if (
(str_replace(self::INVALID_CHARACTERS, '', $sheetCodeName) !== $sheetCodeName)
|| (StringHelper::substring($sheetCodeName, -1, 1) == '\'')
|| (StringHelper::substring($sheetCodeName, 0, 1) == '\'')
) {
throw new Exception('Invalid character found in sheet code name');
}
// Enforce maximum characters allowed for sheet title
if ($charCount > self::SHEET_TITLE_MAXIMUM_LENGTH) {
throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.');
}
return $sheetCodeName;
}
/**
* Check sheet title for valid Excel syntax.
*
* @param string $sheetTitle The string to check
*
* @return string The valid string
*/
private static function checkSheetTitle(string $sheetTitle): string
{
// Some of the printable ASCII characters are invalid: * : / \ ? [ ]
if (str_replace(self::INVALID_CHARACTERS, '', $sheetTitle) !== $sheetTitle) {
throw new Exception('Invalid character found in sheet title');
}
// Enforce maximum characters allowed for sheet title
if (StringHelper::countCharacters($sheetTitle) > self::SHEET_TITLE_MAXIMUM_LENGTH) {
throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.');
}
return $sheetTitle;
}
/**
* Get a sorted list of all cell coordinates currently held in the collection by row and column.
*
* @param bool $sorted Also sort the cell collection?
*
* @return string[]
*/
public function getCoordinates(bool $sorted = true): array
{
if (!isset($this->cellCollection)) { //* @phpstan-ignore-line
return [];
}
if ($sorted) {
return $this->cellCollection->getSortedCoordinates();
}
return $this->cellCollection->getCoordinates();
}
/**
* Get collection of row dimensions.
*
* @return RowDimension[]
*/
public function getRowDimensions(): array
{
return $this->rowDimensions;
}
/**
* Get default row dimension.
*/
public function getDefaultRowDimension(): RowDimension
{
return $this->defaultRowDimension;
}
/**
* Get collection of column dimensions.
*
* @return ColumnDimension[]
*/
public function getColumnDimensions(): array
{
/** @var callable $callable */
$callable = [self::class, 'columnDimensionCompare'];
uasort($this->columnDimensions, $callable);
return $this->columnDimensions;
}
private static function columnDimensionCompare(ColumnDimension $a, ColumnDimension $b): int
{
return $a->getColumnNumeric() - $b->getColumnNumeric();
}
/**
* Get default column dimension.
*/
public function getDefaultColumnDimension(): ColumnDimension
{
return $this->defaultColumnDimension;
}
/**
* Get collection of drawings.
*
* @return ArrayObject<int, BaseDrawing>
*/
public function getDrawingCollection(): ArrayObject
{
return $this->drawingCollection;
}
/**
* Get collection of charts.
*
* @return ArrayObject<int, Chart>
*/
public function getChartCollection(): ArrayObject
{
return $this->chartCollection;
}
public function addChart(Chart $chart): Chart
{
$chart->setWorksheet($this);
$this->chartCollection[] = $chart;
return $chart;
}
/**
* Return the count of charts on this worksheet.
*
* @return int The number of charts
*/
public function getChartCount(): int
{
return count($this->chartCollection);
}
/**
* Get a chart by its index position.
*
* @param ?string $index Chart index position
*
* @return Chart|false
*/
public function getChartByIndex(?string $index)
{
$chartCount = count($this->chartCollection);
if ($chartCount == 0) {
return false;
}
if ($index === null) {
$index = --$chartCount;
}
if (!isset($this->chartCollection[$index])) {
return false;
}
return $this->chartCollection[$index];
}
/**
* Return an array of the names of charts on this worksheet.
*
* @return string[] The names of charts
*/
public function getChartNames(): array
{
$chartNames = [];
foreach ($this->chartCollection as $chart) {
$chartNames[] = $chart->getName();
}
return $chartNames;
}
/**
* Get a chart by name.
*
* @param string $chartName Chart name
*
* @return Chart|false
*/
public function getChartByName(string $chartName)
{
foreach ($this->chartCollection as $index => $chart) {
if ($chart->getName() == $chartName) {
return $chart;
}
}
return false;
}
public function getChartByNameOrThrow(string $chartName): Chart
{
$chart = $this->getChartByName($chartName);
if ($chart !== false) {
return $chart;
}
throw new Exception("Sheet does not have a chart named $chartName.");
}
/**
* Refresh column dimensions.
*
* @return $this
*/
public function refreshColumnDimensions(): static
{
$newColumnDimensions = [];
foreach ($this->getColumnDimensions() as $objColumnDimension) {
$newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension;
}
$this->columnDimensions = $newColumnDimensions;
return $this;
}
/**
* Refresh row dimensions.
*
* @return $this
*/
public function refreshRowDimensions(): static
{
$newRowDimensions = [];
foreach ($this->getRowDimensions() as $objRowDimension) {
$newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension;
}
$this->rowDimensions = $newRowDimensions;
return $this;
}
/**
* Calculate worksheet dimension.
*
* @return string String containing the dimension of this worksheet
*/
public function calculateWorksheetDimension(): string
{
// Return
return 'A1:' . $this->getHighestColumn() . $this->getHighestRow();
}
/**
* Calculate worksheet data dimension.
*
* @return string String containing the dimension of this worksheet that actually contain data
*/
public function calculateWorksheetDataDimension(): string
{
// Return
return 'A1:' . $this->getHighestDataColumn() . $this->getHighestDataRow();
}
/**
* Calculate widths for auto-size columns.
*
* @return $this
*/
public function calculateColumnWidths(): static
{
$activeSheet = $this->getParent()?->getActiveSheetIndex();
$selectedCells = $this->selectedCells;
// initialize $autoSizes array
$autoSizes = [];
foreach ($this->getColumnDimensions() as $colDimension) {
if ($colDimension->getAutoSize()) {
$autoSizes[$colDimension->getColumnIndex()] = -1;
}
}
// There is only something to do if there are some auto-size columns
if (!empty($autoSizes)) {
$holdActivePane = $this->activePane;
// build list of cells references that participate in a merge
$isMergeCell = [];
foreach ($this->getMergeCells() as $cells) {
foreach (Coordinate::extractAllCellReferencesInRange($cells) as $cellReference) {
$isMergeCell[$cellReference] = true;
}
}
$autoFilterIndentRanges = (new AutoFit($this))->getAutoFilterIndentRanges();
// loop through all cells in the worksheet
foreach ($this->getCoordinates(false) as $coordinate) {
$cell = $this->getCellOrNull($coordinate);
if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) {
//Determine if cell is in merge range
$isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]);
//By default merged cells should be ignored
$isMergedButProceed = false;
//The only exception is if it's a merge range value cell of a 'vertical' range (1 column wide)
if ($isMerged && $cell->isMergeRangeValueCell()) {
$range = (string) $cell->getMergeRange();
$rangeBoundaries = Coordinate::rangeDimension($range);
if ($rangeBoundaries[0] === 1) {
$isMergedButProceed = true;
}
}
// Determine width if cell is not part of a merge or does and is a value cell of 1-column wide range
if (!$isMerged || $isMergedButProceed) {
// Determine if we need to make an adjustment for the first row in an AutoFilter range that
// has a column filter dropdown
$filterAdjustment = false;
if (!empty($autoFilterIndentRanges)) {
foreach ($autoFilterIndentRanges as $autoFilterFirstRowRange) {
/** @var string $autoFilterFirstRowRange */
if ($cell->isInRange($autoFilterFirstRowRange)) {
$filterAdjustment = true;
break;
}
}
}
$indentAdjustment = $cell->getStyle()->getAlignment()->getIndent();
$indentAdjustment += (int) ($cell->getStyle()->getAlignment()->getHorizontal() === Alignment::HORIZONTAL_CENTER);
// Calculated value
// To formatted string
$cellValue = NumberFormat::toFormattedString(
$cell->getCalculatedValueString(),
(string) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())
->getNumberFormat()->getFormatCode(true)
);
if ($cellValue !== '') {
$autoSizes[$this->cellCollection->getCurrentColumn()] = max(
$autoSizes[$this->cellCollection->getCurrentColumn()],
round(
Shared\Font::calculateColumnWidth(
$this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont(),
$cellValue,
(int) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())
->getAlignment()->getTextRotation(),
$this->getParentOrThrow()->getDefaultStyle()->getFont(),
$filterAdjustment,
$indentAdjustment
),
3
)
);
}
}
}
}
// adjust column widths
foreach ($autoSizes as $columnIndex => $width) {
if ($width == -1) {
$width = $this->getDefaultColumnDimension()->getWidth();
}
$this->getColumnDimension($columnIndex)->setWidth($width);
}
$this->activePane = $holdActivePane;
}
if ($activeSheet !== null && $activeSheet >= 0) {
$this->getParent()?->setActiveSheetIndex($activeSheet);
}
$this->setSelectedCells($selectedCells);
return $this;
}
/**
* Get parent or null.
*/
public function getParent(): ?Spreadsheet
{
return $this->parent;
}
/**
* Get parent, throw exception if null.
*/
public function getParentOrThrow(): Spreadsheet
{
if ($this->parent !== null) {
return $this->parent;
}
throw new Exception('Sheet does not have a parent.');
}
/**
* Re-bind parent.
*
* @return $this
*/
public function rebindParent(Spreadsheet $parent): static
{
if ($this->parent !== null) {
$definedNames = $this->parent->getDefinedNames();
foreach ($definedNames as $definedName) {
$parent->addDefinedName($definedName);
}
$this->parent->removeSheetByIndex(
$this->parent->getIndex($this)
);
}
$this->parent = $parent;
return $this;
}
public function setParent(Spreadsheet $parent): self
{
$this->parent = $parent;
return $this;
}
/**
* Get title.
*/
public function getTitle(): string
{
return $this->title;
}
/**
* Set title.
*
* @param string $title String containing the dimension of this worksheet
* @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should
* be updated to reflect the new sheet name.
* This should be left as the default true, unless you are
* certain that no formula cells on any worksheet contain
* references to this worksheet
* @param bool $validate False to skip validation of new title. WARNING: This should only be set
* at parse time (by Readers), where titles can be assumed to be valid.
*
* @return $this
*/
public function setTitle(string $title, bool $updateFormulaCellReferences = true, bool $validate = true): static
{
// Is this a 'rename' or not?
if ($this->getTitle() == $title) {
return $this;
}
// Old title
$oldTitle = $this->getTitle();
if ($validate) {
// Syntax check
self::checkSheetTitle($title);
if ($this->parent && $this->parent->getIndex($this, true) >= 0) {
// Is there already such sheet name?
if ($this->parent->sheetNameExists($title)) {
// Use name, but append with lowest possible integer
if (StringHelper::countCharacters($title) > 29) {
$title = StringHelper::substring($title, 0, 29);
}
$i = 1;
while ($this->parent->sheetNameExists($title . ' ' . $i)) {
++$i;
if ($i == 10) {
if (StringHelper::countCharacters($title) > 28) {
$title = StringHelper::substring($title, 0, 28);
}
} elseif ($i == 100) {
if (StringHelper::countCharacters($title) > 27) {
$title = StringHelper::substring($title, 0, 27);
}
}
}
$title .= " $i";
}
}
}
// Set title
$this->title = $title;
if ($this->parent && $this->parent->getIndex($this, true) >= 0) {
// New title
$newTitle = $this->getTitle();
$this->parent->getCalculationEngine()
->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
if ($updateFormulaCellReferences) {
ReferenceHelper::getInstance()->updateNamedFormulae($this->parent, $oldTitle, $newTitle);
}
}
return $this;
}
/**
* Get sheet state.
*
* @return string Sheet state (visible, hidden, veryHidden)
*/
public function getSheetState(): string
{
return $this->sheetState;
}
/**
* Set sheet state.
*
* @param string $value Sheet state (visible, hidden, veryHidden)
*
* @return $this
*/
public function setSheetState(string $value): static
{
$this->sheetState = $value;
return $this;
}
/**
* Get page setup.
*/
public function getPageSetup(): PageSetup
{
return $this->pageSetup;
}
/**
* Set page setup.
*
* @return $this
*/
public function setPageSetup(PageSetup $pageSetup): static
{
$this->pageSetup = $pageSetup;
return $this;
}
/**
* Get page margins.
*/
public function getPageMargins(): PageMargins
{
return $this->pageMargins;
}
/**
* Set page margins.
*
* @return $this
*/
public function setPageMargins(PageMargins $pageMargins): static
{
$this->pageMargins = $pageMargins;
return $this;
}
/**
* Get page header/footer.
*/
public function getHeaderFooter(): HeaderFooter
{
return $this->headerFooter;
}
/**
* Set page header/footer.
*
* @return $this
*/
public function setHeaderFooter(HeaderFooter $headerFooter): static
{
$this->headerFooter = $headerFooter;
return $this;
}
/**
* Get sheet view.
*/
public function getSheetView(): SheetView
{
return $this->sheetView;
}
/**
* Set sheet view.
*
* @return $this
*/
public function setSheetView(SheetView $sheetView): static
{
$this->sheetView = $sheetView;
return $this;
}
/**
* Get Protection.
*/
public function getProtection(): Protection
{
return $this->protection;
}
/**
* Set Protection.
*
* @return $this
*/
public function setProtection(Protection $protection): static
{
$this->protection = $protection;
return $this;
}
/**
* Get highest worksheet column.
*
* @param null|int|string $row Return the data highest column for the specified row,
* or the highest column of any row if no row number is passed
*
* @return string Highest column name
*/
public function getHighestColumn($row = null): string
{
if ($row === null) {
return Coordinate::stringFromColumnIndex($this->cachedHighestColumn);
}
return $this->getHighestDataColumn($row);
}
/**
* Get highest worksheet column that contains data.
*
* @param null|int|string $row Return the highest data column for the specified row,
* or the highest data column of any row if no row number is passed
*
* @return string Highest column name that contains data
*/
public function getHighestDataColumn($row = null): string
{
return $this->cellCollection->getHighestColumn($row);
}
/**
* Get highest worksheet row.
*
* @param null|string $column Return the highest data row for the specified column,
* or the highest row of any column if no column letter is passed
*
* @return int Highest row number
*/
public function getHighestRow(?string $column = null): int
{
if ($column === null) {
return $this->cachedHighestRow;
}
return $this->getHighestDataRow($column);
}
/**
* Get highest worksheet row that contains data.
*
* @param null|string $column Return the highest data row for the specified column,
* or the highest data row of any column if no column letter is passed
*
* @return int Highest row number that contains data
*/
public function getHighestDataRow(?string $column = null): int
{
return $this->cellCollection->getHighestRow($column);
}
/**
* Get highest worksheet column and highest row that have cell records.
*
* @return array{row: int, column: string} Highest column name and highest row number
*/
public function getHighestRowAndColumn(): array
{
return $this->cellCollection->getHighestRowAndColumn();
}
/**
* Set a cell value.
*
* @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
* or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
* @param mixed $value Value for the cell
* @param null|IValueBinder $binder Value Binder to override the currently set Value Binder
*
* @return $this
*/
public function setCellValue(CellAddress|string|array $coordinate, mixed $value, ?IValueBinder $binder = null): static
{
$cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate));
$this->getCell($cellAddress)->setValue($value, $binder);
return $this;
}
/**
* Set a cell value.
*
* @param array{0: int, 1: int}|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5';
* or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
* @param mixed $value Value of the cell
* @param string $dataType Explicit data type, see DataType::TYPE_*
* Note that PhpSpreadsheet does not validate that the value and datatype are consistent, in using this
* method, then it is your responsibility as an end-user developer to validate that the value and
* the datatype match.
* If you do mismatch value and datatpe, then the value you enter may be changed to match the datatype
* that you specify.
*
* @see DataType
*
* @return $this
*/
public function setCellValueExplicit(CellAddress|string|array $coordinate, mixed $value, string $dataType): static
{
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | true |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/PageMargins.php | src/PhpSpreadsheet/Worksheet/PageMargins.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
class PageMargins
{
/**
* Left.
*/
private float $left = 0.7;
/**
* Right.
*/
private float $right = 0.7;
/**
* Top.
*/
private float $top = 0.75;
/**
* Bottom.
*/
private float $bottom = 0.75;
/**
* Header.
*/
private float $header = 0.3;
/**
* Footer.
*/
private float $footer = 0.3;
/**
* Create a new PageMargins.
*/
public function __construct()
{
}
/**
* Get Left.
*/
public function getLeft(): float
{
return $this->left;
}
/**
* Set Left.
*
* @return $this
*/
public function setLeft(float $left): static
{
$this->left = $left;
return $this;
}
/**
* Get Right.
*/
public function getRight(): float
{
return $this->right;
}
/**
* Set Right.
*
* @return $this
*/
public function setRight(float $right): static
{
$this->right = $right;
return $this;
}
/**
* Get Top.
*/
public function getTop(): float
{
return $this->top;
}
/**
* Set Top.
*
* @return $this
*/
public function setTop(float $top): static
{
$this->top = $top;
return $this;
}
/**
* Get Bottom.
*/
public function getBottom(): float
{
return $this->bottom;
}
/**
* Set Bottom.
*
* @return $this
*/
public function setBottom(float $bottom): static
{
$this->bottom = $bottom;
return $this;
}
/**
* Get Header.
*/
public function getHeader(): float
{
return $this->header;
}
/**
* Set Header.
*
* @return $this
*/
public function setHeader(float $header): static
{
$this->header = $header;
return $this;
}
/**
* Get Footer.
*/
public function getFooter(): float
{
return $this->footer;
}
/**
* Set Footer.
*
* @return $this
*/
public function setFooter(float $footer): static
{
$this->footer = $footer;
return $this;
}
public static function fromCentimeters(float $value): float
{
return $value / 2.54;
}
public static function toCentimeters(float $value): float
{
return $value * 2.54;
}
public static function fromMillimeters(float $value): float
{
return $value / 25.4;
}
public static function toMillimeters(float $value): float
{
return $value * 25.4;
}
public static function fromPoints(float $value): float
{
return $value / 72;
}
public static function toPoints(float $value): float
{
return $value * 72;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/BaseDrawing.php | src/PhpSpreadsheet/Worksheet/BaseDrawing.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\IComparable;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing\Shadow;
use SimpleXMLElement;
class BaseDrawing implements IComparable
{
const EDIT_AS_ABSOLUTE = 'absolute';
const EDIT_AS_ONECELL = 'oneCell';
const EDIT_AS_TWOCELL = 'twoCell';
private const VALID_EDIT_AS = [
self::EDIT_AS_ABSOLUTE,
self::EDIT_AS_ONECELL,
self::EDIT_AS_TWOCELL,
];
/**
* The editAs attribute, used only with two cell anchor.
*/
protected string $editAs = '';
/**
* Image counter.
*/
private static int $imageCounter = 0;
/**
* Image index.
*/
private int $imageIndex;
/**
* Name.
*/
protected string $name = '';
/**
* Description.
*/
protected string $description = '';
/**
* Worksheet.
*/
protected ?Worksheet $worksheet = null;
/**
* Coordinates.
*/
protected string $coordinates = 'A1';
/**
* Offset X.
*/
protected int $offsetX = 0;
/**
* Offset Y.
*/
protected int $offsetY = 0;
/**
* Coordinates2.
*/
protected string $coordinates2 = '';
/**
* Offset X2.
*/
protected int $offsetX2 = 0;
/**
* Offset Y2.
*/
protected int $offsetY2 = 0;
/**
* Width.
*/
protected int $width = 0;
/**
* Height.
*/
protected int $height = 0;
/**
* Pixel width of image. See $width for the size the Drawing will be in the sheet.
*/
protected int $imageWidth = 0;
/**
* Pixel width of image. See $height for the size the Drawing will be in the sheet.
*/
protected int $imageHeight = 0;
/**
* Proportional resize.
*/
protected bool $resizeProportional = true;
/**
* Rotation.
*/
protected int $rotation = 0;
protected bool $flipVertical = false;
protected bool $flipHorizontal = false;
/**
* Shadow.
*/
protected Shadow $shadow;
/**
* Image hyperlink.
*/
private ?Hyperlink $hyperlink = null;
/**
* Image type.
*/
protected int $type = IMAGETYPE_UNKNOWN;
/** @var null|SimpleXMLElement|string[] */
protected $srcRect = [];
/**
* Percentage multiplied by 100,000, e.g. 40% = 40,000.
* Opacity=x is the same as transparency=100000-x.
*/
protected ?int $opacity = null;
/**
* Create a new BaseDrawing.
*/
public function __construct()
{
// Initialise values
$this->setShadow();
// Set image index
++self::$imageCounter;
$this->imageIndex = self::$imageCounter;
}
public function __destruct()
{
$this->worksheet = null;
}
public function getImageIndex(): int
{
return $this->imageIndex;
}
public function getName(): string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getDescription(): string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getWorksheet(): ?Worksheet
{
return $this->worksheet;
}
/**
* Set Worksheet.
*
* @param bool $overrideOld If a Worksheet has already been assigned, overwrite it and remove image from old Worksheet?
*/
public function setWorksheet(?Worksheet $worksheet = null, bool $overrideOld = false): self
{
if ($this->worksheet === null) {
// Add drawing to Worksheet
if ($worksheet !== null) {
$this->worksheet = $worksheet;
if (!($this instanceof Drawing && $this->getPath() === '')) {
$this->worksheet->getCell($this->coordinates);
}
$this->worksheet->getDrawingCollection()
->append($this);
}
} else {
if ($overrideOld) {
// Remove drawing from old Worksheet
$iterator = $this->worksheet->getDrawingCollection()->getIterator();
while ($iterator->valid()) {
if ($iterator->current()->getHashCode() === $this->getHashCode()) {
$this->worksheet->getDrawingCollection()->offsetUnset($iterator->key());
$this->worksheet = null;
break;
}
}
// Set new Worksheet
$this->setWorksheet($worksheet);
} else {
throw new PhpSpreadsheetException('A Worksheet has already been assigned. Drawings can only exist on one Worksheet.');
}
}
return $this;
}
public function getCoordinates(): string
{
return $this->coordinates;
}
public function setCoordinates(string $coordinates): self
{
$this->coordinates = $coordinates;
if ($this->worksheet !== null) {
if (!($this instanceof Drawing && $this->getPath() === '')) {
$this->worksheet->getCell($this->coordinates);
}
}
return $this;
}
public function getOffsetX(): int
{
return $this->offsetX;
}
public function setOffsetX(int $offsetX): self
{
$this->offsetX = $offsetX;
return $this;
}
public function getOffsetY(): int
{
return $this->offsetY;
}
public function setOffsetY(int $offsetY): self
{
$this->offsetY = $offsetY;
return $this;
}
public function getCoordinates2(): string
{
return $this->coordinates2;
}
public function setCoordinates2(string $coordinates2): self
{
$this->coordinates2 = $coordinates2;
return $this;
}
public function getOffsetX2(): int
{
return $this->offsetX2;
}
public function setOffsetX2(int $offsetX2): self
{
$this->offsetX2 = $offsetX2;
return $this;
}
public function getOffsetY2(): int
{
return $this->offsetY2;
}
public function setOffsetY2(int $offsetY2): self
{
$this->offsetY2 = $offsetY2;
return $this;
}
public function getWidth(): int
{
return $this->width;
}
public function setWidth(int $width): self
{
// Resize proportional?
if ($this->resizeProportional && $width != 0) {
$ratio = $this->height / ($this->width != 0 ? $this->width : 1);
$this->height = (int) round($ratio * $width);
}
// Set width
$this->width = $width;
return $this;
}
public function getHeight(): int
{
return $this->height;
}
public function setHeight(int $height): self
{
// Resize proportional?
if ($this->resizeProportional && $height != 0) {
$ratio = $this->width / ($this->height != 0 ? $this->height : 1);
$this->width = (int) round($ratio * $height);
}
// Set height
$this->height = $height;
return $this;
}
/**
* Set width and height with proportional resize.
*
* Example:
* <code>
* $objDrawing->setResizeProportional(true);
* $objDrawing->setWidthAndHeight(160,120);
* </code>
*
* @author Vincent@luo MSN:kele_100@hotmail.com
*/
public function setWidthAndHeight(int $width, int $height): self
{
if ($this->width === 0 || $this->height === 0 || $width === 0 || $height === 0 || !$this->resizeProportional) {
$this->width = $width;
$this->height = $height;
} else {
$xratio = $width / $this->width;
$yratio = $height / $this->height;
if (($xratio * $this->height) < $height) {
$this->height = (int) ceil($xratio * $this->height);
$this->width = $width;
} else {
$this->width = (int) ceil($yratio * $this->width);
$this->height = $height;
}
}
return $this;
}
public function getResizeProportional(): bool
{
return $this->resizeProportional;
}
public function setResizeProportional(bool $resizeProportional): self
{
$this->resizeProportional = $resizeProportional;
return $this;
}
public function getRotation(): int
{
return $this->rotation;
}
public function setRotation(int $rotation): self
{
$this->rotation = $rotation;
return $this;
}
public function getShadow(): Shadow
{
return $this->shadow;
}
public function setShadow(?Shadow $shadow = null): self
{
$this->shadow = $shadow ?? new Shadow();
return $this;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
return md5(
$this->name
. $this->description
. (($this->worksheet === null) ? '' : (string) spl_object_id($this->worksheet))
. $this->coordinates
. $this->offsetX
. $this->offsetY
. $this->coordinates2
. $this->offsetX2
. $this->offsetY2
. $this->width
. $this->height
. $this->rotation
. $this->shadow->getHashCode()
. __CLASS__
);
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if ($key == 'worksheet') {
$this->worksheet = null;
} elseif (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
public function setHyperlink(?Hyperlink $hyperlink = null): void
{
$this->hyperlink = $hyperlink;
}
public function getHyperlink(): ?Hyperlink
{
return $this->hyperlink;
}
/**
* Set Fact Sizes and Type of Image.
*/
protected function setSizesAndType(string $path): void
{
if ($this->imageWidth === 0 && $this->imageHeight === 0 && $this->type === IMAGETYPE_UNKNOWN) {
$imageData = getimagesize($path);
if (!empty($imageData)) {
$this->imageWidth = $imageData[0];
$this->imageHeight = $imageData[1];
$this->type = $imageData[2];
}
}
if ($this->width === 0 && $this->height === 0) {
$this->width = $this->imageWidth;
$this->height = $this->imageHeight;
}
}
/**
* Get Image Type.
*/
public function getType(): int
{
return $this->type;
}
public function getImageWidth(): int
{
return $this->imageWidth;
}
public function getImageHeight(): int
{
return $this->imageHeight;
}
public function getEditAs(): string
{
return $this->editAs;
}
public function setEditAs(string $editAs): self
{
$this->editAs = $editAs;
return $this;
}
public function validEditAs(): bool
{
return in_array($this->editAs, self::VALID_EDIT_AS, true);
}
/**
* @return null|SimpleXMLElement|string[]
*/
public function getSrcRect()
{
return $this->srcRect;
}
/**
* @param null|SimpleXMLElement|string[] $srcRect
*/
public function setSrcRect($srcRect): self
{
$this->srcRect = $srcRect;
return $this;
}
public function setFlipHorizontal(bool $flipHorizontal): self
{
$this->flipHorizontal = $flipHorizontal;
return $this;
}
public function getFlipHorizontal(): bool
{
return $this->flipHorizontal;
}
public function setFlipVertical(bool $flipVertical): self
{
$this->flipVertical = $flipVertical;
return $this;
}
public function getFlipVertical(): bool
{
return $this->flipVertical;
}
public function setOpacity(?int $opacity): self
{
$this->opacity = $opacity;
return $this;
}
public function getOpacity(): ?int
{
return $this->opacity;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/RowIterator.php | src/PhpSpreadsheet/Worksheet/RowIterator.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use Iterator as NativeIterator;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
/**
* @implements NativeIterator<int, Row>
*/
class RowIterator implements NativeIterator
{
/**
* Worksheet to iterate.
*/
private Worksheet $subject;
/**
* Current iterator position.
*/
private int $position = 1;
/**
* Start position.
*/
private int $startRow = 1;
/**
* End position.
*/
private int $endRow = 1;
/**
* Create a new row iterator.
*
* @param Worksheet $subject The worksheet to iterate over
* @param int $startRow The row number at which to start iterating
* @param ?int $endRow Optionally, the row number at which to stop iterating
*/
public function __construct(Worksheet $subject, int $startRow = 1, ?int $endRow = null)
{
// Set subject
$this->subject = $subject;
$this->resetEnd($endRow);
$this->resetStart($startRow);
}
public function __destruct()
{
unset($this->subject);
}
/**
* (Re)Set the start row and the current row pointer.
*
* @param int $startRow The row number at which to start iterating
*
* @return $this
*/
public function resetStart(int $startRow = 1): static
{
if ($startRow > $this->subject->getHighestRow()) {
throw new PhpSpreadsheetException(
"Start row ({$startRow}) is beyond highest row ({$this->subject->getHighestRow()})"
);
}
$this->startRow = $startRow;
if ($this->endRow < $this->startRow) {
$this->endRow = $this->startRow;
}
$this->seek($startRow);
return $this;
}
/**
* (Re)Set the end row.
*
* @param ?int $endRow The row number at which to stop iterating
*
* @return $this
*/
public function resetEnd(?int $endRow = null): static
{
$this->endRow = $endRow ?: $this->subject->getHighestRow();
return $this;
}
/**
* Set the row pointer to the selected row.
*
* @param int $row The row number to set the current pointer at
*
* @return $this
*/
public function seek(int $row = 1): static
{
if (($row < $this->startRow) || ($row > $this->endRow)) {
throw new PhpSpreadsheetException("Row $row is out of range ({$this->startRow} - {$this->endRow})");
}
$this->position = $row;
return $this;
}
/**
* Rewind the iterator to the starting row.
*/
public function rewind(): void
{
$this->position = $this->startRow;
}
/**
* Return the current row in this worksheet.
*/
public function current(): Row
{
return new Row($this->subject, $this->position);
}
/**
* Return the current iterator key.
*/
public function key(): int
{
return $this->position;
}
/**
* Set the iterator to its next value.
*/
public function next(): void
{
++$this->position;
}
/**
* Set the iterator to its previous value.
*/
public function prev(): void
{
--$this->position;
}
/**
* Indicate if more rows exist in the worksheet range of rows that we're iterating.
*/
public function valid(): bool
{
return $this->position <= $this->endRow && $this->position >= $this->startRow;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Protection.php | src/PhpSpreadsheet/Worksheet/Protection.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Shared\PasswordHasher;
class Protection
{
const ALGORITHM_MD2 = 'MD2';
const ALGORITHM_MD4 = 'MD4';
const ALGORITHM_MD5 = 'MD5';
const ALGORITHM_SHA_1 = 'SHA-1';
const ALGORITHM_SHA_256 = 'SHA-256';
const ALGORITHM_SHA_384 = 'SHA-384';
const ALGORITHM_SHA_512 = 'SHA-512';
const ALGORITHM_RIPEMD_128 = 'RIPEMD-128';
const ALGORITHM_RIPEMD_160 = 'RIPEMD-160';
const ALGORITHM_WHIRLPOOL = 'WHIRLPOOL';
/**
* Autofilters are locked when sheet is protected, default true.
*/
private ?bool $autoFilter = null;
/**
* Deleting columns is locked when sheet is protected, default true.
*/
private ?bool $deleteColumns = null;
/**
* Deleting rows is locked when sheet is protected, default true.
*/
private ?bool $deleteRows = null;
/**
* Formatting cells is locked when sheet is protected, default true.
*/
private ?bool $formatCells = null;
/**
* Formatting columns is locked when sheet is protected, default true.
*/
private ?bool $formatColumns = null;
/**
* Formatting rows is locked when sheet is protected, default true.
*/
private ?bool $formatRows = null;
/**
* Inserting columns is locked when sheet is protected, default true.
*/
private ?bool $insertColumns = null;
/**
* Inserting hyperlinks is locked when sheet is protected, default true.
*/
private ?bool $insertHyperlinks = null;
/**
* Inserting rows is locked when sheet is protected, default true.
*/
private ?bool $insertRows = null;
/**
* Objects are locked when sheet is protected, default false.
*/
private ?bool $objects = null;
/**
* Pivot tables are locked when the sheet is protected, default true.
*/
private ?bool $pivotTables = null;
/**
* Scenarios are locked when sheet is protected, default false.
*/
private ?bool $scenarios = null;
/**
* Selection of locked cells is locked when sheet is protected, default false.
*/
private ?bool $selectLockedCells = null;
/**
* Selection of unlocked cells is locked when sheet is protected, default false.
*/
private ?bool $selectUnlockedCells = null;
/**
* Sheet is locked when sheet is protected, default false.
*/
private ?bool $sheet = null;
/**
* Sorting is locked when sheet is protected, default true.
*/
private ?bool $sort = null;
/**
* Hashed password.
*/
private string $password = '';
/**
* Algorithm name.
*/
private string $algorithm = '';
/**
* Salt value.
*/
private string $salt = '';
/**
* Spin count.
*/
private int $spinCount = 10000;
/**
* Create a new Protection.
*/
public function __construct()
{
}
/**
* Is some sort of protection enabled?
*/
public function isProtectionEnabled(): bool
{
return
$this->password !== ''
|| isset($this->sheet)
|| isset($this->objects)
|| isset($this->scenarios)
|| isset($this->formatCells)
|| isset($this->formatColumns)
|| isset($this->formatRows)
|| isset($this->insertColumns)
|| isset($this->insertRows)
|| isset($this->insertHyperlinks)
|| isset($this->deleteColumns)
|| isset($this->deleteRows)
|| isset($this->selectLockedCells)
|| isset($this->sort)
|| isset($this->autoFilter)
|| isset($this->pivotTables)
|| isset($this->selectUnlockedCells);
}
public function getSheet(): ?bool
{
return $this->sheet;
}
public function setSheet(?bool $sheet): self
{
$this->sheet = $sheet;
return $this;
}
public function getObjects(): ?bool
{
return $this->objects;
}
public function setObjects(?bool $objects): self
{
$this->objects = $objects;
return $this;
}
public function getScenarios(): ?bool
{
return $this->scenarios;
}
public function setScenarios(?bool $scenarios): self
{
$this->scenarios = $scenarios;
return $this;
}
public function getFormatCells(): ?bool
{
return $this->formatCells;
}
public function setFormatCells(?bool $formatCells): self
{
$this->formatCells = $formatCells;
return $this;
}
public function getFormatColumns(): ?bool
{
return $this->formatColumns;
}
public function setFormatColumns(?bool $formatColumns): self
{
$this->formatColumns = $formatColumns;
return $this;
}
public function getFormatRows(): ?bool
{
return $this->formatRows;
}
public function setFormatRows(?bool $formatRows): self
{
$this->formatRows = $formatRows;
return $this;
}
public function getInsertColumns(): ?bool
{
return $this->insertColumns;
}
public function setInsertColumns(?bool $insertColumns): self
{
$this->insertColumns = $insertColumns;
return $this;
}
public function getInsertRows(): ?bool
{
return $this->insertRows;
}
public function setInsertRows(?bool $insertRows): self
{
$this->insertRows = $insertRows;
return $this;
}
public function getInsertHyperlinks(): ?bool
{
return $this->insertHyperlinks;
}
public function setInsertHyperlinks(?bool $insertHyperLinks): self
{
$this->insertHyperlinks = $insertHyperLinks;
return $this;
}
public function getDeleteColumns(): ?bool
{
return $this->deleteColumns;
}
public function setDeleteColumns(?bool $deleteColumns): self
{
$this->deleteColumns = $deleteColumns;
return $this;
}
public function getDeleteRows(): ?bool
{
return $this->deleteRows;
}
public function setDeleteRows(?bool $deleteRows): self
{
$this->deleteRows = $deleteRows;
return $this;
}
public function getSelectLockedCells(): ?bool
{
return $this->selectLockedCells;
}
public function setSelectLockedCells(?bool $selectLockedCells): self
{
$this->selectLockedCells = $selectLockedCells;
return $this;
}
public function getSort(): ?bool
{
return $this->sort;
}
public function setSort(?bool $sort): self
{
$this->sort = $sort;
return $this;
}
public function getAutoFilter(): ?bool
{
return $this->autoFilter;
}
public function setAutoFilter(?bool $autoFilter): self
{
$this->autoFilter = $autoFilter;
return $this;
}
public function getPivotTables(): ?bool
{
return $this->pivotTables;
}
public function setPivotTables(?bool $pivotTables): self
{
$this->pivotTables = $pivotTables;
return $this;
}
public function getSelectUnlockedCells(): ?bool
{
return $this->selectUnlockedCells;
}
public function setSelectUnlockedCells(?bool $selectUnlockedCells): self
{
$this->selectUnlockedCells = $selectUnlockedCells;
return $this;
}
/**
* Get hashed password.
*/
public function getPassword(): string
{
return $this->password;
}
/**
* Set Password.
*
* @param bool $alreadyHashed If the password has already been hashed, set this to true
*
* @return $this
*/
public function setPassword(string $password, bool $alreadyHashed = false): static
{
if (!$alreadyHashed) {
$salt = $this->generateSalt();
$this->setSalt($salt);
$password = PasswordHasher::hashPassword($password, $this->getAlgorithm(), $this->getSalt(), $this->getSpinCount());
}
$this->password = $password;
return $this;
}
public function setHashValue(string $password): self
{
return $this->setPassword($password, true);
}
/**
* Create a pseudorandom string.
*/
private function generateSalt(): string
{
return base64_encode(random_bytes(16));
}
/**
* Get algorithm name.
*/
public function getAlgorithm(): string
{
return $this->algorithm;
}
/**
* Set algorithm name.
*/
public function setAlgorithm(string $algorithm): self
{
return $this->setAlgorithmName($algorithm);
}
/**
* Set algorithm name.
*/
public function setAlgorithmName(string $algorithm): self
{
$this->algorithm = $algorithm;
return $this;
}
public function getSalt(): string
{
return $this->salt;
}
public function setSalt(string $salt): self
{
return $this->setSaltValue($salt);
}
public function setSaltValue(string $salt): self
{
$this->salt = $salt;
return $this;
}
/**
* Get spin count.
*/
public function getSpinCount(): int
{
return $this->spinCount;
}
/**
* Set spin count.
*/
public function setSpinCount(int $spinCount): self
{
$this->spinCount = $spinCount;
return $this;
}
/**
* Verify that the given non-hashed password can "unlock" the protection.
*/
public function verify(string $password): bool
{
if ($this->password === '') {
return true;
}
$hash = PasswordHasher::hashPassword($password, $this->getAlgorithm(), $this->getSalt(), $this->getSpinCount());
return $this->getPassword() === $hash;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/RowDimension.php | src/PhpSpreadsheet/Worksheet/RowDimension.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension;
class RowDimension extends Dimension
{
private ?int $rowIndex;
/**
* Row height (in pt).
*
* When this is set to a negative value, the row height should be ignored by IWriter
*/
private float $height = -1;
/**
* ZeroHeight for Row?
*/
private bool $zeroHeight = false;
private bool $customFormat = false;
private bool $visibleAfterFilter = true;
public function setVisibleAfterFilter(bool $visibleAfterFilter): self
{
$this->visibleAfterFilter = $visibleAfterFilter;
return $this;
}
public function getVisibleAfterFilter(): bool
{
return $this->visibleAfterFilter;
}
/**
* @param ?int $index Numeric row index
*/
public function __construct(?int $index = 0)
{
// Initialise values
$this->rowIndex = $index;
// set dimension as unformatted by default
parent::__construct(null);
}
public function getRowIndex(): ?int
{
return $this->rowIndex;
}
public function setRowIndex(int $index): static
{
$this->rowIndex = $index;
return $this;
}
/**
* Get Row Height.
* By default, this will be in points; but this method also accepts an optional unit of measure
* argument, and will convert the value from points to the specified UoM.
* A value of -1 tells Excel to display this column in its default height.
*/
public function getRowHeight(?string $unitOfMeasure = null): float
{
return ($unitOfMeasure === null || $this->height < 0)
? $this->height
: (new CssDimension($this->height . CssDimension::UOM_POINTS))->toUnit($unitOfMeasure);
}
/**
* Set Row Height.
*
* @param float $height in points. A value of -1 tells Excel to display this column in its default height.
* By default, this will be the passed argument value; but this method also accepts an optional unit of measure
* argument, and will convert the passed argument value to points from the specified UoM
*/
public function setRowHeight(float $height, ?string $unitOfMeasure = null): static
{
$this->height = ($unitOfMeasure === null || $height < 0)
? $height
: (new CssDimension("{$height}{$unitOfMeasure}"))->height();
$this->customFormat = false;
return $this;
}
public function getZeroHeight(): bool
{
return $this->zeroHeight;
}
public function setZeroHeight(bool $zeroHeight): static
{
$this->zeroHeight = $zeroHeight;
return $this;
}
public function getCustomFormat(): bool
{
return $this->customFormat;
}
public function setCustomFormat(bool $customFormat, ?float $height = -1): self
{
$this->customFormat = $customFormat;
if ($height !== null) {
$this->height = $height;
}
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/ColumnDimension.php | src/PhpSpreadsheet/Worksheet/ColumnDimension.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension;
class ColumnDimension extends Dimension
{
public const EXCEL_MAX_WIDTH = 255.0;
/**
* Column index.
*/
private ?string $columnIndex;
/**
* Column width.
*
* When this is set to a negative value, the column width should be ignored by IWriter
*/
private float $width = -1;
/**
* Auto size?
*/
private bool $autoSize = false;
/**
* Create a new ColumnDimension.
*
* @param ?string $index Character column index
*/
public function __construct(?string $index = 'A')
{
// Initialise values
$this->columnIndex = $index;
// set dimension as unformatted by default
parent::__construct(0);
}
/**
* Get column index as string eg: 'A'.
*/
public function getColumnIndex(): ?string
{
return $this->columnIndex;
}
/**
* Set column index as string eg: 'A'.
*/
public function setColumnIndex(string $index): self
{
$this->columnIndex = $index;
return $this;
}
/**
* Get column index as numeric.
*/
public function getColumnNumeric(): int
{
return Coordinate::columnIndexFromString($this->columnIndex ?? '');
}
/**
* Set column index as numeric.
*/
public function setColumnNumeric(int $index): self
{
$this->columnIndex = Coordinate::stringFromColumnIndex($index);
return $this;
}
/**
* Get Width.
*
* Each unit of column width is equal to the width of one character in the default font size. A value of -1
* tells Excel to display this column in its default width.
* By default, this will be the return value; but this method also accepts an optional unit of measure argument
* and will convert the returned value to the specified UoM..
*/
public function getWidth(?string $unitOfMeasure = null): float
{
return ($unitOfMeasure === null || $this->width < 0)
? $this->width
: (new CssDimension((string) $this->width))->toUnit($unitOfMeasure);
}
public function getWidthForOutput(bool $restrictMax): float
{
return ($restrictMax && $this->width > self::EXCEL_MAX_WIDTH) ? self::EXCEL_MAX_WIDTH : $this->width;
}
/**
* Set Width.
*
* Each unit of column width is equal to the width of one character in the default font size. A value of -1
* tells Excel to display this column in its default width.
* By default, this will be the unit of measure for the passed value; but this method also accepts an
* optional unit of measure argument, and will convert the value from the specified UoM using an
* approximation method.
*
* @return $this
*/
public function setWidth(float $width, ?string $unitOfMeasure = null): static
{
$this->width = ($unitOfMeasure === null || $width < 0)
? $width
: (new CssDimension("{$width}{$unitOfMeasure}"))->width();
return $this;
}
/**
* Get Auto Size.
*/
public function getAutoSize(): bool
{
return $this->autoSize;
}
/**
* Set Auto Size.
*
* @return $this
*/
public function setAutoSize(bool $autosizeEnabled): static
{
$this->autoSize = $autosizeEnabled;
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/AutoFilter.php | src/PhpSpreadsheet/Worksheet/AutoFilter.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use DateTime;
use DateTimeZone;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Calculation\Internal\WildcardMatch;
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
use PhpOffice\PhpSpreadsheet\Cell\CellRange;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule;
use Stringable;
use Throwable;
class AutoFilter implements Stringable
{
/**
* Autofilter Worksheet.
*/
private ?Worksheet $workSheet;
/**
* Autofilter Range.
*/
private string $range;
/**
* Autofilter Column Ruleset.
*
* @var AutoFilter\Column[]
*/
private array $columns = [];
private bool $evaluated = false;
public function getEvaluated(): bool
{
return $this->evaluated;
}
public function setEvaluated(bool $value): void
{
$this->evaluated = $value;
}
/**
* Create a new AutoFilter.
*
* @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range
* A simple string containing a Cell range like 'A1:E10' is permitted
* or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
* or an AddressRange object.
*/
public function __construct(AddressRange|string|array $range = '', ?Worksheet $worksheet = null)
{
if ($range !== '') {
[, $range] = Worksheet::extractSheetTitle(Validations::validateCellRange($range), true);
}
$this->range = $range ?? '';
$this->workSheet = $worksheet;
}
public function __destruct()
{
$this->workSheet = null;
}
/**
* Get AutoFilter Parent Worksheet.
*/
public function getParent(): null|Worksheet
{
return $this->workSheet;
}
/**
* Set AutoFilter Parent Worksheet.
*
* @return $this
*/
public function setParent(?Worksheet $worksheet = null): static
{
$this->evaluated = false;
$this->workSheet = $worksheet;
return $this;
}
/**
* Get AutoFilter Range.
*/
public function getRange(): string
{
return $this->range;
}
/**
* Set AutoFilter Cell Range.
*
* @param AddressRange<CellRange>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $range
* A simple string containing a Cell range like 'A1:E10' or a Cell address like 'A1' is permitted
* or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
* or an AddressRange object.
*/
public function setRange(AddressRange|string|array $range = ''): self
{
$this->evaluated = false;
// extract coordinate
if ($range !== '') {
[, $range] = Worksheet::extractSheetTitle(Validations::validateCellRange($range), true);
}
if (empty($range)) {
// Discard all column rules
$this->columns = [];
$this->range = '';
return $this;
}
if (ctype_digit($range) || ctype_alpha($range)) {
throw new Exception("{$range} is an invalid range for AutoFilter");
}
$this->range = $range;
// Discard any column rules that are no longer valid within this range
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range);
foreach ($this->columns as $key => $value) {
$colIndex = Coordinate::columnIndexFromString($key);
if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) {
unset($this->columns[$key]);
}
}
return $this;
}
public function setRangeToMaxRow(): self
{
$this->evaluated = false;
if ($this->workSheet !== null) {
$thisrange = $this->range;
$range = (string) preg_replace('/\d+$/', (string) $this->workSheet->getHighestRow(), $thisrange);
if ($range !== $thisrange) {
$this->setRange($range);
}
}
return $this;
}
/**
* Get all AutoFilter Columns.
*
* @return AutoFilter\Column[]
*/
public function getColumns(): array
{
return $this->columns;
}
/**
* Validate that the specified column is in the AutoFilter range.
*
* @param string $column Column name (e.g. A)
*
* @return int The column offset within the autofilter range
*/
public function testColumnInRange(string $column): int
{
if (empty($this->range)) {
throw new Exception('No autofilter range is defined.');
}
$columnIndex = Coordinate::columnIndexFromString($column);
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range);
if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) {
throw new Exception('Column is outside of current autofilter range.');
}
return $columnIndex - $rangeStart[0];
}
/**
* Get a specified AutoFilter Column Offset within the defined AutoFilter range.
*
* @param string $column Column name (e.g. A)
*
* @return int The offset of the specified column within the autofilter range
*/
public function getColumnOffset(string $column): int
{
return $this->testColumnInRange($column);
}
/**
* Get a specified AutoFilter Column.
*
* @param string $column Column name (e.g. A)
*/
public function getColumn(string $column): AutoFilter\Column
{
$this->testColumnInRange($column);
if (!isset($this->columns[$column])) {
$this->columns[$column] = new AutoFilter\Column($column, $this);
}
return $this->columns[$column];
}
/**
* Get a specified AutoFilter Column by its offset.
*
* @param int $columnOffset Column offset within range (starting from 0)
*/
public function getColumnByOffset(int $columnOffset): AutoFilter\Column
{
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range);
$pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $columnOffset);
return $this->getColumn($pColumn);
}
/**
* Set AutoFilter.
*
* @param AutoFilter\Column|string $columnObjectOrString
* A simple string containing a Column ID like 'A' is permitted
*
* @return $this
*/
public function setColumn(AutoFilter\Column|string $columnObjectOrString): static
{
$this->evaluated = false;
if ((is_string($columnObjectOrString)) && (!empty($columnObjectOrString))) {
$column = $columnObjectOrString;
} elseif ($columnObjectOrString instanceof AutoFilter\Column) {
$column = $columnObjectOrString->getColumnIndex();
} else {
throw new Exception('Column is not within the autofilter range.');
}
$this->testColumnInRange($column);
if (is_string($columnObjectOrString)) {
$this->columns[$columnObjectOrString] = new AutoFilter\Column($columnObjectOrString, $this);
} else {
$columnObjectOrString->setParent($this);
$this->columns[$column] = $columnObjectOrString;
}
ksort($this->columns);
return $this;
}
/**
* Clear a specified AutoFilter Column.
*
* @param string $column Column name (e.g. A)
*
* @return $this
*/
public function clearColumn(string $column): static
{
$this->evaluated = false;
$this->testColumnInRange($column);
if (isset($this->columns[$column])) {
unset($this->columns[$column]);
}
return $this;
}
/**
* Shift an AutoFilter Column Rule to a different column.
*
* Note: This method bypasses validation of the destination column to ensure it is within this AutoFilter range.
* Nor does it verify whether any column rule already exists at $toColumn, but will simply override any existing value.
* Use with caution.
*
* @param string $fromColumn Column name (e.g. A)
* @param string $toColumn Column name (e.g. B)
*
* @return $this
*/
public function shiftColumn(string $fromColumn, string $toColumn): static
{
$this->evaluated = false;
$fromColumn = strtoupper($fromColumn);
$toColumn = strtoupper($toColumn);
if (isset($this->columns[$fromColumn])) {
$this->columns[$fromColumn]->setParent();
$this->columns[$fromColumn]->setColumnIndex($toColumn);
$this->columns[$toColumn] = $this->columns[$fromColumn];
$this->columns[$toColumn]->setParent($this);
unset($this->columns[$fromColumn]);
ksort($this->columns);
}
return $this;
}
/**
* Test if cell value is in the defined set of values.
*
* @param array{blanks: bool, filterValues: array<string,array<string,string>>} $dataSet
*/
protected static function filterTestInSimpleDataSet(mixed $cellValue, array $dataSet): bool
{
$dataSetValues = $dataSet['filterValues'];
$blanks = $dataSet['blanks'];
if (($cellValue === '') || ($cellValue === null)) {
return $blanks;
}
return in_array($cellValue, $dataSetValues);
}
/**
* Test if cell value is in the defined set of Excel date values.
*
* @param array{blanks: bool, filterValues: array<string,array<string,string>>} $dataSet
*/
protected static function filterTestInDateGroupSet(mixed $cellValue, array $dataSet): bool
{
$dateSet = $dataSet['filterValues'];
$blanks = $dataSet['blanks'];
if (($cellValue === '') || ($cellValue === null)) {
return $blanks;
}
$timeZone = new DateTimeZone('UTC');
if (is_numeric($cellValue)) {
try {
$dateTime = Date::excelToDateTimeObject((float) $cellValue, $timeZone);
} catch (Throwable) {
return false;
}
$cellValue = (float) $cellValue;
if ($cellValue < 1) {
// Just the time part
$dtVal = $dateTime->format('His');
$dateSet = $dateSet['time'];
} elseif ($cellValue == floor($cellValue)) {
// Just the date part
$dtVal = $dateTime->format('Ymd');
$dateSet = $dateSet['date'];
} else {
// date and time parts
$dtVal = $dateTime->format('YmdHis');
$dateSet = $dateSet['dateTime'];
}
foreach ($dateSet as $dateValue) {
// Use of substr to extract value at the appropriate group level
if (str_starts_with($dtVal, $dateValue)) {
return true;
}
}
}
return false;
}
/**
* Test if cell value is within a set of values defined by a ruleset.
*
* @param mixed[][] $ruleSet
*/
protected static function filterTestInCustomDataSet(mixed $cellValue, array $ruleSet): bool
{
$dataSet = $ruleSet['filterRules'];
$join = $ruleSet['join'];
$customRuleForBlanks = $ruleSet['customRuleForBlanks'] ?? false;
if (!$customRuleForBlanks) {
// Blank cells are always ignored, so return a FALSE
if (($cellValue === '') || ($cellValue === null)) {
return false;
}
}
$returnVal = ($join == AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND);
foreach ($dataSet as $rule) {
/** @var string[] $rule */
$ruleValue = $rule['value'];
$ruleOperator = $rule['operator'];
/** @var string */
$cellValueString = $cellValue ?? '';
$retVal = false;
if (is_numeric($ruleValue)) {
// Numeric values are tested using the appropriate operator
$numericTest = is_numeric($cellValue);
switch ($ruleOperator) {
case Rule::AUTOFILTER_COLUMN_RULE_EQUAL:
$retVal = $numericTest && ($cellValue == $ruleValue);
break;
case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL:
$retVal = !$numericTest || ($cellValue != $ruleValue);
break;
case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN:
$retVal = $numericTest && ($cellValue > $ruleValue);
break;
case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL:
$retVal = $numericTest && ($cellValue >= $ruleValue);
break;
case Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN:
$retVal = $numericTest && ($cellValue < $ruleValue);
break;
case Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL:
$retVal = $numericTest && ($cellValue <= $ruleValue);
break;
}
} elseif ($ruleValue == '') {
$retVal = match ($ruleOperator) {
Rule::AUTOFILTER_COLUMN_RULE_EQUAL => ($cellValue === '') || ($cellValue === null),
Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL => ($cellValue != ''),
default => true,
};
} else {
// String values are always tested for equality, factoring in for wildcards (hence a regexp test)
switch ($ruleOperator) {
case Rule::AUTOFILTER_COLUMN_RULE_EQUAL:
$retVal = (bool) preg_match('/^' . $ruleValue . '$/i', $cellValueString);
break;
case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL:
$retVal = !((bool) preg_match('/^' . $ruleValue . '$/i', $cellValueString));
break;
case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN:
$retVal = strcasecmp($cellValueString, $ruleValue) > 0;
break;
case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL:
$retVal = strcasecmp($cellValueString, $ruleValue) >= 0;
break;
case Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN:
$retVal = strcasecmp($cellValueString, $ruleValue) < 0;
break;
case Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL:
$retVal = strcasecmp($cellValueString, $ruleValue) <= 0;
break;
}
}
// If there are multiple conditions, then we need to test both using the appropriate join operator
switch ($join) {
case AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_OR:
$returnVal = $returnVal || $retVal;
// Break as soon as we have a TRUE match for OR joins,
// to avoid unnecessary additional code execution
if ($returnVal) {
return $returnVal;
}
break;
case AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND:
$returnVal = $returnVal && $retVal;
break;
}
}
return $returnVal;
}
/**
* Test if cell date value is matches a set of values defined by a set of months.
*
* @param mixed[] $monthSet
*/
protected static function filterTestInPeriodDateSet(mixed $cellValue, array $monthSet): bool
{
// Blank cells are always ignored, so return a FALSE
if (($cellValue === '') || ($cellValue === null)) {
return false;
}
if (is_numeric($cellValue)) {
try {
$dateObject = Date::excelToDateTimeObject((float) $cellValue, new DateTimeZone('UTC'));
} catch (Throwable) {
return false;
}
$dateValue = (int) $dateObject->format('m');
if (in_array($dateValue, $monthSet)) {
return true;
}
}
return false;
}
private static function makeDateObject(int $year, int $month, int $day, int $hour = 0, int $minute = 0, int $second = 0): DateTime
{
$baseDate = new DateTime();
$baseDate->setDate($year, $month, $day);
$baseDate->setTime($hour, $minute, $second);
return $baseDate;
}
private const DATE_FUNCTIONS = [
Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH => 'dynamicLastMonth',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER => 'dynamicLastQuarter',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK => 'dynamicLastWeek',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR => 'dynamicLastYear',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH => 'dynamicNextMonth',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER => 'dynamicNextQuarter',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK => 'dynamicNextWeek',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR => 'dynamicNextYear',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH => 'dynamicThisMonth',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER => 'dynamicThisQuarter',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK => 'dynamicThisWeek',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR => 'dynamicThisYear',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY => 'dynamicToday',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW => 'dynamicTomorrow',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE => 'dynamicYearToDate',
Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY => 'dynamicYesterday',
];
/** @return array{DateTime, DateTime} */
private static function dynamicLastMonth(): array
{
$maxval = new DateTime();
$year = (int) $maxval->format('Y');
$month = (int) $maxval->format('m');
$maxval->setDate($year, $month, 1);
$maxval->setTime(0, 0, 0);
$val = clone $maxval;
$val->modify('-1 month');
return [$val, $maxval];
}
private static function firstDayOfQuarter(): DateTime
{
$val = new DateTime();
$year = (int) $val->format('Y');
$month = (int) $val->format('m');
$month = 3 * intdiv($month - 1, 3) + 1;
$val->setDate($year, $month, 1);
$val->setTime(0, 0, 0);
return $val;
}
/** @return array{DateTime, DateTime} */
private static function dynamicLastQuarter(): array
{
$maxval = self::firstDayOfQuarter();
$val = clone $maxval;
$val->modify('-3 months');
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicLastWeek(): array
{
$val = new DateTime();
$val->setTime(0, 0, 0);
$dayOfWeek = (int) $val->format('w'); // Sunday is 0
$subtract = $dayOfWeek + 7; // revert to prior Sunday
$val->modify("-$subtract days");
$maxval = clone $val;
$maxval->modify('+7 days');
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicLastYear(): array
{
$val = new DateTime();
$year = (int) $val->format('Y');
$val = self::makeDateObject($year - 1, 1, 1);
$maxval = self::makeDateObject($year, 1, 1);
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicNextMonth(): array
{
$val = new DateTime();
$year = (int) $val->format('Y');
$month = (int) $val->format('m');
$val->setDate($year, $month, 1);
$val->setTime(0, 0, 0);
$val->modify('+1 month');
$maxval = clone $val;
$maxval->modify('+1 month');
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicNextQuarter(): array
{
$val = self::firstDayOfQuarter();
$val->modify('+3 months');
$maxval = clone $val;
$maxval->modify('+3 months');
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicNextWeek(): array
{
$val = new DateTime();
$val->setTime(0, 0, 0);
$dayOfWeek = (int) $val->format('w'); // Sunday is 0
$add = 7 - $dayOfWeek; // move to next Sunday
$val->modify("+$add days");
$maxval = clone $val;
$maxval->modify('+7 days');
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicNextYear(): array
{
$val = new DateTime();
$year = (int) $val->format('Y');
$val = self::makeDateObject($year + 1, 1, 1);
$maxval = self::makeDateObject($year + 2, 1, 1);
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicThisMonth(): array
{
$baseDate = new DateTime();
$baseDate->setTime(0, 0, 0);
$year = (int) $baseDate->format('Y');
$month = (int) $baseDate->format('m');
$val = self::makeDateObject($year, $month, 1);
$maxval = clone $val;
$maxval->modify('+1 month');
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicThisQuarter(): array
{
$val = self::firstDayOfQuarter();
$maxval = clone $val;
$maxval->modify('+3 months');
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicThisWeek(): array
{
$val = new DateTime();
$val->setTime(0, 0, 0);
$dayOfWeek = (int) $val->format('w'); // Sunday is 0
$subtract = $dayOfWeek; // revert to Sunday
$val->modify("-$subtract days");
$maxval = clone $val;
$maxval->modify('+7 days');
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicThisYear(): array
{
$val = new DateTime();
$year = (int) $val->format('Y');
$val = self::makeDateObject($year, 1, 1);
$maxval = self::makeDateObject($year + 1, 1, 1);
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicToday(): array
{
$val = new DateTime();
$val->setTime(0, 0, 0);
$maxval = clone $val;
$maxval->modify('+1 day');
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicTomorrow(): array
{
$val = new DateTime();
$val->setTime(0, 0, 0);
$val->modify('+1 day');
$maxval = clone $val;
$maxval->modify('+1 day');
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicYearToDate(): array
{
$maxval = new DateTime();
$maxval->setTime(0, 0, 0);
$val = self::makeDateObject((int) $maxval->format('Y'), 1, 1);
$maxval->modify('+1 day');
return [$val, $maxval];
}
/** @return array{DateTime, DateTime} */
private static function dynamicYesterday(): array
{
$maxval = new DateTime();
$maxval->setTime(0, 0, 0);
$val = clone $maxval;
$val->modify('-1 day');
return [$val, $maxval];
}
/**
* Convert a dynamic rule daterange to a custom filter range expression for ease of calculation.
*
* @return mixed[]
*/
private function dynamicFilterDateRange(string $dynamicRuleType, AutoFilter\Column &$filterColumn): array
{
$ruleValues = [];
$callBack = [__CLASS__, self::DATE_FUNCTIONS[$dynamicRuleType]]; // What if not found?
// Calculate start/end dates for the required date range based on current date
// Val is lowest permitted value.
// Maxval is greater than highest permitted value
$val = $maxval = 0;
if (is_callable($callBack)) { //* @phpstan-ignore-line
[$val, $maxval] = $callBack();
}
$val = Date::dateTimeToExcel($val);
$maxval = Date::dateTimeToExcel($maxval);
// Set the filter column rule attributes ready for writing
$filterColumn->setAttributes(['val' => $val, 'maxVal' => $maxval]);
// Set the rules for identifying rows for hide/show
$ruleValues[] = ['operator' => Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val];
$ruleValues[] = ['operator' => Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxval];
return ['method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND]];
}
/**
* Apply the AutoFilter rules to the AutoFilter Range.
*/
private function calculateTopTenValue(string $columnID, int $startRow, int $endRow, ?string $ruleType, mixed $ruleValue): mixed
{
$range = $columnID . $startRow . ':' . $columnID . $endRow;
$retVal = null;
if ($this->workSheet !== null) {
$dataValues = Functions::flattenArray($this->workSheet->rangeToArray($range, null, true, false));
$dataValues = array_filter($dataValues);
if ($ruleType == Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) {
rsort($dataValues);
} else {
sort($dataValues);
}
if (is_numeric($ruleValue)) {
$ruleValue = (int) $ruleValue;
}
if ($ruleValue === null || is_int($ruleValue)) {
$slice = array_slice($dataValues, 0, $ruleValue);
$retVal = array_pop($slice);
}
}
return $retVal;
}
/**
* Apply the AutoFilter rules to the AutoFilter Range.
*
* @return $this
*/
public function showHideRows(): static
{
if ($this->workSheet === null) {
return $this;
}
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range);
// The heading row should always be visible
$this->workSheet->getRowDimension($rangeStart[1])->setVisible(true);
$columnFilterTests = [];
foreach ($this->columns as $columnID => $filterColumn) {
$rules = $filterColumn->getRules();
switch ($filterColumn->getFilterType()) {
case AutoFilter\Column::AUTOFILTER_FILTERTYPE_FILTER:
$ruleType = null;
$ruleValues = [];
// Build a list of the filter value selections
foreach ($rules as $rule) {
$ruleType = $rule->getRuleType();
$ruleValues[] = $rule->getValue();
}
// Test if we want to include blanks in our filter criteria
$blanks = false;
$ruleDataSet = array_filter($ruleValues);
if (count($ruleValues) != count($ruleDataSet)) {
$blanks = true;
}
if ($ruleType == Rule::AUTOFILTER_RULETYPE_FILTER) {
// Filter on absolute values
$columnFilterTests[$columnID] = [
'method' => 'filterTestInSimpleDataSet',
'arguments' => ['filterValues' => $ruleDataSet, 'blanks' => $blanks],
];
} elseif ($ruleType !== null) {
// Filter on date group values
$arguments = [
'date' => [],
'time' => [],
'dateTime' => [],
];
foreach ($ruleDataSet as $ruleValue) {
if (!is_array($ruleValue)) {
continue;
}
$date = $time = '';
if (
(isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]))
&& ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== '')
) {
$date .= sprintf('%04d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]);
}
if (
(isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]))
&& ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != '')
) {
$date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]);
}
if (
(isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]))
&& ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== '')
) {
$date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]);
}
if (
(isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]))
&& ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== '')
) {
$time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]);
}
if (
(isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]))
&& ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== '')
) {
$time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]);
}
if (
(isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]))
&& ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== '')
) {
$time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]);
}
$dateTime = $date . $time;
$arguments['date'][] = $date;
$arguments['time'][] = $time;
$arguments['dateTime'][] = $dateTime;
}
// Remove empty elements
$arguments['date'] = array_filter($arguments['date']);
$arguments['time'] = array_filter($arguments['time']);
$arguments['dateTime'] = array_filter($arguments['dateTime']);
$columnFilterTests[$columnID] = [
'method' => 'filterTestInDateGroupSet',
'arguments' => ['filterValues' => $arguments, 'blanks' => $blanks],
];
}
break;
case AutoFilter\Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER:
$customRuleForBlanks = true;
$ruleValues = [];
// Build a list of the filter value selections
foreach ($rules as $rule) {
$ruleValue = $rule->getValue();
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | true |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/SheetView.php | src/PhpSpreadsheet/Worksheet/SheetView.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
class SheetView
{
// Sheet View types
const SHEETVIEW_NORMAL = 'normal';
const SHEETVIEW_PAGE_LAYOUT = 'pageLayout';
const SHEETVIEW_PAGE_BREAK_PREVIEW = 'pageBreakPreview';
private const SHEET_VIEW_TYPES = [
self::SHEETVIEW_NORMAL,
self::SHEETVIEW_PAGE_LAYOUT,
self::SHEETVIEW_PAGE_BREAK_PREVIEW,
];
/**
* ZoomScale.
*
* Valid values range from 10 to 400.
*/
private ?int $zoomScale = 100;
/**
* ZoomScaleNormal.
*
* Valid values range from 10 to 400.
*/
private ?int $zoomScaleNormal = 100;
/**
* ZoomScalePageLayoutView.
*
* Valid values range from 10 to 400.
*/
private int $zoomScalePageLayoutView = 100;
/**
* ZoomScaleSheetLayoutView.
*
* Valid values range from 10 to 400.
*/
private int $zoomScaleSheetLayoutView = 100;
/**
* ShowZeros.
*
* If true, "null" values from a calculation will be shown as "0". This is the default Excel behaviour and can be changed
* with the advanced worksheet option "Show a zero in cells that have zero value"
*/
private bool $showZeros = true;
/**
* View.
*
* Valid values range from 10 to 400.
*/
private string $sheetviewType = self::SHEETVIEW_NORMAL;
/**
* Create a new SheetView.
*/
public function __construct()
{
}
/**
* Get ZoomScale.
*/
public function getZoomScale(): ?int
{
return $this->zoomScale;
}
/**
* Set ZoomScale.
* Valid values range from 10 to 400.
*
* @return $this
*/
public function setZoomScale(?int $zoomScale): static
{
// Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface,
// but it is apparently still able to handle any scale >= 1
if ($zoomScale === null || $zoomScale >= 1) {
$this->zoomScale = $zoomScale;
} else {
throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.');
}
return $this;
}
/**
* Get ZoomScaleNormal.
*/
public function getZoomScaleNormal(): ?int
{
return $this->zoomScaleNormal;
}
/**
* Set ZoomScale.
* Valid values range from 10 to 400.
*
* @return $this
*/
public function setZoomScaleNormal(?int $zoomScaleNormal): static
{
if ($zoomScaleNormal === null || $zoomScaleNormal >= 1) {
$this->zoomScaleNormal = $zoomScaleNormal;
} else {
throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.');
}
return $this;
}
public function getZoomScalePageLayoutView(): int
{
return $this->zoomScalePageLayoutView;
}
public function setZoomScalePageLayoutView(int $zoomScalePageLayoutView): static
{
if ($zoomScalePageLayoutView >= 1) {
$this->zoomScalePageLayoutView = $zoomScalePageLayoutView;
} else {
throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.');
}
return $this;
}
public function getZoomScaleSheetLayoutView(): int
{
return $this->zoomScaleSheetLayoutView;
}
public function setZoomScaleSheetLayoutView(int $zoomScaleSheetLayoutView): static
{
if ($zoomScaleSheetLayoutView >= 1) {
$this->zoomScaleSheetLayoutView = $zoomScaleSheetLayoutView;
} else {
throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.');
}
return $this;
}
/**
* Set ShowZeroes setting.
*/
public function setShowZeros(bool $showZeros): void
{
$this->showZeros = $showZeros;
}
public function getShowZeros(): bool
{
return $this->showZeros;
}
/**
* Get View.
*/
public function getView(): string
{
return $this->sheetviewType;
}
/**
* Set View.
*
* Valid values are
* 'normal' self::SHEETVIEW_NORMAL
* 'pageLayout' self::SHEETVIEW_PAGE_LAYOUT
* 'pageBreakPreview' self::SHEETVIEW_PAGE_BREAK_PREVIEW
*
* @return $this
*/
public function setView(?string $sheetViewType): static
{
// MS Excel 2007 allows setting the view to 'normal', 'pageLayout' or 'pageBreakPreview' via the user interface
if ($sheetViewType === null) {
$sheetViewType = self::SHEETVIEW_NORMAL;
}
if (in_array($sheetViewType, self::SHEET_VIEW_TYPES)) {
$this->sheetviewType = $sheetViewType;
} else {
throw new PhpSpreadsheetException('Invalid sheetview layout type.');
}
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Pane.php | src/PhpSpreadsheet/Worksheet/Pane.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
class Pane
{
private string $sqref;
private string $activeCell;
private string $position;
public function __construct(string $position, string $sqref = '', string $activeCell = '')
{
$this->sqref = $sqref;
$this->activeCell = $activeCell;
$this->position = $position;
}
public function getPosition(): string
{
return $this->position;
}
public function getSqref(): string
{
return $this->sqref;
}
public function setSqref(string $sqref): self
{
$this->sqref = $sqref;
return $this;
}
public function getActiveCell(): string
{
return $this->activeCell;
}
public function setActiveCell(string $activeCell): self
{
$this->activeCell = $activeCell;
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Iterator.php | src/PhpSpreadsheet/Worksheet/Iterator.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
/**
* @implements \Iterator<int, Worksheet>
*/
class Iterator implements \Iterator
{
/**
* Spreadsheet to iterate.
*/
private Spreadsheet $subject;
/**
* Current iterator position.
*/
private int $position = 0;
/**
* Create a new worksheet iterator.
*/
public function __construct(Spreadsheet $subject)
{
// Set subject
$this->subject = $subject;
}
/**
* Rewind iterator.
*/
public function rewind(): void
{
$this->position = 0;
}
/**
* Current Worksheet.
*/
public function current(): Worksheet
{
return $this->subject->getSheet($this->position);
}
/**
* Current key.
*/
public function key(): int
{
return $this->position;
}
/**
* Next value.
*/
public function next(): void
{
++$this->position;
}
/**
* Are there more Worksheet instances available?
*/
public function valid(): bool
{
return $this->position < $this->subject->getSheetCount() && $this->position >= 0;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/HeaderFooterDrawing.php | src/PhpSpreadsheet/Worksheet/HeaderFooterDrawing.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
class HeaderFooterDrawing extends Drawing
{
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
return md5(
$this->getPath()
. $this->name
. $this->offsetX
. $this->offsetY
. $this->width
. $this->height
. __CLASS__
);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Column.php | src/PhpSpreadsheet/Worksheet/Column.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
class Column
{
private Worksheet $worksheet;
/**
* Column index.
*/
private string $columnIndex;
/**
* Create a new column.
*/
public function __construct(Worksheet $worksheet, string $columnIndex = 'A')
{
// Set parent and column index
$this->worksheet = $worksheet;
$this->columnIndex = $columnIndex;
}
/**
* Destructor.
*/
public function __destruct()
{
unset($this->worksheet);
}
/**
* Get column index as string eg: 'A'.
*/
public function getColumnIndex(): string
{
return $this->columnIndex;
}
/**
* Get cell iterator.
*
* @param int $startRow The row number at which to start iterating
* @param ?int $endRow Optionally, the row number at which to stop iterating
*/
public function getCellIterator(int $startRow = 1, ?int $endRow = null, bool $iterateOnlyExistingCells = false): ColumnCellIterator
{
return new ColumnCellIterator($this->worksheet, $this->columnIndex, $startRow, $endRow, $iterateOnlyExistingCells);
}
/**
* Get row iterator. Synonym for getCellIterator().
*
* @param int $startRow The row number at which to start iterating
* @param ?int $endRow Optionally, the row number at which to stop iterating
*/
public function getRowIterator(int $startRow = 1, ?int $endRow = null, bool $iterateOnlyExistingCells = false): ColumnCellIterator
{
return $this->getCellIterator($startRow, $endRow, $iterateOnlyExistingCells);
}
/**
* Returns a boolean true if the column contains no cells. By default, this means that no cell records exist in the
* collection for this column. false will be returned otherwise.
* This rule can be modified by passing a $definitionOfEmptyFlags value:
* 1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value
* cells, then the column will be considered empty.
* 2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty
* string value cells, then the column will be considered empty.
* 3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
* If the only cells in the collection are null value or empty string value cells, then the column
* will be considered empty.
*
* @param int $definitionOfEmptyFlags
* Possible Flag Values are:
* CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL
* CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL
* @param int $startRow The row number at which to start checking if cells are empty
* @param ?int $endRow Optionally, the row number at which to stop checking if cells are empty
*/
public function isEmpty(int $definitionOfEmptyFlags = 0, int $startRow = 1, ?int $endRow = null): bool
{
$nullValueCellIsEmpty = (bool) ($definitionOfEmptyFlags & CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL);
$emptyStringCellIsEmpty = (bool) ($definitionOfEmptyFlags & CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL);
$cellIterator = $this->getCellIterator($startRow, $endRow);
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $cell) {
$value = $cell->getValue();
if ($value === null && $nullValueCellIsEmpty === true) {
continue;
}
if ($value === '' && $emptyStringCellIsEmpty === true) {
continue;
}
return false;
}
return true;
}
/**
* Returns bound worksheet.
*/
public function getWorksheet(): Worksheet
{
return $this->worksheet;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/AutoFit.php | src/PhpSpreadsheet/Worksheet/AutoFit.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
use PhpOffice\PhpSpreadsheet\Cell\CellRange;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
class AutoFit
{
protected Worksheet $worksheet;
public function __construct(Worksheet $worksheet)
{
$this->worksheet = $worksheet;
}
/** @return mixed[] */
public function getAutoFilterIndentRanges(): array
{
$autoFilterIndentRanges = [];
$autoFilterIndentRanges[] = $this->getAutoFilterIndentRange($this->worksheet->getAutoFilter());
foreach ($this->worksheet->getTableCollection() as $table) {
if ($table->getShowHeaderRow() === true && $table->getAllowFilter() === true) {
$autoFilter = $table->getAutoFilter();
$autoFilterIndentRanges[] = $this->getAutoFilterIndentRange($autoFilter);
}
}
return array_filter($autoFilterIndentRanges);
}
private function getAutoFilterIndentRange(AutoFilter $autoFilter): ?string
{
$autoFilterRange = $autoFilter->getRange();
$autoFilterIndentRange = null;
if (!empty($autoFilterRange)) {
$autoFilterRangeBoundaries = Coordinate::rangeBoundaries($autoFilterRange);
$autoFilterIndentRange = (string) new CellRange(
CellAddress::fromColumnAndRow($autoFilterRangeBoundaries[0][0], $autoFilterRangeBoundaries[0][1]),
CellAddress::fromColumnAndRow($autoFilterRangeBoundaries[1][0], $autoFilterRangeBoundaries[0][1])
);
}
return $autoFilterIndentRange;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/HeaderFooter.php | src/PhpSpreadsheet/Worksheet/HeaderFooter.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
/**
* <code>
* Header/Footer Formatting Syntax taken from Office Open XML Part 4 - Markup Language Reference, page 1970:.
*
* There are a number of formatting codes that can be written inline with the actual header / footer text, which
* affect the formatting in the header or footer.
*
* Example: This example shows the text "Center Bold Header" on the first line (center section), and the date on
* the second line (center section).
* &CCenter &"-,Bold"Bold&"-,Regular"Header_x000A_&D
*
* General Rules:
* There is no required order in which these codes must appear.
*
* The first occurrence of the following codes turns the formatting ON, the second occurrence turns it OFF again:
* - strikethrough
* - superscript
* - subscript
* Superscript and subscript cannot both be ON at same time. Whichever comes first wins and the other is ignored,
* while the first is ON.
* &L - code for "left section" (there are three header / footer locations, "left", "center", and "right"). When
* two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the
* order of appearance, and placed into the left section.
* &P - code for "current page #"
* &N - code for "total pages"
* &font size - code for "text font size", where font size is a font size in points.
* &K - code for "text font color"
* RGB Color is specified as RRGGBB
* Theme Color is specified as TTSNN where TT is the theme color Id, S is either "+" or "-" of the tint/shade
* value, NN is the tint/shade value.
* &S - code for "text strikethrough" on / off
* &X - code for "text super script" on / off
* &Y - code for "text subscript" on / off
* &C - code for "center section". When two or more occurrences of this section marker exist, the contents
* from all markers are concatenated, in the order of appearance, and placed into the center section.
*
* &D - code for "date"
* &T - code for "time"
* &G - code for "picture as background"
* &U - code for "text single underline"
* &E - code for "double underline"
* &R - code for "right section". When two or more occurrences of this section marker exist, the contents
* from all markers are concatenated, in the order of appearance, and placed into the right section.
* &Z - code for "this workbook's file path"
* &F - code for "this workbook's file name"
* &A - code for "sheet tab name"
* &+ - code for add to page #.
* &- - code for subtract from page #.
* &"font name,font type" - code for "text font name" and "text font type", where font name and font type
* are strings specifying the name and type of the font, separated by a comma. When a hyphen appears in font
* name, it means "none specified". Both of font name and font type can be localized values.
* &"-,Bold" - code for "bold font style"
* &B - also means "bold font style".
* &"-,Regular" - code for "regular font style"
* &"-,Italic" - code for "italic font style"
* &I - also means "italic font style"
* &"-,Bold Italic" code for "bold italic font style"
* &O - code for "outline style"
* &H - code for "shadow style"
* </code>
*/
class HeaderFooter
{
// Header/footer image location
const IMAGE_HEADER_LEFT = 'LH';
const IMAGE_HEADER_LEFT_ODD = 'LH';
const IMAGE_HEADER_LEFT_FIRST = 'LHFIRST';
const IMAGE_HEADER_LEFT_EVEN = 'LHEVEN';
const IMAGE_HEADER_CENTER = 'CH';
const IMAGE_HEADER_CENTER_ODD = 'CH';
const IMAGE_HEADER_CENTER_FIRST = 'CHFIRST';
const IMAGE_HEADER_CENTER_EVEN = 'CHEVEN';
const IMAGE_HEADER_RIGHT = 'RH';
const IMAGE_HEADER_RIGHT_ODD = 'RH';
const IMAGE_HEADER_RIGHT_FIRST = 'RHFIRST';
const IMAGE_HEADER_RIGHT_EVEN = 'RHEVEN';
const IMAGE_FOOTER_LEFT = 'LF';
const IMAGE_FOOTER_LEFT_ODD = 'LF';
const IMAGE_FOOTER_LEFT_FIRST = 'LFFIRST';
const IMAGE_FOOTER_LEFT_EVEN = 'LFEVEN';
const IMAGE_FOOTER_CENTER = 'CF';
const IMAGE_FOOTER_CENTER_ODD = 'CF';
const IMAGE_FOOTER_CENTER_FIRST = 'CFFIRST';
const IMAGE_FOOTER_CENTER_EVEN = 'CFEVEN';
const IMAGE_FOOTER_RIGHT = 'RF';
const IMAGE_FOOTER_RIGHT_ODD = 'RF';
const IMAGE_FOOTER_RIGHT_FIRST = 'RFFIRST';
const IMAGE_FOOTER_RIGHT_EVEN = 'RFEVEN';
/**
* OddHeader.
*/
private string $oddHeader = '';
/**
* OddFooter.
*/
private string $oddFooter = '';
/**
* EvenHeader.
*/
private string $evenHeader = '';
/**
* EvenFooter.
*/
private string $evenFooter = '';
/**
* FirstHeader.
*/
private string $firstHeader = '';
/**
* FirstFooter.
*/
private string $firstFooter = '';
/**
* Different header for Odd/Even, defaults to false.
*/
private bool $differentOddEven = false;
/**
* Different header for first page, defaults to false.
*/
private bool $differentFirst = false;
/**
* Scale with document, defaults to true.
*/
private bool $scaleWithDocument = true;
/**
* Align with margins, defaults to true.
*/
private bool $alignWithMargins = true;
/**
* Header/footer images.
*
* @var HeaderFooterDrawing[]
*/
private array $headerFooterImages = [];
/**
* Create a new HeaderFooter.
*/
public function __construct()
{
}
/**
* Get OddHeader.
*/
public function getOddHeader(): string
{
return $this->oddHeader;
}
/**
* Set OddHeader.
*
* @return $this
*/
public function setOddHeader(string $oddHeader): static
{
$this->oddHeader = $oddHeader;
return $this;
}
/**
* Get OddFooter.
*/
public function getOddFooter(): string
{
return $this->oddFooter;
}
/**
* Set OddFooter.
*
* @return $this
*/
public function setOddFooter(string $oddFooter): static
{
$this->oddFooter = $oddFooter;
return $this;
}
/**
* Get EvenHeader.
*/
public function getEvenHeader(): string
{
return $this->evenHeader;
}
/**
* Set EvenHeader.
*
* @return $this
*/
public function setEvenHeader(string $eventHeader): static
{
$this->evenHeader = $eventHeader;
return $this;
}
/**
* Get EvenFooter.
*/
public function getEvenFooter(): string
{
return $this->evenFooter;
}
/**
* Set EvenFooter.
*
* @return $this
*/
public function setEvenFooter(string $evenFooter): static
{
$this->evenFooter = $evenFooter;
return $this;
}
/**
* Get FirstHeader.
*/
public function getFirstHeader(): string
{
return $this->firstHeader;
}
/**
* Set FirstHeader.
*
* @return $this
*/
public function setFirstHeader(string $firstHeader): static
{
$this->firstHeader = $firstHeader;
return $this;
}
/**
* Get FirstFooter.
*/
public function getFirstFooter(): string
{
return $this->firstFooter;
}
/**
* Set FirstFooter.
*
* @return $this
*/
public function setFirstFooter(string $firstFooter): static
{
$this->firstFooter = $firstFooter;
return $this;
}
/**
* Get DifferentOddEven.
*/
public function getDifferentOddEven(): bool
{
return $this->differentOddEven;
}
/**
* Set DifferentOddEven.
*
* @return $this
*/
public function setDifferentOddEven(bool $differentOddEvent): static
{
$this->differentOddEven = $differentOddEvent;
return $this;
}
/**
* Get DifferentFirst.
*/
public function getDifferentFirst(): bool
{
return $this->differentFirst;
}
/**
* Set DifferentFirst.
*
* @return $this
*/
public function setDifferentFirst(bool $differentFirst): static
{
$this->differentFirst = $differentFirst;
return $this;
}
/**
* Get ScaleWithDocument.
*/
public function getScaleWithDocument(): bool
{
return $this->scaleWithDocument;
}
/**
* Set ScaleWithDocument.
*
* @return $this
*/
public function setScaleWithDocument(bool $scaleWithDocument): static
{
$this->scaleWithDocument = $scaleWithDocument;
return $this;
}
/**
* Get AlignWithMargins.
*/
public function getAlignWithMargins(): bool
{
return $this->alignWithMargins;
}
/**
* Set AlignWithMargins.
*
* @return $this
*/
public function setAlignWithMargins(bool $alignWithMargins): static
{
$this->alignWithMargins = $alignWithMargins;
return $this;
}
/**
* Add header/footer image.
*
* @return $this
*/
public function addImage(HeaderFooterDrawing $image, string $location = self::IMAGE_HEADER_LEFT): static
{
$this->headerFooterImages[$location] = $image;
return $this;
}
/**
* Remove header/footer image.
*
* @return $this
*/
public function removeImage(string $location = self::IMAGE_HEADER_LEFT): static
{
if (isset($this->headerFooterImages[$location])) {
unset($this->headerFooterImages[$location]);
}
return $this;
}
/**
* Set header/footer images.
*
* @param HeaderFooterDrawing[] $images
*
* @return $this
*/
public function setImages(array $images): static
{
$this->headerFooterImages = $images;
return $this;
}
private const IMAGE_SORT_ORDER = [
self::IMAGE_HEADER_LEFT,
self::IMAGE_HEADER_LEFT_FIRST,
self::IMAGE_HEADER_LEFT_EVEN,
self::IMAGE_HEADER_CENTER,
self::IMAGE_HEADER_CENTER_FIRST,
self::IMAGE_HEADER_CENTER_EVEN,
self::IMAGE_HEADER_RIGHT,
self::IMAGE_HEADER_RIGHT_FIRST,
self::IMAGE_HEADER_RIGHT_EVEN,
self::IMAGE_FOOTER_LEFT,
self::IMAGE_FOOTER_LEFT_FIRST,
self::IMAGE_FOOTER_LEFT_EVEN,
self::IMAGE_FOOTER_CENTER,
self::IMAGE_FOOTER_CENTER_FIRST,
self::IMAGE_FOOTER_CENTER_EVEN,
self::IMAGE_FOOTER_RIGHT,
self::IMAGE_FOOTER_RIGHT_FIRST,
self::IMAGE_FOOTER_RIGHT_EVEN,
];
/**
* Get header/footer images.
*
* @return HeaderFooterDrawing[]
*/
public function getImages(): array
{
// Sort array - not sure why needed
$images = [];
foreach (self::IMAGE_SORT_ORDER as $key) {
if (isset($this->headerFooterImages[$key])) {
$images[$key] = $this->headerFooterImages[$key];
}
}
$this->headerFooterImages = $images;
return $this->headerFooterImages;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Validations.php | src/PhpSpreadsheet/Worksheet/Validations.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use Composer\Pcre\Preg;
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
use PhpOffice\PhpSpreadsheet\Cell\CellRange;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
class Validations
{
/**
* Validate a cell address.
*
* @param null|array{0: int, 1: int}|CellAddress|string $cellAddress Coordinate of the cell as a string, eg: 'C5';
* or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object.
*/
public static function validateCellAddress(null|CellAddress|string|array $cellAddress): string
{
if (is_string($cellAddress)) {
[$worksheet, $address] = Worksheet::extractSheetTitle($cellAddress, true);
// if (!empty($worksheet) && $worksheet !== $this->getTitle()) {
// throw new Exception('Reference is not for this worksheet');
// }
return empty($worksheet) ? strtoupper("$address") : $worksheet . '!' . strtoupper("$address");
}
if (is_array($cellAddress)) {
$cellAddress = CellAddress::fromColumnRowArray($cellAddress);
}
return (string) $cellAddress;
}
/**
* Validate a cell address or cell range.
*
* @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|CellAddress|int|string $cellRange Coordinate of the cells as a string, eg: 'C5:F12';
* or as an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 12]),
* or as a CellAddress or AddressRange object.
*/
public static function validateCellOrCellRange(AddressRange|CellAddress|int|string|array $cellRange): string
{
if (is_string($cellRange) || is_numeric($cellRange)) {
// Convert a single column reference like 'A' to 'A:A',
// a single row reference like '1' to '1:1'
$cellRange = Preg::replace('/^([A-Z]+|\d+)$/', '${1}:${1}', (string) $cellRange);
} elseif (is_object($cellRange) && $cellRange instanceof CellAddress) {
$cellRange = new CellRange($cellRange, $cellRange);
}
return self::validateCellRange($cellRange);
}
private const SETMAXROW = '${1}1:${2}' . AddressRange::MAX_ROW;
private const SETMAXCOL = 'A${1}:' . AddressRange::MAX_COLUMN . '${2}';
/**
* Convert Column ranges like 'A:C' to 'A1:C1048576'
* or Row ranges like '1:3' to 'A1:XFD3'.
*/
public static function convertWholeRowColumn(?string $addressRange): string
{
return Preg::replace(
['/^([A-Z]+):([A-Z]+)$/i', '/^(\d+):(\d+)$/'],
[self::SETMAXROW, self::SETMAXCOL],
$addressRange ?? ''
);
}
/**
* Validate a cell range.
*
* @param AddressRange<CellAddress>|AddressRange<int>|AddressRange<string>|array{0: int, 1: int, 2: int, 3: int}|array{0: int, 1: int}|string $cellRange Coordinate of the cells as a string, eg: 'C5:F12';
* or as an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 12]),
* or as an AddressRange object.
*/
public static function validateCellRange(AddressRange|string|array $cellRange): string
{
if (is_string($cellRange)) {
[$worksheet, $addressRange] = Worksheet::extractSheetTitle($cellRange, true);
// Convert Column ranges like 'A:C' to 'A1:C1048576'
// or Row ranges like '1:3' to 'A1:XFD3'
$addressRange = self::convertWholeRowColumn($addressRange);
return empty($worksheet) ? strtoupper($addressRange) : $worksheet . '!' . strtoupper($addressRange);
}
if (is_array($cellRange)) {
switch (count($cellRange)) {
case 4:
$from = [$cellRange[0], $cellRange[1]];
$to = [$cellRange[2], $cellRange[3]];
break;
case 2:
$from = [$cellRange[0], $cellRange[1]];
$to = [$cellRange[0], $cellRange[1]];
break;
default:
throw new SpreadsheetException('CellRange array length must be 2 or 4');
}
$cellRange = new CellRange(CellAddress::fromColumnRowArray($from), CellAddress::fromColumnRowArray($to));
}
return (string) $cellRange;
}
public static function definedNameToCoordinate(string $coordinate, Worksheet $worksheet): string
{
// Uppercase coordinate
$coordinate = strtoupper($coordinate);
// Eliminate leading equal sign
$testCoordinate = Preg::replace('/^=/', '', $coordinate);
$defined = $worksheet->getParentOrThrow()->getDefinedName($testCoordinate, $worksheet);
if ($defined !== null) {
if ($defined->getWorksheet() === $worksheet && !$defined->isFormula()) {
$coordinate = Preg::replace('/^=/', '', $defined->getValue());
}
}
return $coordinate;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Table/TableStyle.php | src/PhpSpreadsheet/Worksheet/Table/TableStyle.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet\Table;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
class TableStyle
{
const TABLE_STYLE_NONE = '';
const TABLE_STYLE_LIGHT1 = 'TableStyleLight1';
const TABLE_STYLE_LIGHT2 = 'TableStyleLight2';
const TABLE_STYLE_LIGHT3 = 'TableStyleLight3';
const TABLE_STYLE_LIGHT4 = 'TableStyleLight4';
const TABLE_STYLE_LIGHT5 = 'TableStyleLight5';
const TABLE_STYLE_LIGHT6 = 'TableStyleLight6';
const TABLE_STYLE_LIGHT7 = 'TableStyleLight7';
const TABLE_STYLE_LIGHT8 = 'TableStyleLight8';
const TABLE_STYLE_LIGHT9 = 'TableStyleLight9';
const TABLE_STYLE_LIGHT10 = 'TableStyleLight10';
const TABLE_STYLE_LIGHT11 = 'TableStyleLight11';
const TABLE_STYLE_LIGHT12 = 'TableStyleLight12';
const TABLE_STYLE_LIGHT13 = 'TableStyleLight13';
const TABLE_STYLE_LIGHT14 = 'TableStyleLight14';
const TABLE_STYLE_LIGHT15 = 'TableStyleLight15';
const TABLE_STYLE_LIGHT16 = 'TableStyleLight16';
const TABLE_STYLE_LIGHT17 = 'TableStyleLight17';
const TABLE_STYLE_LIGHT18 = 'TableStyleLight18';
const TABLE_STYLE_LIGHT19 = 'TableStyleLight19';
const TABLE_STYLE_LIGHT20 = 'TableStyleLight20';
const TABLE_STYLE_LIGHT21 = 'TableStyleLight21';
const TABLE_STYLE_MEDIUM1 = 'TableStyleMedium1';
const TABLE_STYLE_MEDIUM2 = 'TableStyleMedium2';
const TABLE_STYLE_MEDIUM3 = 'TableStyleMedium3';
const TABLE_STYLE_MEDIUM4 = 'TableStyleMedium4';
const TABLE_STYLE_MEDIUM5 = 'TableStyleMedium5';
const TABLE_STYLE_MEDIUM6 = 'TableStyleMedium6';
const TABLE_STYLE_MEDIUM7 = 'TableStyleMedium7';
const TABLE_STYLE_MEDIUM8 = 'TableStyleMedium8';
const TABLE_STYLE_MEDIUM9 = 'TableStyleMedium9';
const TABLE_STYLE_MEDIUM10 = 'TableStyleMedium10';
const TABLE_STYLE_MEDIUM11 = 'TableStyleMedium11';
const TABLE_STYLE_MEDIUM12 = 'TableStyleMedium12';
const TABLE_STYLE_MEDIUM13 = 'TableStyleMedium13';
const TABLE_STYLE_MEDIUM14 = 'TableStyleMedium14';
const TABLE_STYLE_MEDIUM15 = 'TableStyleMedium15';
const TABLE_STYLE_MEDIUM16 = 'TableStyleMedium16';
const TABLE_STYLE_MEDIUM17 = 'TableStyleMedium17';
const TABLE_STYLE_MEDIUM18 = 'TableStyleMedium18';
const TABLE_STYLE_MEDIUM19 = 'TableStyleMedium19';
const TABLE_STYLE_MEDIUM20 = 'TableStyleMedium20';
const TABLE_STYLE_MEDIUM21 = 'TableStyleMedium21';
const TABLE_STYLE_MEDIUM22 = 'TableStyleMedium22';
const TABLE_STYLE_MEDIUM23 = 'TableStyleMedium23';
const TABLE_STYLE_MEDIUM24 = 'TableStyleMedium24';
const TABLE_STYLE_MEDIUM25 = 'TableStyleMedium25';
const TABLE_STYLE_MEDIUM26 = 'TableStyleMedium26';
const TABLE_STYLE_MEDIUM27 = 'TableStyleMedium27';
const TABLE_STYLE_MEDIUM28 = 'TableStyleMedium28';
const TABLE_STYLE_DARK1 = 'TableStyleDark1';
const TABLE_STYLE_DARK2 = 'TableStyleDark2';
const TABLE_STYLE_DARK3 = 'TableStyleDark3';
const TABLE_STYLE_DARK4 = 'TableStyleDark4';
const TABLE_STYLE_DARK5 = 'TableStyleDark5';
const TABLE_STYLE_DARK6 = 'TableStyleDark6';
const TABLE_STYLE_DARK7 = 'TableStyleDark7';
const TABLE_STYLE_DARK8 = 'TableStyleDark8';
const TABLE_STYLE_DARK9 = 'TableStyleDark9';
const TABLE_STYLE_DARK10 = 'TableStyleDark10';
const TABLE_STYLE_DARK11 = 'TableStyleDark11';
/**
* Theme.
*/
private string $theme;
/**
* Show First Column.
*/
private bool $showFirstColumn = false;
/**
* Show Last Column.
*/
private bool $showLastColumn = false;
/**
* Show Row Stripes.
*/
private bool $showRowStripes = false;
/**
* Show Column Stripes.
*/
private bool $showColumnStripes = false;
/**
* TableDxfsStyle.
*/
private ?TableDxfsStyle $tableStyle = null;
/**
* Table.
*/
private ?Table $table = null;
/**
* Create a new Table Style.
*
* @param string $theme (e.g. TableStyle::TABLE_STYLE_MEDIUM2)
*/
public function __construct(string $theme = self::TABLE_STYLE_MEDIUM2)
{
$this->theme = $theme;
}
/**
* Get theme.
*/
public function getTheme(): string
{
return $this->theme;
}
/**
* Set theme.
*/
public function setTheme(string $theme): self
{
$this->theme = $theme;
return $this;
}
/**
* Get show First Column.
*/
public function getShowFirstColumn(): bool
{
return $this->showFirstColumn;
}
/**
* Set show First Column.
*/
public function setShowFirstColumn(bool $showFirstColumn): self
{
$this->showFirstColumn = $showFirstColumn;
return $this;
}
/**
* Get show Last Column.
*/
public function getShowLastColumn(): bool
{
return $this->showLastColumn;
}
/**
* Set show Last Column.
*/
public function setShowLastColumn(bool $showLastColumn): self
{
$this->showLastColumn = $showLastColumn;
return $this;
}
/**
* Get show Row Stripes.
*/
public function getShowRowStripes(): bool
{
return $this->showRowStripes;
}
/**
* Set show Row Stripes.
*/
public function setShowRowStripes(bool $showRowStripes): self
{
$this->showRowStripes = $showRowStripes;
return $this;
}
/**
* Get show Column Stripes.
*/
public function getShowColumnStripes(): bool
{
return $this->showColumnStripes;
}
/**
* Set show Column Stripes.
*/
public function setShowColumnStripes(bool $showColumnStripes): self
{
$this->showColumnStripes = $showColumnStripes;
return $this;
}
/**
* Get this Style's Dxfs TableStyle.
*/
public function getTableDxfsStyle(): ?TableDxfsStyle
{
return $this->tableStyle;
}
/**
* Set this Style's Dxfs TableStyle.
*
* @param Style[] $dxfs
*/
public function setTableDxfsStyle(TableDxfsStyle $tableStyle, array $dxfs): self
{
$this->tableStyle = $tableStyle;
if ($this->tableStyle->getHeaderRow() !== null && isset($dxfs[$this->tableStyle->getHeaderRow()])) {
$this->tableStyle->setHeaderRowStyle($dxfs[$this->tableStyle->getHeaderRow()]);
}
if ($this->tableStyle->getFirstRowStripe() !== null && isset($dxfs[$this->tableStyle->getFirstRowStripe()])) {
$this->tableStyle->setFirstRowStripeStyle($dxfs[$this->tableStyle->getFirstRowStripe()]);
}
if ($this->tableStyle->getSecondRowStripe() !== null && isset($dxfs[$this->tableStyle->getSecondRowStripe()])) {
$this->tableStyle->setSecondRowStripeStyle($dxfs[$this->tableStyle->getSecondRowStripe()]);
}
return $this;
}
/**
* Get this Style's Table.
*/
public function getTable(): ?Table
{
return $this->table;
}
/**
* Set this Style's Table.
*/
public function setTable(?Table $table = null): self
{
$this->table = $table;
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Table/TableDxfsStyle.php | src/PhpSpreadsheet/Worksheet/Table/TableDxfsStyle.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet\Table;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
class TableDxfsStyle
{
/**
* Header row dxfs index.
*/
private ?int $headerRow = null;
/**
* First row stripe dxfs index.
*/
private ?int $firstRowStripe = null;
/**
* second row stripe dxfs index.
*/
private ?int $secondRowStripe = null;
/**
* Header row Style.
*/
private ?Style $headerRowStyle = null;
/**
* First row stripe Style.
*/
private ?Style $firstRowStripeStyle = null;
/**
* Second row stripe Style.
*/
private ?Style $secondRowStripeStyle = null;
/**
* Name of the style.
*/
private string $name;
/**
* Create a new Table Style.
*
* @param string $name The name
*/
public function __construct(string $name)
{
$this->name = $name;
}
/**
* Get name.
*/
public function getName(): string
{
return $this->name;
}
/**
* Set header row dxfs index.
*/
public function setHeaderRow(int $row): self
{
$this->headerRow = $row;
return $this;
}
/**
* Get header row dxfs index.
*/
public function getHeaderRow(): ?int
{
return $this->headerRow;
}
/**
* Set first row stripe dxfs index.
*/
public function setFirstRowStripe(int $row): self
{
$this->firstRowStripe = $row;
return $this;
}
/**
* Get first row stripe dxfs index.
*/
public function getFirstRowStripe(): ?int
{
return $this->firstRowStripe;
}
/**
* Set second row stripe dxfs index.
*/
public function setSecondRowStripe(int $row): self
{
$this->secondRowStripe = $row;
return $this;
}
/**
* Get second row stripe dxfs index.
*/
public function getSecondRowStripe(): ?int
{
return $this->secondRowStripe;
}
/**
* Set Header row Style.
*/
public function setHeaderRowStyle(Style $style): self
{
$this->headerRowStyle = $style;
return $this;
}
/**
* Get Header row Style.
*/
public function getHeaderRowStyle(): ?Style
{
return $this->headerRowStyle;
}
/**
* Set first row stripe Style.
*/
public function setFirstRowStripeStyle(Style $style): self
{
$this->firstRowStripeStyle = $style;
return $this;
}
/**
* Get first row stripe Style.
*/
public function getFirstRowStripeStyle(): ?Style
{
return $this->firstRowStripeStyle;
}
/**
* Set second row stripe Style.
*/
public function setSecondRowStripeStyle(Style $style): self
{
$this->secondRowStripeStyle = $style;
return $this;
}
/**
* Get second row stripe Style.
*/
public function getSecondRowStripeStyle(): ?Style
{
return $this->secondRowStripeStyle;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Table/Column.php | src/PhpSpreadsheet/Worksheet/Table/Column.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet\Table;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class Column
{
/**
* Table Column Index.
*/
private string $columnIndex;
/**
* Show Filter Button.
*/
private bool $showFilterButton = true;
/**
* Total Row Label.
*/
private ?string $totalsRowLabel = null;
/**
* Total Row Function.
*/
private ?string $totalsRowFunction = null;
/**
* Total Row Formula.
*/
private ?string $totalsRowFormula = null;
/**
* Column Formula.
*/
private ?string $columnFormula = null;
/**
* Table.
*/
private ?Table $table;
/**
* Create a new Column.
*
* @param string $column Column (e.g. A)
* @param ?Table $table Table for this column
*/
public function __construct(string $column, ?Table $table = null)
{
$this->columnIndex = $column;
$this->table = $table;
}
/**
* Get Table column index as string eg: 'A'.
*/
public function getColumnIndex(): string
{
return $this->columnIndex;
}
/**
* Set Table column index as string eg: 'A'.
*
* @param string $column Column (e.g. A)
*/
public function setColumnIndex(string $column): self
{
// Uppercase coordinate
$column = strtoupper($column);
if ($this->table !== null) {
$this->table->isColumnInRange($column);
}
$this->columnIndex = $column;
return $this;
}
/**
* Get show Filter Button.
*/
public function getShowFilterButton(): bool
{
return $this->showFilterButton;
}
/**
* Set show Filter Button.
*/
public function setShowFilterButton(bool $showFilterButton): self
{
$this->showFilterButton = $showFilterButton;
return $this;
}
/**
* Get total Row Label.
*/
public function getTotalsRowLabel(): ?string
{
return $this->totalsRowLabel;
}
/**
* Set total Row Label.
*/
public function setTotalsRowLabel(string $totalsRowLabel): self
{
$this->totalsRowLabel = $totalsRowLabel;
return $this;
}
/**
* Get total Row Function.
*/
public function getTotalsRowFunction(): ?string
{
return $this->totalsRowFunction;
}
/**
* Set total Row Function.
*/
public function setTotalsRowFunction(string $totalsRowFunction): self
{
$this->totalsRowFunction = $totalsRowFunction;
return $this;
}
/**
* Get total Row Formula.
*/
public function getTotalsRowFormula(): ?string
{
return $this->totalsRowFormula;
}
/**
* Set total Row Formula.
*/
public function setTotalsRowFormula(string $totalsRowFormula): self
{
$this->totalsRowFormula = $totalsRowFormula;
return $this;
}
/**
* Get column Formula.
*/
public function getColumnFormula(): ?string
{
return $this->columnFormula;
}
/**
* Set column Formula.
*/
public function setColumnFormula(string $columnFormula): self
{
$this->columnFormula = $columnFormula;
return $this;
}
/**
* Get this Column's Table.
*/
public function getTable(): ?Table
{
return $this->table;
}
/**
* Set this Column's Table.
*/
public function setTable(?Table $table = null): self
{
$this->table = $table;
return $this;
}
public static function updateStructuredReferences(?Worksheet $workSheet, ?string $oldTitle, ?string $newTitle): void
{
if ($workSheet === null || $oldTitle === null || $oldTitle === '' || $newTitle === null) {
return;
}
// Remember that table headings are case-insensitive
if (StringHelper::strToLower($oldTitle) !== StringHelper::strToLower($newTitle)) {
// We need to check all formula cells that might contain Structured References that refer
// to this column, and update those formulae to reference the new column text
$spreadsheet = $workSheet->getParentOrThrow();
foreach ($spreadsheet->getWorksheetIterator() as $sheet) {
self::updateStructuredReferencesInCells($sheet, $oldTitle, $newTitle);
}
self::updateStructuredReferencesInNamedFormulae($spreadsheet, $oldTitle, $newTitle);
}
}
private static function updateStructuredReferencesInCells(Worksheet $worksheet, string $oldTitle, string $newTitle): void
{
$pattern = '/\[(@?)' . preg_quote($oldTitle, '/') . '\]/mui';
foreach ($worksheet->getCoordinates(false) as $coordinate) {
$cell = $worksheet->getCell($coordinate);
if ($cell->getDataType() === DataType::TYPE_FORMULA) {
$formula = $cell->getValueString();
if (preg_match($pattern, $formula) === 1) {
$formula = preg_replace($pattern, "[$1{$newTitle}]", $formula);
$cell->setValueExplicit($formula, DataType::TYPE_FORMULA);
}
}
}
}
private static function updateStructuredReferencesInNamedFormulae(Spreadsheet $spreadsheet, string $oldTitle, string $newTitle): void
{
$pattern = '/\[(@?)' . preg_quote($oldTitle, '/') . '\]/mui';
foreach ($spreadsheet->getNamedFormulae() as $namedFormula) {
$formula = $namedFormula->getValue();
if (preg_match($pattern, $formula) === 1) {
$formula = preg_replace($pattern, "[$1{$newTitle}]", $formula) ?? '';
$namedFormula->setValue($formula);
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php | src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter;
class Column
{
const AUTOFILTER_FILTERTYPE_FILTER = 'filters';
const AUTOFILTER_FILTERTYPE_CUSTOMFILTER = 'customFilters';
// Supports no more than 2 rules, with an And/Or join criteria
// if more than 1 rule is defined
const AUTOFILTER_FILTERTYPE_DYNAMICFILTER = 'dynamicFilter';
// Even though the filter rule is constant, the filtered data can vary
// e.g. filtered by date = TODAY
const AUTOFILTER_FILTERTYPE_TOPTENFILTER = 'top10';
/**
* Types of autofilter rules.
*
* @var string[]
*/
private static array $filterTypes = [
// Currently we're not handling
// colorFilter
// extLst
// iconFilter
self::AUTOFILTER_FILTERTYPE_FILTER,
self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER,
self::AUTOFILTER_FILTERTYPE_DYNAMICFILTER,
self::AUTOFILTER_FILTERTYPE_TOPTENFILTER,
];
// Multiple Rule Connections
const AUTOFILTER_COLUMN_JOIN_AND = 'and';
const AUTOFILTER_COLUMN_JOIN_OR = 'or';
/**
* Join options for autofilter rules.
*
* @var string[]
*/
private static array $ruleJoins = [
self::AUTOFILTER_COLUMN_JOIN_AND,
self::AUTOFILTER_COLUMN_JOIN_OR,
];
/**
* Autofilter.
*/
private ?AutoFilter $parent;
/**
* Autofilter Column Index.
*/
private string $columnIndex;
/**
* Autofilter Column Filter Type.
*/
private string $filterType = self::AUTOFILTER_FILTERTYPE_FILTER;
/**
* Autofilter Multiple Rules And/Or.
*/
private string $join = self::AUTOFILTER_COLUMN_JOIN_OR;
/**
* Autofilter Column Rules.
*
* @var Column\Rule[]
*/
private array $ruleset = [];
/**
* Autofilter Column Dynamic Attributes.
*
* @var (float|int|string)[]
*/
private array $attributes = [];
/**
* Create a new Column.
*
* @param string $column Column (e.g. A)
* @param ?AutoFilter $parent Autofilter for this column
*/
public function __construct(string $column, ?AutoFilter $parent = null)
{
$this->columnIndex = $column;
$this->parent = $parent;
}
public function setEvaluatedFalse(): void
{
if ($this->parent !== null) {
$this->parent->setEvaluated(false);
}
}
/**
* Get AutoFilter column index as string eg: 'A'.
*/
public function getColumnIndex(): string
{
return $this->columnIndex;
}
/**
* Set AutoFilter column index as string eg: 'A'.
*
* @param string $column Column (e.g. A)
*
* @return $this
*/
public function setColumnIndex(string $column): static
{
$this->setEvaluatedFalse();
// Uppercase coordinate
$column = strtoupper($column);
if ($this->parent !== null) {
$this->parent->testColumnInRange($column);
}
$this->columnIndex = $column;
return $this;
}
/**
* Get this Column's AutoFilter Parent.
*/
public function getParent(): ?AutoFilter
{
return $this->parent;
}
/**
* Set this Column's AutoFilter Parent.
*
* @return $this
*/
public function setParent(?AutoFilter $parent = null): static
{
$this->setEvaluatedFalse();
$this->parent = $parent;
return $this;
}
/**
* Get AutoFilter Type.
*/
public function getFilterType(): string
{
return $this->filterType;
}
/**
* Set AutoFilter Type.
*
* @return $this
*/
public function setFilterType(string $filterType): static
{
$this->setEvaluatedFalse();
if (!in_array($filterType, self::$filterTypes)) {
throw new PhpSpreadsheetException('Invalid filter type for column AutoFilter.');
}
if ($filterType === self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER && count($this->ruleset) > 2) {
throw new PhpSpreadsheetException('No more than 2 rules are allowed in a Custom Filter');
}
$this->filterType = $filterType;
return $this;
}
/**
* Get AutoFilter Multiple Rules And/Or Join.
*/
public function getJoin(): string
{
return $this->join;
}
/**
* Set AutoFilter Multiple Rules And/Or.
*
* @param string $join And/Or
*
* @return $this
*/
public function setJoin(string $join): static
{
$this->setEvaluatedFalse();
// Lowercase And/Or
$join = strtolower($join);
if (!in_array($join, self::$ruleJoins)) {
throw new PhpSpreadsheetException('Invalid rule connection for column AutoFilter.');
}
$this->join = $join;
return $this;
}
/**
* Set AutoFilter Attributes.
*
* @param (float|int|string)[] $attributes
*
* @return $this
*/
public function setAttributes(array $attributes): static
{
$this->setEvaluatedFalse();
$this->attributes = $attributes;
return $this;
}
/**
* Set An AutoFilter Attribute.
*
* @param string $name Attribute Name
* @param float|int|string $value Attribute Value
*
* @return $this
*/
public function setAttribute(string $name, $value): static
{
$this->setEvaluatedFalse();
$this->attributes[$name] = $value;
return $this;
}
/**
* Get AutoFilter Column Attributes.
*
* @return (float|int|string)[]
*/
public function getAttributes(): array
{
return $this->attributes;
}
/**
* Get specific AutoFilter Column Attribute.
*
* @param string $name Attribute Name
*/
public function getAttribute(string $name): null|float|int|string
{
if (isset($this->attributes[$name])) {
return $this->attributes[$name];
}
return null;
}
public function ruleCount(): int
{
return count($this->ruleset);
}
/**
* Get all AutoFilter Column Rules.
*
* @return Column\Rule[]
*/
public function getRules(): array
{
return $this->ruleset;
}
/**
* Get a specified AutoFilter Column Rule.
*
* @param int $index Rule index in the ruleset array
*/
public function getRule(int $index): Column\Rule
{
if (!isset($this->ruleset[$index])) {
$this->ruleset[$index] = new Column\Rule($this);
}
return $this->ruleset[$index];
}
/**
* Create a new AutoFilter Column Rule in the ruleset.
*/
public function createRule(): Column\Rule
{
$this->setEvaluatedFalse();
if ($this->filterType === self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER && count($this->ruleset) >= 2) {
throw new PhpSpreadsheetException('No more than 2 rules are allowed in a Custom Filter');
}
$this->ruleset[] = new Column\Rule($this);
return end($this->ruleset);
}
/**
* Add a new AutoFilter Column Rule to the ruleset.
*
* @return $this
*/
public function addRule(Column\Rule $rule): static
{
$this->setEvaluatedFalse();
$rule->setParent($this);
$this->ruleset[] = $rule;
return $this;
}
/**
* Delete a specified AutoFilter Column Rule
* If the number of rules is reduced to 1, then we reset And/Or logic to Or.
*
* @param int $index Rule index in the ruleset array
*
* @return $this
*/
public function deleteRule(int $index): static
{
$this->setEvaluatedFalse();
if (isset($this->ruleset[$index])) {
unset($this->ruleset[$index]);
// If we've just deleted down to a single rule, then reset And/Or joining to Or
if (count($this->ruleset) <= 1) {
$this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR);
}
}
return $this;
}
/**
* Delete all AutoFilter Column Rules.
*
* @return $this
*/
public function clearRules(): static
{
$this->setEvaluatedFalse();
$this->ruleset = [];
$this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR);
return $this;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
/** @var Column\Rule[] $value */
foreach ($vars as $key => $value) {
if ($key === 'parent') {
// Detach from autofilter parent
$this->parent = null;
} elseif ($key === 'ruleset') {
// The columns array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter objects
$this->ruleset = [];
foreach ($value as $k => $v) {
$cloned = clone $v;
$cloned->setParent($this); // attach the new cloned Rule to this new cloned Autofilter Cloned object
$this->ruleset[$k] = $cloned;
}
} else {
$this->$key = $value;
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php | src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column;
class Rule
{
const AUTOFILTER_RULETYPE_FILTER = 'filter';
const AUTOFILTER_RULETYPE_DATEGROUP = 'dateGroupItem';
const AUTOFILTER_RULETYPE_CUSTOMFILTER = 'customFilter';
const AUTOFILTER_RULETYPE_DYNAMICFILTER = 'dynamicFilter';
const AUTOFILTER_RULETYPE_TOPTENFILTER = 'top10Filter';
private const RULE_TYPES = [
// Currently we're not handling
// colorFilter
// extLst
// iconFilter
self::AUTOFILTER_RULETYPE_FILTER,
self::AUTOFILTER_RULETYPE_DATEGROUP,
self::AUTOFILTER_RULETYPE_CUSTOMFILTER,
self::AUTOFILTER_RULETYPE_DYNAMICFILTER,
self::AUTOFILTER_RULETYPE_TOPTENFILTER,
];
const AUTOFILTER_RULETYPE_DATEGROUP_YEAR = 'year';
const AUTOFILTER_RULETYPE_DATEGROUP_MONTH = 'month';
const AUTOFILTER_RULETYPE_DATEGROUP_DAY = 'day';
const AUTOFILTER_RULETYPE_DATEGROUP_HOUR = 'hour';
const AUTOFILTER_RULETYPE_DATEGROUP_MINUTE = 'minute';
const AUTOFILTER_RULETYPE_DATEGROUP_SECOND = 'second';
private const DATE_TIME_GROUPS = [
self::AUTOFILTER_RULETYPE_DATEGROUP_YEAR,
self::AUTOFILTER_RULETYPE_DATEGROUP_MONTH,
self::AUTOFILTER_RULETYPE_DATEGROUP_DAY,
self::AUTOFILTER_RULETYPE_DATEGROUP_HOUR,
self::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE,
self::AUTOFILTER_RULETYPE_DATEGROUP_SECOND,
];
const AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY = 'yesterday';
const AUTOFILTER_RULETYPE_DYNAMIC_TODAY = 'today';
const AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW = 'tomorrow';
const AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE = 'yearToDate';
const AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR = 'thisYear';
const AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER = 'thisQuarter';
const AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH = 'thisMonth';
const AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK = 'thisWeek';
const AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR = 'lastYear';
const AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER = 'lastQuarter';
const AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH = 'lastMonth';
const AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK = 'lastWeek';
const AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR = 'nextYear';
const AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER = 'nextQuarter';
const AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH = 'nextMonth';
const AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK = 'nextWeek';
const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 = 'M1';
const AUTOFILTER_RULETYPE_DYNAMIC_JANUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1;
const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 = 'M2';
const AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2;
const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 = 'M3';
const AUTOFILTER_RULETYPE_DYNAMIC_MARCH = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3;
const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 = 'M4';
const AUTOFILTER_RULETYPE_DYNAMIC_APRIL = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4;
const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 = 'M5';
const AUTOFILTER_RULETYPE_DYNAMIC_MAY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5;
const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 = 'M6';
const AUTOFILTER_RULETYPE_DYNAMIC_JUNE = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6;
const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 = 'M7';
const AUTOFILTER_RULETYPE_DYNAMIC_JULY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7;
const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 = 'M8';
const AUTOFILTER_RULETYPE_DYNAMIC_AUGUST = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8;
const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 = 'M9';
const AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9;
const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 = 'M10';
const AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10;
const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 = 'M11';
const AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11;
const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 = 'M12';
const AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12;
const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 = 'Q1';
const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 = 'Q2';
const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 = 'Q3';
const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 = 'Q4';
const AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE = 'aboveAverage';
const AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE = 'belowAverage';
private const DYNAMIC_TYPES = [
self::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY,
self::AUTOFILTER_RULETYPE_DYNAMIC_TODAY,
self::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW,
self::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE,
self::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR,
self::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER,
self::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH,
self::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK,
self::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR,
self::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER,
self::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH,
self::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK,
self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR,
self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER,
self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH,
self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK,
self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1,
self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2,
self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3,
self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4,
self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5,
self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6,
self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7,
self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8,
self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9,
self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10,
self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11,
self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12,
self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1,
self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2,
self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3,
self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4,
self::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE,
self::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE,
];
// Filter rule operators for filter and customFilter types.
const AUTOFILTER_COLUMN_RULE_EQUAL = 'equal';
const AUTOFILTER_COLUMN_RULE_NOTEQUAL = 'notEqual';
const AUTOFILTER_COLUMN_RULE_GREATERTHAN = 'greaterThan';
const AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL = 'greaterThanOrEqual';
const AUTOFILTER_COLUMN_RULE_LESSTHAN = 'lessThan';
const AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL = 'lessThanOrEqual';
private const OPERATORS = [
self::AUTOFILTER_COLUMN_RULE_EQUAL,
self::AUTOFILTER_COLUMN_RULE_NOTEQUAL,
self::AUTOFILTER_COLUMN_RULE_GREATERTHAN,
self::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL,
self::AUTOFILTER_COLUMN_RULE_LESSTHAN,
self::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL,
];
const AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE = 'byValue';
const AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT = 'byPercent';
private const TOP_TEN_VALUE = [
self::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE,
self::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT,
];
const AUTOFILTER_COLUMN_RULE_TOPTEN_TOP = 'top';
const AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM = 'bottom';
private const TOP_TEN_TYPE = [
self::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP,
self::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM,
];
// Unimplemented Rule Operators (Numeric, Boolean etc)
// const AUTOFILTER_COLUMN_RULE_BETWEEN = 'between'; // greaterThanOrEqual 1 && lessThanOrEqual 2
// Rule Operators (Numeric Special) which are translated to standard numeric operators with calculated values
// Rule Operators (String) which are set as wild-carded values
// const AUTOFILTER_COLUMN_RULE_BEGINSWITH = 'beginsWith'; // A*
// const AUTOFILTER_COLUMN_RULE_ENDSWITH = 'endsWith'; // *Z
// const AUTOFILTER_COLUMN_RULE_CONTAINS = 'contains'; // *B*
// const AUTOFILTER_COLUMN_RULE_DOESNTCONTAIN = 'notEqual'; // notEqual *B*
// Rule Operators (Date Special) which are translated to standard numeric operators with calculated values
// const AUTOFILTER_COLUMN_RULE_BEFORE = 'lessThan';
// const AUTOFILTER_COLUMN_RULE_AFTER = 'greaterThan';
/**
* Autofilter Column.
*/
private ?Column $parent;
/**
* Autofilter Rule Type.
*/
private string $ruleType = self::AUTOFILTER_RULETYPE_FILTER;
/**
* Autofilter Rule Value.
*
* @var int|int[]|string|string[]
*/
private $value = '';
/**
* Autofilter Rule Operator.
*/
private string $operator = self::AUTOFILTER_COLUMN_RULE_EQUAL;
/**
* DateTimeGrouping Group Value.
*/
private string $grouping = '';
/**
* Create a new Rule.
*/
public function __construct(?Column $parent = null)
{
$this->parent = $parent;
}
private function setEvaluatedFalse(): void
{
if ($this->parent !== null) {
$this->parent->setEvaluatedFalse();
}
}
/**
* Get AutoFilter Rule Type.
*/
public function getRuleType(): string
{
return $this->ruleType;
}
/**
* Set AutoFilter Rule Type.
*
* @param string $ruleType see self::AUTOFILTER_RULETYPE_*
*
* @return $this
*/
public function setRuleType(string $ruleType): static
{
$this->setEvaluatedFalse();
if (!in_array($ruleType, self::RULE_TYPES)) {
throw new PhpSpreadsheetException('Invalid rule type for column AutoFilter Rule.');
}
$this->ruleType = $ruleType;
return $this;
}
/**
* Get AutoFilter Rule Value.
*
* @return int|int[]|string|string[]
*/
public function getValue()
{
return $this->value;
}
/**
* Set AutoFilter Rule Value.
*
* @param int|int[]|string|string[] $value
*
* @return $this
*/
public function setValue($value): static
{
$this->setEvaluatedFalse();
if (is_array($value)) {
$grouping = -1;
foreach ($value as $key => $v) {
// Validate array entries
if (!in_array($key, self::DATE_TIME_GROUPS)) {
// Remove any invalid entries from the value array
unset($value[$key]);
} else {
// Work out what the dateTime grouping will be
$grouping = max($grouping, array_search($key, self::DATE_TIME_GROUPS));
}
}
if (count($value) == 0) {
throw new PhpSpreadsheetException('Invalid rule value for column AutoFilter Rule.');
}
// Set the dateTime grouping that we've anticipated
// I have no idea what Phpstan is complaining about below
$this->setGrouping(self::DATE_TIME_GROUPS[$grouping]); // @phpstan-ignore-line
}
$this->value = $value;
return $this;
}
/**
* Get AutoFilter Rule Operator.
*/
public function getOperator(): string
{
return $this->operator;
}
/**
* Set AutoFilter Rule Operator.
*
* @param string $operator see self::AUTOFILTER_COLUMN_RULE_*
*
* @return $this
*/
public function setOperator(string $operator): static
{
$this->setEvaluatedFalse();
if (empty($operator)) {
$operator = self::AUTOFILTER_COLUMN_RULE_EQUAL;
}
if (
(!in_array($operator, self::OPERATORS))
&& (!in_array($operator, self::TOP_TEN_VALUE))
) {
throw new PhpSpreadsheetException('Invalid operator for column AutoFilter Rule.');
}
$this->operator = $operator;
return $this;
}
/**
* Get AutoFilter Rule Grouping.
*/
public function getGrouping(): string
{
return $this->grouping;
}
/**
* Set AutoFilter Rule Grouping.
*
* @return $this
*/
public function setGrouping(string $grouping): static
{
$this->setEvaluatedFalse();
if (
(!in_array($grouping, self::DATE_TIME_GROUPS))
&& (!in_array($grouping, self::DYNAMIC_TYPES))
&& (!in_array($grouping, self::TOP_TEN_TYPE))
) {
throw new PhpSpreadsheetException('Invalid grouping for column AutoFilter Rule.');
}
$this->grouping = $grouping;
return $this;
}
/**
* Set AutoFilter Rule.
*
* @param string $operator see self::AUTOFILTER_COLUMN_RULE_*
* @param int|int[]|string|string[] $value
*
* @return $this
*/
public function setRule(string $operator, $value, ?string $grouping = null): static
{
$this->setEvaluatedFalse();
$this->setOperator($operator);
$this->setValue($value);
// Only set grouping if it's been passed in as a user-supplied argument,
// otherwise we're calculating it when we setValue() and don't want to overwrite that
// If the user supplies an argument for grouping, then on their own head be it
if ($grouping !== null) {
$this->setGrouping($grouping);
}
return $this;
}
/**
* Get this Rule's AutoFilter Column Parent.
*/
public function getParent(): ?Column
{
return $this->parent;
}
/**
* Set this Rule's AutoFilter Column Parent.
*
* @return $this
*/
public function setParent(?Column $parent = null): static
{
$this->setEvaluatedFalse();
$this->parent = $parent;
return $this;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
if ($key == 'parent') { // this is only object
// Detach from autofilter column parent
$this->$key = null;
}
} else {
$this->$key = $value;
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php | src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php | <?php
namespace PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\IComparable;
use PhpOffice\PhpSpreadsheet\Style\Color;
class Shadow implements IComparable
{
// Shadow alignment
const SHADOW_BOTTOM = 'b';
const SHADOW_BOTTOM_LEFT = 'bl';
const SHADOW_BOTTOM_RIGHT = 'br';
const SHADOW_CENTER = 'ctr';
const SHADOW_LEFT = 'l';
const SHADOW_TOP = 't';
const SHADOW_TOP_LEFT = 'tl';
const SHADOW_TOP_RIGHT = 'tr';
/**
* Visible.
*/
private bool $visible;
/**
* Blur radius.
*
* Defaults to 6
*/
private int $blurRadius;
/**
* Shadow distance.
*
* Defaults to 2
*/
private int $distance;
/**
* Shadow direction (in degrees).
*/
private int $direction;
/**
* Shadow alignment.
*/
private string $alignment;
/**
* Color.
*/
private Color $color;
/**
* Alpha.
*/
private int $alpha;
/**
* Create a new Shadow.
*/
public function __construct()
{
// Initialise values
$this->visible = false;
$this->blurRadius = 6;
$this->distance = 2;
$this->direction = 0;
$this->alignment = self::SHADOW_BOTTOM_RIGHT;
$this->color = new Color(Color::COLOR_BLACK);
$this->alpha = 50;
}
/**
* Get Visible.
*/
public function getVisible(): bool
{
return $this->visible;
}
/**
* Set Visible.
*
* @return $this
*/
public function setVisible(bool $visible): static
{
$this->visible = $visible;
return $this;
}
/**
* Get Blur radius.
*/
public function getBlurRadius(): int
{
return $this->blurRadius;
}
/**
* Set Blur radius.
*
* @return $this
*/
public function setBlurRadius(int $blurRadius): static
{
$this->blurRadius = $blurRadius;
return $this;
}
/**
* Get Shadow distance.
*/
public function getDistance(): int
{
return $this->distance;
}
/**
* Set Shadow distance.
*
* @return $this
*/
public function setDistance(int $distance): static
{
$this->distance = $distance;
return $this;
}
/**
* Get Shadow direction (in degrees).
*/
public function getDirection(): int
{
return $this->direction;
}
/**
* Set Shadow direction (in degrees).
*
* @return $this
*/
public function setDirection(int $direction): static
{
$this->direction = $direction;
return $this;
}
/**
* Get Shadow alignment.
*/
public function getAlignment(): string
{
return $this->alignment;
}
/**
* Set Shadow alignment.
*
* @return $this
*/
public function setAlignment(string $alignment): static
{
$this->alignment = $alignment;
return $this;
}
/**
* Get Color.
*/
public function getColor(): Color
{
return $this->color;
}
/**
* Set Color.
*
* @return $this
*/
public function setColor(Color $color): static
{
$this->color = $color;
return $this;
}
/**
* Get Alpha.
*/
public function getAlpha(): int
{
return $this->alpha;
}
/**
* Set Alpha.
*
* @return $this
*/
public function setAlpha(int $alpha): static
{
$this->alpha = $alpha;
return $this;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
return md5(
($this->visible ? 't' : 'f')
. $this->blurRadius
. $this->distance
. $this->direction
. $this->alignment
. $this->color->getHashCode()
. $this->alpha
. __CLASS__
);
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Helper/Dimension.php | src/PhpSpreadsheet/Helper/Dimension.php | <?php
namespace PhpOffice\PhpSpreadsheet\Helper;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Shared\Drawing;
use PhpOffice\PhpSpreadsheet\Style\Font;
class Dimension
{
public const UOM_CENTIMETERS = 'cm';
public const UOM_MILLIMETERS = 'mm';
public const UOM_INCHES = 'in';
public const UOM_PIXELS = 'px';
public const UOM_POINTS = 'pt';
public const UOM_PICA = 'pc';
/**
* Based on 96 dpi.
*/
const ABSOLUTE_UNITS = [
self::UOM_CENTIMETERS => 96.0 / 2.54,
self::UOM_MILLIMETERS => 96.0 / 25.4,
self::UOM_INCHES => 96.0,
self::UOM_PIXELS => 1.0,
self::UOM_POINTS => 96.0 / 72,
self::UOM_PICA => 96.0 * 12 / 72,
];
/**
* Based on a standard column width of 8.54 units in MS Excel.
*/
const RELATIVE_UNITS = [
'em' => 10.0 / 8.54,
'ex' => 10.0 / 8.54,
'ch' => 10.0 / 8.54,
'rem' => 10.0 / 8.54,
'vw' => 8.54,
'vh' => 8.54,
'vmin' => 8.54,
'vmax' => 8.54,
'%' => 8.54 / 100,
];
/**
* @var float|int If this is a width, then size is measured in pixels (if is set)
* or in Excel's default column width units if $unit is null.
* If this is a height, then size is measured in pixels ()
* or in points () if $unit is null.
*/
protected float|int $size;
protected ?string $unit = null;
public function __construct(string $dimension)
{
$size = 0.0;
$unit = '';
$sscanf = sscanf($dimension, '%[1234567890.]%s');
if (is_array($sscanf)) {
$size = (float) ($sscanf[0] ?? 0.0);
$unit = strtolower($sscanf[1] ?? '');
}
// If a UoM is specified, then convert the size to pixels for internal storage
if (isset(self::ABSOLUTE_UNITS[$unit])) {
$size *= self::ABSOLUTE_UNITS[$unit];
$this->unit = self::UOM_PIXELS;
} elseif (isset(self::RELATIVE_UNITS[$unit])) {
$size *= self::RELATIVE_UNITS[$unit];
$size = round($size, 4);
}
$this->size = $size;
}
public function width(): float
{
return (float) ($this->unit === null)
? $this->size
: round(Drawing::pixelsToCellDimension((int) $this->size, new Font(false)), 4);
}
public function height(): float
{
return (float) ($this->unit === null)
? $this->size
: $this->toUnit(self::UOM_POINTS);
}
public function toUnit(string $unitOfMeasure): float
{
$unitOfMeasure = strtolower($unitOfMeasure);
if (!array_key_exists($unitOfMeasure, self::ABSOLUTE_UNITS)) {
throw new Exception("{$unitOfMeasure} is not a vaid unit of measure");
}
$size = $this->size;
if ($this->unit === null) {
$size = Drawing::cellDimensionToPixels($size, new Font(false));
}
return $size / self::ABSOLUTE_UNITS[$unitOfMeasure];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Helper/Size.php | src/PhpSpreadsheet/Helper/Size.php | <?php
namespace PhpOffice\PhpSpreadsheet\Helper;
use Stringable;
class Size implements Stringable
{
const REGEXP_SIZE_VALIDATION = '/^(?P<size>\d*\.?\d+)(?P<unit>pt|px|em)?$/i';
protected bool $valid = false;
protected string $size = '';
protected string $unit = '';
public function __construct(string $size)
{
if (1 === preg_match(self::REGEXP_SIZE_VALIDATION, $size, $matches)) {
$this->valid = true;
$this->size = $matches['size'];
$this->unit = $matches['unit'] ?? 'pt';
}
}
public function valid(): bool
{
return $this->valid;
}
public function size(): string
{
return $this->size;
}
public function unit(): string
{
return $this->unit;
}
public function __toString(): string
{
return $this->size . $this->unit;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Helper/Handler.php | src/PhpSpreadsheet/Helper/Handler.php | <?php
namespace PhpOffice\PhpSpreadsheet\Helper;
class Handler
{
private static string $invalidHex = 'Y';
// A bunch of methods to show that we continue
// to capture messages even using PhpUnit 10.
public static function suppressed(): bool
{
return @trigger_error('hello');
}
public static function deprecated(): string
{
return (string) hexdec(self::$invalidHex);
}
public static function notice(string $value): void
{
date_default_timezone_set($value);
}
public static function warning(): bool
{
return file_get_contents(__FILE__ . 'noexist') !== false;
}
public static function userDeprecated(): bool
{
return trigger_error('hello', E_USER_DEPRECATED);
}
public static function userNotice(): bool
{
return trigger_error('userNotice', E_USER_NOTICE);
}
public static function userWarning(): bool
{
return trigger_error('userWarning', E_USER_WARNING);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Helper/Downloader.php | src/PhpSpreadsheet/Helper/Downloader.php | <?php
namespace PhpOffice\PhpSpreadsheet\Helper;
use PhpOffice\PhpSpreadsheet\Exception;
/**
* Assist downloading files when samples are run in browser.
* Never run as part of unit tests, which are command line.
*
* @codeCoverageIgnore
*/
class Downloader
{
protected string $filepath;
protected string $filename;
protected string $filetype;
protected const CONTENT_TYPES = [
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xls' => 'application/vnd.ms-excel',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
'csv' => 'text/csv',
'html' => 'text/html',
'pdf' => 'application/pdf',
];
public function __construct(string $folder, string $filename, ?string $filetype = null)
{
if ((is_dir($folder) === false) || (is_readable($folder) === false)) {
throw new Exception('Folder is not accessible');
}
$filepath = "{$folder}/{$filename}";
$this->filepath = (string) realpath($filepath);
$this->filename = basename($filepath);
clearstatcache();
if ((is_file($this->filepath) === false) || (is_readable($this->filepath) === false)) {
throw new Exception('File not found, or not a regular file, or cannot be read');
}
$filetype ??= pathinfo($filename, PATHINFO_EXTENSION);
if (array_key_exists(strtolower($filetype), self::CONTENT_TYPES) === false) {
throw new Exception('Invalid filetype: file cannot be downloaded');
}
$this->filetype = strtolower($filetype);
}
public function download(): void
{
$this->headers();
readfile($this->filepath);
}
public function headers(): void
{
// I cannot tell what this ob_clean is paired with.
// I have never seen a problem with it, but someone has - issue 3739.
// Perhaps it should be removed altogether,
// but making it conditional seems harmless, and safer.
if ((int) ob_get_length() > 0) {
ob_clean();
}
$this->contentType();
$this->contentDisposition();
$this->cacheHeaders();
$this->fileSize();
flush();
}
protected function contentType(): void
{
header('Content-Type: ' . self::CONTENT_TYPES[$this->filetype]);
}
protected function contentDisposition(): void
{
header('Content-Disposition: attachment;filename="' . $this->filename . '"');
}
protected function cacheHeaders(): void
{
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
}
protected function fileSize(): void
{
header('Content-Length: ' . filesize($this->filepath));
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Helper/Sample.php | src/PhpSpreadsheet/Helper/Sample.php | <?php
namespace PhpOffice\PhpSpreadsheet\Helper;
use PhpOffice\PhpSpreadsheet\Chart\Chart;
use PhpOffice\PhpSpreadsheet\Chart\Renderer\MtJpGraphRenderer;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Settings;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Writer\IWriter;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RecursiveRegexIterator;
use ReflectionClass;
use RegexIterator;
use RuntimeException;
use Throwable;
/**
* Helper class to be used in sample code.
*/
class Sample
{
/**
* Returns whether we run on CLI or browser.
*/
public function isCli(): bool
{
return PHP_SAPI === 'cli';
}
/**
* Return the filename currently being executed.
*/
public function getScriptFilename(): string
{
return basename(StringHelper::convertToString($_SERVER['SCRIPT_FILENAME']), '.php');
}
/**
* Whether we are executing the index page.
*/
public function isIndex(): bool
{
return $this->getScriptFilename() === 'index';
}
/**
* Return the page title.
*/
public function getPageTitle(): string
{
return $this->isIndex() ? 'PHPSpreadsheet' : $this->getScriptFilename();
}
/**
* Return the page heading.
*/
public function getPageHeading(): string
{
return $this->isIndex() ? '' : '<h1>' . str_replace('_', ' ', $this->getScriptFilename()) . '</h1>';
}
/**
* Returns an array of all known samples.
*
* @return string[][] [$name => $path]
*/
public function getSamples(): array
{
// Populate samples
$baseDir = realpath(__DIR__ . '/../../../samples');
if ($baseDir === false) {
// @codeCoverageIgnoreStart
throw new RuntimeException('realpath returned false');
// @codeCoverageIgnoreEnd
}
$directory = new RecursiveDirectoryIterator($baseDir);
$iterator = new RecursiveIteratorIterator($directory);
$regex = new RegexIterator($iterator, '/^.+\.php$/', RecursiveRegexIterator::GET_MATCH);
$files = [];
/** @var string[] $file */
foreach ($regex as $file) {
$file = str_replace(str_replace('\\', '/', $baseDir) . '/', '', str_replace('\\', '/', $file[0]));
$info = pathinfo($file);
$category = str_replace('_', ' ', $info['dirname'] ?? '');
$name = str_replace('_', ' ', (string) preg_replace('/(|\.php)/', '', $info['filename']));
if (!in_array($category, ['.', 'bootstrap', 'templates']) && $name !== 'Header') {
if (!isset($files[$category])) {
$files[$category] = [];
}
$files[$category][$name] = $file;
}
}
// Sort everything
ksort($files);
foreach ($files as &$f) {
asort($f);
}
return $files;
}
/**
* Write documents.
*
* @param string[] $writers
*/
public function write(Spreadsheet $spreadsheet, string $filename, array $writers = ['Xlsx', 'Xls'], bool $withCharts = false, ?callable $writerCallback = null, bool $resetActiveSheet = true): void
{
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
if ($resetActiveSheet) {
$spreadsheet->setActiveSheetIndex(0);
}
// Write documents
foreach ($writers as $writerType) {
$path = $this->getFilename($filename, mb_strtolower($writerType));
if (preg_match('/(mpdf|tcpdf)$/', $path)) {
$path .= '.pdf';
}
$writer = IOFactory::createWriter($spreadsheet, $writerType);
$writer->setIncludeCharts($withCharts);
if ($writerCallback !== null) {
$writerCallback($writer);
}
$callStartTime = microtime(true);
$writer->save($path);
$this->logWrite($writer, $path, $callStartTime);
if ($this->isCli() === false) {
// @codeCoverageIgnoreStart
echo '<a href="/download.php?type=' . pathinfo($path, PATHINFO_EXTENSION) . '&name=' . basename($path) . '">Download ' . basename($path) . '</a><br />';
// @codeCoverageIgnoreEnd
}
}
$this->logEndingNotes();
}
protected function isDirOrMkdir(string $folder): bool
{
return \is_dir($folder) || \mkdir($folder);
}
/**
* Returns the temporary directory and make sure it exists.
*/
public function getTemporaryFolder(): string
{
$tempFolder = sys_get_temp_dir() . '/phpspreadsheet';
if (!$this->isDirOrMkdir($tempFolder)) {
throw new RuntimeException(sprintf('Directory "%s" was not created', $tempFolder));
}
return $tempFolder;
}
/**
* Returns the filename that should be used for sample output.
*/
public function getFilename(string $filename, string $extension = 'xlsx'): string
{
$originalExtension = pathinfo($filename, PATHINFO_EXTENSION);
return $this->getTemporaryFolder() . '/' . str_replace('.' . $originalExtension, '.' . $extension, basename($filename));
}
/**
* Return a random temporary file name.
*/
public function getTemporaryFilename(string $extension = 'xlsx'): string
{
$temporaryFilename = tempnam($this->getTemporaryFolder(), 'phpspreadsheet-');
if ($temporaryFilename === false) {
// @codeCoverageIgnoreStart
throw new RuntimeException('tempnam returned false');
// @codeCoverageIgnoreEnd
}
unlink($temporaryFilename);
return $temporaryFilename . '.' . $extension;
}
public function log(mixed $message): void
{
$eol = $this->isCli() ? PHP_EOL : '<br />';
echo ($this->isCli() ? date('H:i:s ') : '') . StringHelper::convertToString($message) . $eol;
}
/**
* Render chart as part of running chart samples in browser.
* Charts are not rendered in unit tests, which are command line.
*
* @codeCoverageIgnore
*/
public function renderChart(Chart $chart, string $fileName, ?Spreadsheet $spreadsheet = null): void
{
if ($this->isCli() === true) {
return;
}
Settings::setChartRenderer(MtJpGraphRenderer::class);
$fileName = $this->getFilename($fileName, 'png');
$title = $chart->getTitle();
$caption = null;
if ($title !== null) {
$calculatedTitle = $title->getCalculatedTitle($spreadsheet);
if ($calculatedTitle !== null) {
$caption = $title->getCaption();
$title->setCaption($calculatedTitle);
}
}
try {
$chart->render($fileName);
$this->log('Rendered image: ' . $fileName);
$imageData = @file_get_contents($fileName);
if ($imageData !== false) {
echo '<div><img src="data:image/gif;base64,' . base64_encode($imageData) . '" /></div>';
} else {
$this->log('Unable to open chart' . PHP_EOL);
}
} catch (Throwable $e) {
$this->log('Error rendering chart: ' . $e->getMessage() . PHP_EOL);
}
if (isset($title, $caption)) {
$title->setCaption($caption);
}
Settings::unsetChartRenderer();
}
public function titles(string $category, string $functionName, ?string $description = null): void
{
$this->log(sprintf('%s Functions:', $category));
$description === null
? $this->log(sprintf('Function: %s()', rtrim($functionName, '()')))
: $this->log(sprintf('Function: %s() - %s.', rtrim($functionName, '()'), rtrim($description, '.')));
}
/** @param mixed[][] $matrix */
public function displayGrid(array $matrix, null|bool|TextGridRightAlign $numbersRight = null): void
{
$renderer = new TextGrid($matrix, $this->isCli());
if (is_bool($numbersRight)) {
$numbersRight = $numbersRight ? TextGridRightAlign::numeric : TextGridRightAlign::none;
}
if ($numbersRight !== null) {
$renderer->setNumbersRight($numbersRight);
}
echo $renderer->render();
}
public function logCalculationResult(
Worksheet $worksheet,
string $functionName,
string $formulaCell,
?string $descriptionCell = null
): void {
if ($descriptionCell !== null) {
$this->log($worksheet->getCell($descriptionCell)->getValueString());
}
$this->log($worksheet->getCell($formulaCell)->getValueString());
$this->log(sprintf('%s() Result is ', $functionName) . $worksheet->getCell($formulaCell)->getCalculatedValueString());
}
/**
* Log ending notes.
*/
public function logEndingNotes(): void
{
// Do not show execution time for index
$this->log('Peak memory usage: ' . (memory_get_peak_usage(true) / 1024 / 1024) . 'MB');
}
/**
* Log a line about the write operation.
*/
public function logWrite(IWriter $writer, string $path, float $callStartTime): void
{
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
$reflection = new ReflectionClass($writer);
$format = $reflection->getShortName();
$codePath = $this->isCli() ? $path : "<code>$path</code>";
$message = "Write {$format} format to {$codePath} in " . sprintf('%.4f', $callTime) . ' seconds';
$this->log($message);
}
/**
* Log a line about the read operation.
*/
public function logRead(string $format, string $path, float $callStartTime): void
{
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
$message = "Read {$format} format from <code>{$path}</code> in " . sprintf('%.4f', $callTime) . ' seconds';
$this->log($message);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Helper/TextGridRightAlign.php | src/PhpSpreadsheet/Helper/TextGridRightAlign.php | <?php
namespace PhpOffice\PhpSpreadsheet\Helper;
enum TextGridRightAlign
{
case none;
case numeric;
case floatOrInt;
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Helper/Html.php | src/PhpSpreadsheet/Helper/Html.php | <?php
namespace PhpOffice\PhpSpreadsheet\Helper;
use DOMAttr;
use DOMDocument;
use DOMElement;
use DOMNode;
use DOMText;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Font;
class Html
{
protected const COLOUR_MAP = [
'aliceblue' => 'f0f8ff',
'antiquewhite' => 'faebd7',
'antiquewhite1' => 'ffefdb',
'antiquewhite2' => 'eedfcc',
'antiquewhite3' => 'cdc0b0',
'antiquewhite4' => '8b8378',
'aqua' => '00ffff',
'aquamarine1' => '7fffd4',
'aquamarine2' => '76eec6',
'aquamarine4' => '458b74',
'azure1' => 'f0ffff',
'azure2' => 'e0eeee',
'azure3' => 'c1cdcd',
'azure4' => '838b8b',
'beige' => 'f5f5dc',
'bisque1' => 'ffe4c4',
'bisque2' => 'eed5b7',
'bisque3' => 'cdb79e',
'bisque4' => '8b7d6b',
'black' => '000000',
'blanchedalmond' => 'ffebcd',
'blue' => '0000ff',
'blue1' => '0000ff',
'blue2' => '0000ee',
'blue4' => '00008b',
'blueviolet' => '8a2be2',
'brown' => 'a52a2a',
'brown1' => 'ff4040',
'brown2' => 'ee3b3b',
'brown3' => 'cd3333',
'brown4' => '8b2323',
'burlywood' => 'deb887',
'burlywood1' => 'ffd39b',
'burlywood2' => 'eec591',
'burlywood3' => 'cdaa7d',
'burlywood4' => '8b7355',
'cadetblue' => '5f9ea0',
'cadetblue1' => '98f5ff',
'cadetblue2' => '8ee5ee',
'cadetblue3' => '7ac5cd',
'cadetblue4' => '53868b',
'chartreuse1' => '7fff00',
'chartreuse2' => '76ee00',
'chartreuse3' => '66cd00',
'chartreuse4' => '458b00',
'chocolate' => 'd2691e',
'chocolate1' => 'ff7f24',
'chocolate2' => 'ee7621',
'chocolate3' => 'cd661d',
'coral' => 'ff7f50',
'coral1' => 'ff7256',
'coral2' => 'ee6a50',
'coral3' => 'cd5b45',
'coral4' => '8b3e2f',
'cornflowerblue' => '6495ed',
'cornsilk1' => 'fff8dc',
'cornsilk2' => 'eee8cd',
'cornsilk3' => 'cdc8b1',
'cornsilk4' => '8b8878',
'cyan1' => '00ffff',
'cyan2' => '00eeee',
'cyan3' => '00cdcd',
'cyan4' => '008b8b',
'darkgoldenrod' => 'b8860b',
'darkgoldenrod1' => 'ffb90f',
'darkgoldenrod2' => 'eead0e',
'darkgoldenrod3' => 'cd950c',
'darkgoldenrod4' => '8b6508',
'darkgreen' => '006400',
'darkkhaki' => 'bdb76b',
'darkolivegreen' => '556b2f',
'darkolivegreen1' => 'caff70',
'darkolivegreen2' => 'bcee68',
'darkolivegreen3' => 'a2cd5a',
'darkolivegreen4' => '6e8b3d',
'darkorange' => 'ff8c00',
'darkorange1' => 'ff7f00',
'darkorange2' => 'ee7600',
'darkorange3' => 'cd6600',
'darkorange4' => '8b4500',
'darkorchid' => '9932cc',
'darkorchid1' => 'bf3eff',
'darkorchid2' => 'b23aee',
'darkorchid3' => '9a32cd',
'darkorchid4' => '68228b',
'darksalmon' => 'e9967a',
'darkseagreen' => '8fbc8f',
'darkseagreen1' => 'c1ffc1',
'darkseagreen2' => 'b4eeb4',
'darkseagreen3' => '9bcd9b',
'darkseagreen4' => '698b69',
'darkslateblue' => '483d8b',
'darkslategray' => '2f4f4f',
'darkslategray1' => '97ffff',
'darkslategray2' => '8deeee',
'darkslategray3' => '79cdcd',
'darkslategray4' => '528b8b',
'darkturquoise' => '00ced1',
'darkviolet' => '9400d3',
'deeppink1' => 'ff1493',
'deeppink2' => 'ee1289',
'deeppink3' => 'cd1076',
'deeppink4' => '8b0a50',
'deepskyblue1' => '00bfff',
'deepskyblue2' => '00b2ee',
'deepskyblue3' => '009acd',
'deepskyblue4' => '00688b',
'dimgray' => '696969',
'dodgerblue1' => '1e90ff',
'dodgerblue2' => '1c86ee',
'dodgerblue3' => '1874cd',
'dodgerblue4' => '104e8b',
'firebrick' => 'b22222',
'firebrick1' => 'ff3030',
'firebrick2' => 'ee2c2c',
'firebrick3' => 'cd2626',
'firebrick4' => '8b1a1a',
'floralwhite' => 'fffaf0',
'forestgreen' => '228b22',
'fuchsia' => 'ff00ff',
'gainsboro' => 'dcdcdc',
'ghostwhite' => 'f8f8ff',
'gold1' => 'ffd700',
'gold2' => 'eec900',
'gold3' => 'cdad00',
'gold4' => '8b7500',
'goldenrod' => 'daa520',
'goldenrod1' => 'ffc125',
'goldenrod2' => 'eeb422',
'goldenrod3' => 'cd9b1d',
'goldenrod4' => '8b6914',
'gray' => 'bebebe',
'gray1' => '030303',
'gray10' => '1a1a1a',
'gray11' => '1c1c1c',
'gray12' => '1f1f1f',
'gray13' => '212121',
'gray14' => '242424',
'gray15' => '262626',
'gray16' => '292929',
'gray17' => '2b2b2b',
'gray18' => '2e2e2e',
'gray19' => '303030',
'gray2' => '050505',
'gray20' => '333333',
'gray21' => '363636',
'gray22' => '383838',
'gray23' => '3b3b3b',
'gray24' => '3d3d3d',
'gray25' => '404040',
'gray26' => '424242',
'gray27' => '454545',
'gray28' => '474747',
'gray29' => '4a4a4a',
'gray3' => '080808',
'gray30' => '4d4d4d',
'gray31' => '4f4f4f',
'gray32' => '525252',
'gray33' => '545454',
'gray34' => '575757',
'gray35' => '595959',
'gray36' => '5c5c5c',
'gray37' => '5e5e5e',
'gray38' => '616161',
'gray39' => '636363',
'gray4' => '0a0a0a',
'gray40' => '666666',
'gray41' => '696969',
'gray42' => '6b6b6b',
'gray43' => '6e6e6e',
'gray44' => '707070',
'gray45' => '737373',
'gray46' => '757575',
'gray47' => '787878',
'gray48' => '7a7a7a',
'gray49' => '7d7d7d',
'gray5' => '0d0d0d',
'gray50' => '7f7f7f',
'gray51' => '828282',
'gray52' => '858585',
'gray53' => '878787',
'gray54' => '8a8a8a',
'gray55' => '8c8c8c',
'gray56' => '8f8f8f',
'gray57' => '919191',
'gray58' => '949494',
'gray59' => '969696',
'gray6' => '0f0f0f',
'gray60' => '999999',
'gray61' => '9c9c9c',
'gray62' => '9e9e9e',
'gray63' => 'a1a1a1',
'gray64' => 'a3a3a3',
'gray65' => 'a6a6a6',
'gray66' => 'a8a8a8',
'gray67' => 'ababab',
'gray68' => 'adadad',
'gray69' => 'b0b0b0',
'gray7' => '121212',
'gray70' => 'b3b3b3',
'gray71' => 'b5b5b5',
'gray72' => 'b8b8b8',
'gray73' => 'bababa',
'gray74' => 'bdbdbd',
'gray75' => 'bfbfbf',
'gray76' => 'c2c2c2',
'gray77' => 'c4c4c4',
'gray78' => 'c7c7c7',
'gray79' => 'c9c9c9',
'gray8' => '141414',
'gray80' => 'cccccc',
'gray81' => 'cfcfcf',
'gray82' => 'd1d1d1',
'gray83' => 'd4d4d4',
'gray84' => 'd6d6d6',
'gray85' => 'd9d9d9',
'gray86' => 'dbdbdb',
'gray87' => 'dedede',
'gray88' => 'e0e0e0',
'gray89' => 'e3e3e3',
'gray9' => '171717',
'gray90' => 'e5e5e5',
'gray91' => 'e8e8e8',
'gray92' => 'ebebeb',
'gray93' => 'ededed',
'gray94' => 'f0f0f0',
'gray95' => 'f2f2f2',
'gray97' => 'f7f7f7',
'gray98' => 'fafafa',
'gray99' => 'fcfcfc',
'green' => '00ff00',
'green1' => '00ff00',
'green2' => '00ee00',
'green3' => '00cd00',
'green4' => '008b00',
'greenyellow' => 'adff2f',
'honeydew1' => 'f0fff0',
'honeydew2' => 'e0eee0',
'honeydew3' => 'c1cdc1',
'honeydew4' => '838b83',
'hotpink' => 'ff69b4',
'hotpink1' => 'ff6eb4',
'hotpink2' => 'ee6aa7',
'hotpink3' => 'cd6090',
'hotpink4' => '8b3a62',
'indianred' => 'cd5c5c',
'indianred1' => 'ff6a6a',
'indianred2' => 'ee6363',
'indianred3' => 'cd5555',
'indianred4' => '8b3a3a',
'ivory1' => 'fffff0',
'ivory2' => 'eeeee0',
'ivory3' => 'cdcdc1',
'ivory4' => '8b8b83',
'khaki' => 'f0e68c',
'khaki1' => 'fff68f',
'khaki2' => 'eee685',
'khaki3' => 'cdc673',
'khaki4' => '8b864e',
'lavender' => 'e6e6fa',
'lavenderblush1' => 'fff0f5',
'lavenderblush2' => 'eee0e5',
'lavenderblush3' => 'cdc1c5',
'lavenderblush4' => '8b8386',
'lawngreen' => '7cfc00',
'lemonchiffon1' => 'fffacd',
'lemonchiffon2' => 'eee9bf',
'lemonchiffon3' => 'cdc9a5',
'lemonchiffon4' => '8b8970',
'light' => 'eedd82',
'lightblue' => 'add8e6',
'lightblue1' => 'bfefff',
'lightblue2' => 'b2dfee',
'lightblue3' => '9ac0cd',
'lightblue4' => '68838b',
'lightcoral' => 'f08080',
'lightcyan1' => 'e0ffff',
'lightcyan2' => 'd1eeee',
'lightcyan3' => 'b4cdcd',
'lightcyan4' => '7a8b8b',
'lightgoldenrod1' => 'ffec8b',
'lightgoldenrod2' => 'eedc82',
'lightgoldenrod3' => 'cdbe70',
'lightgoldenrod4' => '8b814c',
'lightgoldenrodyellow' => 'fafad2',
'lightgray' => 'd3d3d3',
'lightpink' => 'ffb6c1',
'lightpink1' => 'ffaeb9',
'lightpink2' => 'eea2ad',
'lightpink3' => 'cd8c95',
'lightpink4' => '8b5f65',
'lightsalmon1' => 'ffa07a',
'lightsalmon2' => 'ee9572',
'lightsalmon3' => 'cd8162',
'lightsalmon4' => '8b5742',
'lightseagreen' => '20b2aa',
'lightskyblue' => '87cefa',
'lightskyblue1' => 'b0e2ff',
'lightskyblue2' => 'a4d3ee',
'lightskyblue3' => '8db6cd',
'lightskyblue4' => '607b8b',
'lightslateblue' => '8470ff',
'lightslategray' => '778899',
'lightsteelblue' => 'b0c4de',
'lightsteelblue1' => 'cae1ff',
'lightsteelblue2' => 'bcd2ee',
'lightsteelblue3' => 'a2b5cd',
'lightsteelblue4' => '6e7b8b',
'lightyellow1' => 'ffffe0',
'lightyellow2' => 'eeeed1',
'lightyellow3' => 'cdcdb4',
'lightyellow4' => '8b8b7a',
'lime' => '00ff00',
'limegreen' => '32cd32',
'linen' => 'faf0e6',
'magenta' => 'ff00ff',
'magenta2' => 'ee00ee',
'magenta3' => 'cd00cd',
'magenta4' => '8b008b',
'maroon' => 'b03060',
'maroon1' => 'ff34b3',
'maroon2' => 'ee30a7',
'maroon3' => 'cd2990',
'maroon4' => '8b1c62',
'medium' => '66cdaa',
'mediumaquamarine' => '66cdaa',
'mediumblue' => '0000cd',
'mediumorchid' => 'ba55d3',
'mediumorchid1' => 'e066ff',
'mediumorchid2' => 'd15fee',
'mediumorchid3' => 'b452cd',
'mediumorchid4' => '7a378b',
'mediumpurple' => '9370db',
'mediumpurple1' => 'ab82ff',
'mediumpurple2' => '9f79ee',
'mediumpurple3' => '8968cd',
'mediumpurple4' => '5d478b',
'mediumseagreen' => '3cb371',
'mediumslateblue' => '7b68ee',
'mediumspringgreen' => '00fa9a',
'mediumturquoise' => '48d1cc',
'mediumvioletred' => 'c71585',
'midnightblue' => '191970',
'mintcream' => 'f5fffa',
'mistyrose1' => 'ffe4e1',
'mistyrose2' => 'eed5d2',
'mistyrose3' => 'cdb7b5',
'mistyrose4' => '8b7d7b',
'moccasin' => 'ffe4b5',
'navajowhite1' => 'ffdead',
'navajowhite2' => 'eecfa1',
'navajowhite3' => 'cdb38b',
'navajowhite4' => '8b795e',
'navy' => '000080',
'navyblue' => '000080',
'oldlace' => 'fdf5e6',
'olive' => '808000',
'olivedrab' => '6b8e23',
'olivedrab1' => 'c0ff3e',
'olivedrab2' => 'b3ee3a',
'olivedrab4' => '698b22',
'orange' => 'ffa500',
'orange1' => 'ffa500',
'orange2' => 'ee9a00',
'orange3' => 'cd8500',
'orange4' => '8b5a00',
'orangered1' => 'ff4500',
'orangered2' => 'ee4000',
'orangered3' => 'cd3700',
'orangered4' => '8b2500',
'orchid' => 'da70d6',
'orchid1' => 'ff83fa',
'orchid2' => 'ee7ae9',
'orchid3' => 'cd69c9',
'orchid4' => '8b4789',
'pale' => 'db7093',
'palegoldenrod' => 'eee8aa',
'palegreen' => '98fb98',
'palegreen1' => '9aff9a',
'palegreen2' => '90ee90',
'palegreen3' => '7ccd7c',
'palegreen4' => '548b54',
'paleturquoise' => 'afeeee',
'paleturquoise1' => 'bbffff',
'paleturquoise2' => 'aeeeee',
'paleturquoise3' => '96cdcd',
'paleturquoise4' => '668b8b',
'palevioletred' => 'db7093',
'palevioletred1' => 'ff82ab',
'palevioletred2' => 'ee799f',
'palevioletred3' => 'cd6889',
'palevioletred4' => '8b475d',
'papayawhip' => 'ffefd5',
'peachpuff1' => 'ffdab9',
'peachpuff2' => 'eecbad',
'peachpuff3' => 'cdaf95',
'peachpuff4' => '8b7765',
'pink' => 'ffc0cb',
'pink1' => 'ffb5c5',
'pink2' => 'eea9b8',
'pink3' => 'cd919e',
'pink4' => '8b636c',
'plum' => 'dda0dd',
'plum1' => 'ffbbff',
'plum2' => 'eeaeee',
'plum3' => 'cd96cd',
'plum4' => '8b668b',
'powderblue' => 'b0e0e6',
'purple' => 'a020f0',
'rebeccapurple' => '663399',
'purple1' => '9b30ff',
'purple2' => '912cee',
'purple3' => '7d26cd',
'purple4' => '551a8b',
'red' => 'ff0000',
'red1' => 'ff0000',
'red2' => 'ee0000',
'red3' => 'cd0000',
'red4' => '8b0000',
'rosybrown' => 'bc8f8f',
'rosybrown1' => 'ffc1c1',
'rosybrown2' => 'eeb4b4',
'rosybrown3' => 'cd9b9b',
'rosybrown4' => '8b6969',
'royalblue' => '4169e1',
'royalblue1' => '4876ff',
'royalblue2' => '436eee',
'royalblue3' => '3a5fcd',
'royalblue4' => '27408b',
'saddlebrown' => '8b4513',
'salmon' => 'fa8072',
'salmon1' => 'ff8c69',
'salmon2' => 'ee8262',
'salmon3' => 'cd7054',
'salmon4' => '8b4c39',
'sandybrown' => 'f4a460',
'seagreen1' => '54ff9f',
'seagreen2' => '4eee94',
'seagreen3' => '43cd80',
'seagreen4' => '2e8b57',
'seashell1' => 'fff5ee',
'seashell2' => 'eee5de',
'seashell3' => 'cdc5bf',
'seashell4' => '8b8682',
'sienna' => 'a0522d',
'sienna1' => 'ff8247',
'sienna2' => 'ee7942',
'sienna3' => 'cd6839',
'sienna4' => '8b4726',
'silver' => 'c0c0c0',
'skyblue' => '87ceeb',
'skyblue1' => '87ceff',
'skyblue2' => '7ec0ee',
'skyblue3' => '6ca6cd',
'skyblue4' => '4a708b',
'slateblue' => '6a5acd',
'slateblue1' => '836fff',
'slateblue2' => '7a67ee',
'slateblue3' => '6959cd',
'slateblue4' => '473c8b',
'slategray' => '708090',
'slategray1' => 'c6e2ff',
'slategray2' => 'b9d3ee',
'slategray3' => '9fb6cd',
'slategray4' => '6c7b8b',
'snow1' => 'fffafa',
'snow2' => 'eee9e9',
'snow3' => 'cdc9c9',
'snow4' => '8b8989',
'springgreen1' => '00ff7f',
'springgreen2' => '00ee76',
'springgreen3' => '00cd66',
'springgreen4' => '008b45',
'steelblue' => '4682b4',
'steelblue1' => '63b8ff',
'steelblue2' => '5cacee',
'steelblue3' => '4f94cd',
'steelblue4' => '36648b',
'tan' => 'd2b48c',
'tan1' => 'ffa54f',
'tan2' => 'ee9a49',
'tan3' => 'cd853f',
'tan4' => '8b5a2b',
'teal' => '008080',
'thistle' => 'd8bfd8',
'thistle1' => 'ffe1ff',
'thistle2' => 'eed2ee',
'thistle3' => 'cdb5cd',
'thistle4' => '8b7b8b',
'tomato1' => 'ff6347',
'tomato2' => 'ee5c42',
'tomato3' => 'cd4f39',
'tomato4' => '8b3626',
'turquoise' => '40e0d0',
'turquoise1' => '00f5ff',
'turquoise2' => '00e5ee',
'turquoise3' => '00c5cd',
'turquoise4' => '00868b',
'violet' => 'ee82ee',
'violetred' => 'd02090',
'violetred1' => 'ff3e96',
'violetred2' => 'ee3a8c',
'violetred3' => 'cd3278',
'violetred4' => '8b2252',
'wheat' => 'f5deb3',
'wheat1' => 'ffe7ba',
'wheat2' => 'eed8ae',
'wheat3' => 'cdba96',
'wheat4' => '8b7e66',
'white' => 'ffffff',
'whitesmoke' => 'f5f5f5',
'yellow' => 'ffff00',
'yellow1' => 'ffff00',
'yellow2' => 'eeee00',
'yellow3' => 'cdcd00',
'yellow4' => '8b8b00',
'yellowgreen' => '9acd32',
];
private ?string $face = null;
private ?string $size = null;
private ?string $color = null;
private bool $bold = false;
private bool $italic = false;
private bool $underline = false;
private bool $superscript = false;
private bool $subscript = false;
private bool $strikethrough = false;
/** @var callable[] */
protected array $startTagCallbacks;
/** @var callable[] */
protected array $endTagCallbacks;
/** @var mixed[] */
private array $stack = [];
public string $stringData = '';
private RichText $richTextObject;
private bool $preserveWhiteSpace = false;
public function __construct()
{
if (!isset($this->startTagCallbacks)) {
$this->startTagCallbacks = [
'font' => $this->startFontTag(...),
'b' => $this->startBoldTag(...),
'strong' => $this->startBoldTag(...),
'i' => $this->startItalicTag(...),
'em' => $this->startItalicTag(...),
'u' => $this->startUnderlineTag(...),
'ins' => $this->startUnderlineTag(...),
'del' => $this->startStrikethruTag(...),
's' => $this->startStrikethruTag(...),
'sup' => $this->startSuperscriptTag(...),
'sub' => $this->startSubscriptTag(...),
];
}
if (!isset($this->endTagCallbacks)) {
$this->endTagCallbacks = [
'font' => $this->endFontTag(...),
'b' => $this->endBoldTag(...),
'strong' => $this->endBoldTag(...),
'i' => $this->endItalicTag(...),
'em' => $this->endItalicTag(...),
'u' => $this->endUnderlineTag(...),
'ins' => $this->endUnderlineTag(...),
'del' => $this->endStrikethruTag(...),
's' => $this->endStrikethruTag(...),
'sup' => $this->endSuperscriptTag(...),
'sub' => $this->endSubscriptTag(...),
'br' => $this->breakTag(...),
'p' => $this->breakTag(...),
'h1' => $this->breakTag(...),
'h2' => $this->breakTag(...),
'h3' => $this->breakTag(...),
'h4' => $this->breakTag(...),
'h5' => $this->breakTag(...),
'h6' => $this->breakTag(...),
];
}
}
private function initialise(): void
{
$this->face = $this->size = $this->color = null;
$this->bold = $this->italic = $this->underline = $this->superscript = $this->subscript = $this->strikethrough = false;
$this->stack = [];
$this->stringData = '';
}
/**
* Parse HTML formatting and return the resulting RichText.
*/
public function toRichTextObject(string $html, bool $preserveWhiteSpace = false): RichText
{
$this->initialise();
// Create a new DOM object
$dom = new DOMDocument();
// Load the HTML file into the DOM object
// Note the use of error suppression, because typically this will be an html fragment, so not fully valid markup
$prefix = '<?xml encoding="UTF-8">';
@$dom->loadHTML($prefix . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
// Discard excess white space
$dom->preserveWhiteSpace = false;
$this->richTextObject = new RichText();
$this->preserveWhiteSpace = $preserveWhiteSpace;
$this->parseElements($dom);
$this->preserveWhiteSpace = false;
// Clean any further spurious whitespace
$this->cleanWhitespace();
return $this->richTextObject;
}
private function cleanWhitespace(): void
{
foreach ($this->richTextObject->getRichTextElements() as $key => $element) {
$text = $element->getText();
// Trim any leading spaces on the first run
if ($key == 0) {
$text = ltrim($text);
}
// Trim any spaces immediately after a line break
$text = (string) preg_replace('/\n */mu', "\n", $text);
$element->setText($text);
}
}
private function buildTextRun(): void
{
$text = $this->stringData;
if (trim($text) === '') {
return;
}
$richtextRun = $this->richTextObject->createTextRun($this->stringData);
$font = $richtextRun->getFont();
if ($font !== null) {
if ($this->face) {
$font->setName($this->face);
}
if ($this->size) {
$font->setSize($this->size);
}
if ($this->color) {
$font->setColor(new Color('ff' . $this->color));
}
if ($this->bold) {
$font->setBold(true);
}
if ($this->italic) {
$font->setItalic(true);
}
if ($this->underline) {
$font->setUnderline(Font::UNDERLINE_SINGLE);
}
if ($this->superscript) {
$font->setSuperscript(true);
}
if ($this->subscript) {
$font->setSubscript(true);
}
if ($this->strikethrough) {
$font->setStrikethrough(true);
}
}
$this->stringData = '';
}
private function rgbToColour(string $rgbValue): string
{
preg_match_all('/\d+/', $rgbValue, $values);
foreach ($values[0] as &$value) {
$value = str_pad(dechex((int) $value), 2, '0', STR_PAD_LEFT);
}
return implode('', $values[0]);
}
public static function colourNameLookup(string $colorName): string
{
/** @var string[] */
$temp = static::COLOUR_MAP;
return $temp[$colorName] ?? '';
}
protected function startFontTag(DOMElement $tag): void
{
$attrs = $tag->attributes ?? [];
/** @var DOMAttr $attribute */
foreach ($attrs as $attribute) {
$attributeName = strtolower($attribute->name);
$attributeName = preg_replace('/^html:/', '', $attributeName) ?? $attributeName; // in case from Xml spreadsheet
$attributeValue = $attribute->value;
if ($attributeName === 'color') {
if (preg_match('/rgb\s*\(/', $attributeValue)) {
$this->$attributeName = $this->rgbToColour($attributeValue);
} elseif (str_starts_with(trim($attributeValue), '#')) {
$this->$attributeName = ltrim($attributeValue, '#');
} else {
$this->$attributeName = static::colourNameLookup($attributeValue);
}
} elseif ($attributeName === 'face' || $attributeName === 'size') {
$this->$attributeName = $attributeValue;
}
}
}
protected function endFontTag(): void
{
$this->face = $this->size = $this->color = null;
}
protected function startBoldTag(): void
{
$this->bold = true;
}
protected function endBoldTag(): void
{
$this->bold = false;
}
protected function startItalicTag(): void
{
$this->italic = true;
}
protected function endItalicTag(): void
{
$this->italic = false;
}
protected function startUnderlineTag(): void
{
$this->underline = true;
}
protected function endUnderlineTag(): void
{
$this->underline = false;
}
protected function startSubscriptTag(): void
{
$this->subscript = true;
}
protected function endSubscriptTag(): void
{
$this->subscript = false;
}
protected function startSuperscriptTag(): void
{
$this->superscript = true;
}
protected function endSuperscriptTag(): void
{
$this->superscript = false;
}
protected function startStrikethruTag(): void
{
$this->strikethrough = true;
}
protected function endStrikethruTag(): void
{
$this->strikethrough = false;
}
public function breakTag(): void
{
$this->stringData .= "\n";
}
private function parseTextNode(DOMText $textNode): void
{
if ($this->preserveWhiteSpace) {
$domText = $textNode->nodeValue ?? '';
} else {
$domText = (string) preg_replace(
'/\s+/u',
' ',
str_replace(["\r", "\n"], ' ', $textNode->nodeValue ?? '')
);
}
$this->stringData .= $domText;
$this->buildTextRun();
}
public function addStartTagCallback(string $tag, callable $callback): void
{
$this->startTagCallbacks[$tag] = $callback;
}
public function addEndTagCallback(string $tag, callable $callback): void
{
$this->endTagCallbacks[$tag] = $callback;
}
/** @param callable[] $callbacks */
private function handleCallback(DOMElement $element, string $callbackTag, array $callbacks): void
{
if (isset($callbacks[$callbackTag])) {
$elementHandler = $callbacks[$callbackTag];
call_user_func($elementHandler, $element, $this);
}
}
private function parseElementNode(DOMElement $element): void
{
$callbackTag = strtolower($element->nodeName);
$this->stack[] = $callbackTag;
$this->handleCallback($element, $callbackTag, $this->startTagCallbacks);
$this->parseElements($element);
array_pop($this->stack);
$this->handleCallback($element, $callbackTag, $this->endTagCallbacks);
}
private function parseElements(DOMNode $element): void
{
foreach ($element->childNodes as $child) {
if ($child instanceof DOMText) {
$this->parseTextNode($child);
} elseif ($child instanceof DOMElement) {
$this->parseElementNode($child);
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Helper/TextGrid.php | src/PhpSpreadsheet/Helper/TextGrid.php | <?php
namespace PhpOffice\PhpSpreadsheet\Helper;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
class TextGrid
{
protected bool $isCli;
/** @var mixed[][] */
protected array $matrix;
/** @var int[] */
protected array $rows;
/** @var string[] */
protected array $columns;
protected string $gridDisplay;
protected bool $rowDividers = false;
protected bool $rowHeaders = true;
protected bool $columnHeaders = true;
protected TextGridRightAlign $numbersRight = TextGridRightAlign::none;
/** @param mixed[][] $matrix */
public function __construct(array $matrix, bool $isCli = true, bool $rowDividers = false, bool $rowHeaders = true, bool $columnHeaders = true, TextGridRightAlign $numbersRight = TextGridRightAlign::none)
{
$this->rows = array_keys($matrix);
$this->columns = array_keys($matrix[$this->rows[0]]);
$matrix = array_values($matrix);
array_walk(
$matrix,
function (&$row): void {
$row = array_values($row);
}
);
$this->matrix = $matrix;
$this->isCli = $isCli;
$this->rowDividers = $rowDividers;
$this->rowHeaders = $rowHeaders;
$this->columnHeaders = $columnHeaders;
$this->numbersRight = $numbersRight;
}
public function setNumbersRight(TextGridRightAlign $numbersRight): void
{
$this->numbersRight = $numbersRight;
}
public function render(): string
{
$this->gridDisplay = $this->isCli ? '' : ('<pre>' . PHP_EOL);
if (!empty($this->rows)) {
$maxRow = max($this->rows);
$maxRowLength = $this->strlen((string) $maxRow) + 1;
$columnWidths = $this->getColumnWidths();
$this->renderColumnHeader($maxRowLength, $columnWidths);
$this->renderRows($maxRowLength, $columnWidths);
if (!$this->rowDividers) {
$this->renderFooter($maxRowLength, $columnWidths);
}
}
$this->gridDisplay .= $this->isCli ? '' : '</pre>';
return $this->gridDisplay;
}
/** @param int[] $columnWidths */
protected function renderRows(int $maxRowLength, array $columnWidths): void
{
foreach ($this->matrix as $row => $rowData) {
if ($this->rowHeaders) {
$this->gridDisplay .= '|' . str_pad((string) $this->rows[$row], $maxRowLength, ' ', STR_PAD_LEFT) . ' ';
}
$this->renderCells($rowData, $columnWidths);
$this->gridDisplay .= '|' . PHP_EOL;
if ($this->rowDividers) {
$this->renderFooter($maxRowLength, $columnWidths);
}
}
}
/**
* @param mixed[] $rowData
* @param int[] $columnWidths
*/
protected function renderCells(array $rowData, array $columnWidths): void
{
foreach ($rowData as $column => $cell) {
$valueForLength = $this->getString($cell);
$displayCell = $this->isCli ? $valueForLength : htmlentities($valueForLength);
$this->gridDisplay .= '| ';
if ($this->rightAlign($displayCell, $cell)) {
$this->gridDisplay .= str_repeat(' ', $columnWidths[$column] - $this->strlen($valueForLength)) . $displayCell . ' ';
} else {
$this->gridDisplay .= $displayCell . str_repeat(' ', $columnWidths[$column] - $this->strlen($valueForLength) + 1);
}
}
}
protected function rightAlign(string $displayCell, mixed $cell = null): bool
{
return ($this->numbersRight === TextGridRightAlign::numeric && is_numeric($displayCell)) || ($this->numbersRight === TextGridRightAlign::floatOrInt && (is_int($cell) || is_float($cell)));
}
/** @param int[] $columnWidths */
protected function renderColumnHeader(int $maxRowLength, array &$columnWidths): void
{
if (!$this->columnHeaders) {
$this->renderFooter($maxRowLength, $columnWidths);
return;
}
foreach ($this->columns as $column => $reference) {
/** @var string $reference */
$columnWidths[$column] = max($columnWidths[$column], $this->strlen($reference));
}
if ($this->rowHeaders) {
$this->gridDisplay .= str_repeat(' ', $maxRowLength + 2);
}
foreach ($this->columns as $column => $reference) {
$this->gridDisplay .= '+-' . str_repeat('-', $columnWidths[$column] + 1);
}
$this->gridDisplay .= '+' . PHP_EOL;
if ($this->rowHeaders) {
$this->gridDisplay .= str_repeat(' ', $maxRowLength + 2);
}
foreach ($this->columns as $column => $reference) {
/** @var scalar $reference */
$this->gridDisplay .= '| ' . str_pad((string) $reference, $columnWidths[$column] + 1, ' ');
}
$this->gridDisplay .= '|' . PHP_EOL;
$this->renderFooter($maxRowLength, $columnWidths);
}
/** @param int[] $columnWidths */
protected function renderFooter(int $maxRowLength, array $columnWidths): void
{
if ($this->rowHeaders) {
$this->gridDisplay .= '+' . str_repeat('-', $maxRowLength + 1);
}
foreach ($this->columns as $column => $reference) {
$this->gridDisplay .= '+-';
$this->gridDisplay .= str_pad((string) '', $columnWidths[$column] + 1, '-');
}
$this->gridDisplay .= '+' . PHP_EOL;
}
/** @return int[] */
protected function getColumnWidths(): array
{
$columnCount = count($this->matrix, COUNT_RECURSIVE) / count($this->matrix);
$columnWidths = [];
for ($column = 0; $column < $columnCount; ++$column) {
$columnWidths[] = $this->getColumnWidth(array_column($this->matrix, $column));
}
return $columnWidths;
}
/** @param mixed[] $columnData */
protected function getColumnWidth(array $columnData): int
{
$columnWidth = 0;
$columnData = array_values($columnData);
foreach ($columnData as $columnValue) {
$columnWidth = max($columnWidth, $this->strlen($this->getString($columnValue)));
}
return $columnWidth;
}
protected function getString(mixed $value): string
{
return StringHelper::convertToString($value, convertBool: true);
}
protected function strlen(string $value): int
{
return mb_strlen($value);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/ColumnRange.php | src/PhpSpreadsheet/Cell/ColumnRange.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Stringable;
/**
* @implements AddressRange<string>
*/
class ColumnRange implements AddressRange, Stringable
{
protected ?Worksheet $worksheet;
protected int $from;
protected int $to;
public function __construct(string $from, ?string $to = null, ?Worksheet $worksheet = null)
{
$this->validateFromTo(
Coordinate::columnIndexFromString($from),
Coordinate::columnIndexFromString($to ?? $from)
);
$this->worksheet = $worksheet;
}
public function __destruct()
{
$this->worksheet = null;
}
public static function fromColumnIndexes(int $from, int $to, ?Worksheet $worksheet = null): self
{
return new self(Coordinate::stringFromColumnIndex($from), Coordinate::stringFromColumnIndex($to), $worksheet);
}
/**
* @param array<int|string> $array
*/
public static function fromArray(array $array, ?Worksheet $worksheet = null): self
{
array_walk(
$array,
function (&$column): void {
$column = is_numeric($column) ? Coordinate::stringFromColumnIndex((int) $column) : $column;
}
);
/** @var string $from */
/** @var string $to */
[$from, $to] = $array;
return new self($from, $to, $worksheet);
}
private function validateFromTo(int $from, int $to): void
{
// Identify actual top and bottom values (in case we've been given bottom and top)
$this->from = min($from, $to);
$this->to = max($from, $to);
}
public function columnCount(): int
{
return $this->to - $this->from + 1;
}
public function shiftDown(int $offset = 1): self
{
$newFrom = $this->from + $offset;
$newFrom = ($newFrom < 1) ? 1 : $newFrom;
$newTo = $this->to + $offset;
$newTo = ($newTo < 1) ? 1 : $newTo;
return self::fromColumnIndexes($newFrom, $newTo, $this->worksheet);
}
public function shiftUp(int $offset = 1): self
{
return $this->shiftDown(0 - $offset);
}
public function from(): string
{
return Coordinate::stringFromColumnIndex($this->from);
}
public function to(): string
{
return Coordinate::stringFromColumnIndex($this->to);
}
public function fromIndex(): int
{
return $this->from;
}
public function toIndex(): int
{
return $this->to;
}
public function toCellRange(): CellRange
{
return new CellRange(
CellAddress::fromColumnAndRow($this->from, 1, $this->worksheet),
CellAddress::fromColumnAndRow($this->to, AddressRange::MAX_ROW)
);
}
public function __toString(): string
{
$from = $this->from();
$to = $this->to();
if ($this->worksheet !== null) {
$title = str_replace("'", "''", $this->worksheet->getTitle());
return "'{$title}'!{$from}:{$to}";
}
return "{$from}:{$to}";
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/Cell.php | src/PhpSpreadsheet/Cell/Cell.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalculationException;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
use PhpOffice\PhpSpreadsheet\Collection\Cells;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDate;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\CellStyleAssessor;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Protection;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Stringable;
class Cell implements Stringable
{
/**
* Value binder to use.
*/
private static ?IValueBinder $valueBinder = null;
/**
* Value of the cell.
*/
private mixed $value;
/**
* Calculated value of the cell (used for caching)
* This returns the value last calculated by MS Excel or whichever spreadsheet program was used to
* create the original spreadsheet file.
* Note that this value is not guaranteed to reflect the actual calculated value because it is
* possible that auto-calculation was disabled in the original spreadsheet, and underlying data
* values used by the formula have changed since it was last calculated.
*
* @var mixed
*/
private $calculatedValue;
/**
* Type of the cell data.
*/
private string $dataType;
/**
* The collection of cells that this cell belongs to (i.e. The Cell Collection for the parent Worksheet).
*/
private ?Cells $parent;
/**
* Index to the cellXf reference for the styling of this cell.
*/
private int $xfIndex = 0;
/**
* Attributes of the formula.
*
* @var null|array<string, string>
*/
private ?array $formulaAttributes = null;
private IgnoredErrors $ignoredErrors;
/**
* Update the cell into the cell collection.
*
* @throws SpreadsheetException
*/
public function updateInCollection(): self
{
$parent = $this->parent;
if ($parent === null) {
throw new SpreadsheetException('Cannot update when cell is not bound to a worksheet');
}
$parent->update($this);
return $this;
}
public function detach(): void
{
$this->parent = null;
}
public function attach(Cells $parent): void
{
$this->parent = $parent;
}
/**
* Create a new Cell.
*
* @throws SpreadsheetException
*/
public function __construct(mixed $value, ?string $dataType, Worksheet $worksheet)
{
// Initialise cell value
$this->value = $value;
// Set worksheet cache
$this->parent = $worksheet->getCellCollection();
// Set datatype?
if ($dataType !== null) {
if ($dataType == DataType::TYPE_STRING2) {
$dataType = DataType::TYPE_STRING;
}
$this->dataType = $dataType;
} else {
$valueBinder = $worksheet->getParent()?->getValueBinder() ?? self::getValueBinder();
if ($valueBinder->bindValue($this, $value) === false) {
throw new SpreadsheetException('Value could not be bound to cell.');
}
}
$this->ignoredErrors = new IgnoredErrors();
}
/**
* Get cell coordinate column.
*
* @throws SpreadsheetException
*/
public function getColumn(): string
{
$parent = $this->parent;
if ($parent === null) {
throw new SpreadsheetException('Cannot get column when cell is not bound to a worksheet');
}
return $parent->getCurrentColumn();
}
/**
* Get cell coordinate row.
*
* @throws SpreadsheetException
*/
public function getRow(): int
{
$parent = $this->parent;
if ($parent === null) {
throw new SpreadsheetException('Cannot get row when cell is not bound to a worksheet');
}
return $parent->getCurrentRow();
}
/**
* Get cell coordinate.
*
* @throws SpreadsheetException
*/
public function getCoordinate(): string
{
$parent = $this->parent;
if ($parent !== null) {
$coordinate = $parent->getCurrentCoordinate();
} else {
$coordinate = null;
}
if ($coordinate === null) {
throw new SpreadsheetException('Coordinate no longer exists');
}
return $coordinate;
}
/**
* Get cell value.
*/
public function getValue(): mixed
{
return $this->value;
}
public function getValueString(): string
{
return StringHelper::convertToString($this->value, false);
}
/**
* Get cell value with formatting.
*/
public function getFormattedValue(): string
{
$currentCalendar = SharedDate::getExcelCalendar();
SharedDate::setExcelCalendar($this->getWorksheet()->getParent()?->getExcelCalendar());
$formattedValue = (string) NumberFormat::toFormattedString(
$this->getCalculatedValueString(),
(string) $this->getStyle()->getNumberFormat()->getFormatCode(true)
);
SharedDate::setExcelCalendar($currentCalendar);
return $formattedValue;
}
protected static function updateIfCellIsTableHeader(?Worksheet $workSheet, self $cell, mixed $oldValue, mixed $newValue): void
{
$oldValue = StringHelper::convertToString($oldValue, false);
$newValue = StringHelper::convertToString($newValue, false);
if (StringHelper::strToLower($oldValue) === StringHelper::strToLower($newValue) || $workSheet === null) {
return;
}
foreach ($workSheet->getTableCollection() as $table) {
/** @var Table $table */
if ($cell->isInRange($table->getRange())) {
$rangeRowsColumns = Coordinate::getRangeBoundaries($table->getRange());
if ($cell->getRow() === (int) $rangeRowsColumns[0][1]) {
Table\Column::updateStructuredReferences($workSheet, $oldValue, $newValue);
}
return;
}
}
}
/**
* Set cell value.
*
* Sets the value for a cell, automatically determining the datatype using the value binder
*
* @param mixed $value Value
* @param null|IValueBinder $binder Value Binder to override the currently set Value Binder
*
* @throws SpreadsheetException
*/
public function setValue(mixed $value, ?IValueBinder $binder = null): self
{
// Cells?->Worksheet?->Spreadsheet
$binder ??= $this->parent?->getParent()?->getParent()?->getValueBinder() ?? self::getValueBinder();
if (!$binder->bindValue($this, $value)) {
throw new SpreadsheetException('Value could not be bound to cell.');
}
return $this;
}
/**
* Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder).
*
* @param mixed $value Value
* @param string $dataType Explicit data type, see DataType::TYPE_*
* This parameter is currently optional (default = string).
* Omitting it is ***DEPRECATED***, and the default will be removed in a future release.
* Note that PhpSpreadsheet does not validate that the value and datatype are consistent, in using this
* method, then it is your responsibility as an end-user developer to validate that the value and
* the datatype match.
* If you do mismatch value and datatype, then the value you enter may be changed to match the datatype
* that you specify.
*
* @throws SpreadsheetException
*/
public function setValueExplicit(mixed $value, string $dataType = DataType::TYPE_STRING): self
{
$oldValue = $this->value;
$quotePrefix = false;
// set the value according to data type
switch ($dataType) {
case DataType::TYPE_NULL:
$this->value = null;
break;
case DataType::TYPE_STRING2:
$dataType = DataType::TYPE_STRING;
// no break
case DataType::TYPE_STRING:
// Synonym for string
if (is_string($value) && strlen($value) > 1 && $value[0] === '=') {
$quotePrefix = true;
}
// no break
case DataType::TYPE_INLINE:
// Rich text
$value2 = StringHelper::convertToString($value, true);
// Cells?->Worksheet?->Spreadsheet
$binder = $this->parent?->getParent()?->getParent()?->getValueBinder();
$preserveCr = false;
if ($binder !== null && method_exists($binder, 'getPreserveCr')) {
/** @var bool */
$preserveCr = $binder->getPreserveCr();
}
$this->value = DataType::checkString(($value instanceof RichText) ? $value : $value2, $preserveCr);
break;
case DataType::TYPE_NUMERIC:
if ($value !== null && !is_bool($value) && !is_numeric($value)) {
throw new SpreadsheetException('Invalid numeric value for datatype Numeric');
}
$this->value = 0 + $value;
break;
case DataType::TYPE_FORMULA:
$this->value = StringHelper::convertToString($value, true);
break;
case DataType::TYPE_BOOL:
$this->value = (bool) $value;
break;
case DataType::TYPE_ISO_DATE:
$this->value = SharedDate::convertIsoDate($value);
$dataType = DataType::TYPE_NUMERIC;
break;
case DataType::TYPE_ERROR:
$this->value = DataType::checkErrorCode($value);
break;
default:
throw new SpreadsheetException('Invalid datatype: ' . $dataType);
}
// set the datatype
$this->dataType = $dataType;
$this->updateInCollection();
$cellCoordinate = $this->getCoordinate();
self::updateIfCellIsTableHeader($this->getParent()?->getParent(), $this, $oldValue, $value);
$worksheet = $this->getWorksheet();
$spreadsheet = $worksheet->getParent();
if (isset($spreadsheet) && $spreadsheet->getIndex($worksheet, true) >= 0) {
$originalSelected = $worksheet->getSelectedCells();
$activeSheetIndex = $spreadsheet->getActiveSheetIndex();
$style = $this->getStyle();
$oldQuotePrefix = $style->getQuotePrefix();
if ($oldQuotePrefix !== $quotePrefix) {
$style->setQuotePrefix($quotePrefix);
}
$worksheet->setSelectedCells($originalSelected);
if ($activeSheetIndex >= 0) {
$spreadsheet->setActiveSheetIndex($activeSheetIndex);
}
}
return $this->getParent()?->get($cellCoordinate) ?? $this;
}
public const CALCULATE_DATE_TIME_ASIS = 0;
public const CALCULATE_DATE_TIME_FLOAT = 1;
public const CALCULATE_TIME_FLOAT = 2;
private static int $calculateDateTimeType = self::CALCULATE_DATE_TIME_ASIS;
public static function getCalculateDateTimeType(): int
{
return self::$calculateDateTimeType;
}
/** @throws CalculationException */
public static function setCalculateDateTimeType(int $calculateDateTimeType): void
{
self::$calculateDateTimeType = match ($calculateDateTimeType) {
self::CALCULATE_DATE_TIME_ASIS, self::CALCULATE_DATE_TIME_FLOAT, self::CALCULATE_TIME_FLOAT => $calculateDateTimeType,
default => throw new CalculationException("Invalid value $calculateDateTimeType for calculated date time type"),
};
}
/**
* Convert date, time, or datetime from int to float if desired.
*/
private function convertDateTimeInt(mixed $result): mixed
{
if (is_int($result)) {
if (self::$calculateDateTimeType === self::CALCULATE_TIME_FLOAT) {
if (SharedDate::isDateTime($this, $result, false)) {
$result = (float) $result;
}
} elseif (self::$calculateDateTimeType === self::CALCULATE_DATE_TIME_FLOAT) {
if (SharedDate::isDateTime($this, $result, true)) {
$result = (float) $result;
}
}
}
return $result;
}
/**
* Get calculated cell value converted to string.
*/
public function getCalculatedValueString(): string
{
$value = $this->getCalculatedValue();
while (is_array($value)) {
$value = array_shift($value);
}
return StringHelper::convertToString($value, false);
}
/**
* Get calculated cell value.
*
* @param bool $resetLog Whether the calculation engine logger should be reset or not
*
* @throws CalculationException
*/
public function getCalculatedValue(bool $resetLog = true): mixed
{
$title = 'unknown';
$oldAttributes = $this->formulaAttributes;
$oldAttributesT = $oldAttributes['t'] ?? '';
$coordinate = $this->getCoordinate();
$oldAttributesRef = $oldAttributes['ref'] ?? $coordinate;
$originalValue = $this->value;
$originalDataType = $this->dataType;
$this->formulaAttributes = [];
$spill = false;
if ($this->dataType === DataType::TYPE_FORMULA) {
try {
$currentCalendar = SharedDate::getExcelCalendar();
SharedDate::setExcelCalendar($this->getWorksheet()->getParent()?->getExcelCalendar());
$thisworksheet = $this->getWorksheet();
$index = $thisworksheet->getParentOrThrow()->getActiveSheetIndex();
$selected = $thisworksheet->getSelectedCells();
$title = $thisworksheet->getTitle();
$calculation = Calculation::getInstance($thisworksheet->getParent());
$result = $calculation->calculateCellValue($this, $resetLog);
$result = $this->convertDateTimeInt($result);
$thisworksheet->setSelectedCells($selected);
$thisworksheet->getParentOrThrow()->setActiveSheetIndex($index);
if (is_array($result) && $calculation->getInstanceArrayReturnType() !== Calculation::RETURN_ARRAY_AS_ARRAY) {
while (is_array($result)) {
$result = array_shift($result);
}
}
if (
!is_array($result)
&& $calculation->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY
&& $oldAttributesT === 'array'
&& ($oldAttributesRef === $coordinate || $oldAttributesRef === "$coordinate:$coordinate")
) {
$result = [$result];
}
// if return_as_array for formula like '=sheet!cell'
if (is_array($result) && count($result) === 1) {
$resultKey = array_keys($result)[0];
$resultValue = $result[$resultKey];
if (is_int($resultKey) && is_array($resultValue) && count($resultValue) === 1) {
$resultKey2 = array_keys($resultValue)[0];
$resultValue2 = $resultValue[$resultKey2];
if (is_string($resultKey2) && !is_array($resultValue2) && preg_match('/[a-zA-Z]{1,3}/', $resultKey2) === 1) {
$result = $resultValue2;
}
}
}
$newColumn = $this->getColumn();
if (is_array($result)) {
$result = self::convertSpecialArray($result);
$this->formulaAttributes['t'] = 'array';
$this->formulaAttributes['ref'] = $maxCoordinate = $coordinate;
$newRow = $row = $this->getRow();
$column = $this->getColumn();
foreach ($result as $resultRow) {
if (is_array($resultRow)) {
$newColumn = $column;
foreach ($resultRow as $resultValue) {
if ($row !== $newRow || $column !== $newColumn) {
$maxCoordinate = $newColumn . $newRow;
if ($thisworksheet->getCell($newColumn . $newRow)->getValue() !== null) {
if (!Coordinate::coordinateIsInsideRange($oldAttributesRef, $newColumn . $newRow)) {
$spill = true;
break;
}
}
}
/** @var string $newColumn */
StringHelper::stringIncrement($newColumn);
}
++$newRow;
} else {
if ($row !== $newRow || $column !== $newColumn) {
$maxCoordinate = $newColumn . $newRow;
if ($thisworksheet->getCell($newColumn . $newRow)->getValue() !== null) {
if (!Coordinate::coordinateIsInsideRange($oldAttributesRef, $newColumn . $newRow)) {
$spill = true;
}
}
}
StringHelper::stringIncrement($newColumn);
}
if ($spill) {
break;
}
}
if (!$spill) {
$this->formulaAttributes['ref'] .= ":$maxCoordinate";
}
$thisworksheet->getCell($column . $row);
}
if (is_array($result)) {
if ($oldAttributes !== null && $calculation->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY) {
if (($oldAttributesT) === 'array') {
$thisworksheet = $this->getWorksheet();
$coordinate = $this->getCoordinate();
$ref = $oldAttributesRef;
if (preg_match('/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/', $ref, $matches) === 1) {
if (isset($matches[3])) {
$minCol = $matches[1];
$minRow = (int) $matches[2];
$maxCol = $matches[4];
StringHelper::stringIncrement($maxCol);
$maxRow = (int) $matches[5];
for ($row = $minRow; $row <= $maxRow; ++$row) {
for ($col = $minCol; $col !== $maxCol; StringHelper::stringIncrement($col)) {
/** @var string $col */
if ("$col$row" !== $coordinate) {
$thisworksheet->getCell("$col$row")->setValue(null);
}
}
}
}
}
$thisworksheet->getCell($coordinate);
}
}
}
if ($spill) {
$result = ExcelError::SPILL();
}
if (is_array($result)) {
$newRow = $row = $this->getRow();
$newColumn = $column = $this->getColumn();
foreach ($result as $resultRow) {
if (is_array($resultRow)) {
$newColumn = $column;
foreach ($resultRow as $resultValue) {
if ($row !== $newRow || $column !== $newColumn) {
$thisworksheet
->getCell($newColumn . $newRow)
->setValue($resultValue);
}
StringHelper::stringIncrement($newColumn);
}
++$newRow;
} else {
if ($row !== $newRow || $column !== $newColumn) {
$thisworksheet->getCell($newColumn . $newRow)->setValue($resultRow);
}
StringHelper::stringIncrement($newColumn);
}
}
$thisworksheet->getCell($column . $row);
$this->value = $originalValue;
$this->dataType = $originalDataType;
}
} catch (SpreadsheetException $ex) {
SharedDate::setExcelCalendar($currentCalendar);
if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) {
return $this->calculatedValue; // Fallback for calculations referencing external files.
} elseif (preg_match('/[Uu]ndefined (name|offset: 2|array key 2)/', $ex->getMessage()) === 1) {
return ExcelError::NAME();
}
throw new CalculationException(
$title . '!' . $this->getCoordinate() . ' -> ' . $ex->getMessage(),
$ex->getCode(),
$ex
);
}
SharedDate::setExcelCalendar($currentCalendar);
if ($result === Functions::NOT_YET_IMPLEMENTED) {
$this->formulaAttributes = $oldAttributes;
return $this->calculatedValue; // Fallback if calculation engine does not support the formula.
}
return $result;
} elseif ($this->value instanceof RichText) {
return $this->value->getPlainText();
}
return $this->convertDateTimeInt($this->value);
}
/**
* Convert array like the following (preserve values, lose indexes):
* [
* rowNumber1 => [colLetter1 => value, colLetter2 => value ...],
* rowNumber2 => [colLetter1 => value, colLetter2 => value ...],
* ...
* ].
*
* @param mixed[] $array
*
* @return mixed[]
*/
private static function convertSpecialArray(array $array): array
{
$newArray = [];
foreach ($array as $rowIndex => $row) {
if (!is_int($rowIndex) || $rowIndex <= 0 || !is_array($row)) {
return $array;
}
$keys = array_keys($row);
$key0 = $keys[0] ?? '';
if (!is_string($key0)) {
return $array;
}
$newArray[] = array_values($row);
}
return $newArray;
}
/**
* Set old calculated value (cached).
*
* @param mixed $originalValue Value
*/
public function setCalculatedValue(mixed $originalValue, bool $tryNumeric = true): self
{
if ($originalValue !== null) {
$this->calculatedValue = ($tryNumeric && is_numeric($originalValue)) ? (0 + $originalValue) : $originalValue;
}
return $this->updateInCollection();
}
/**
* Get old calculated value (cached)
* This returns the value last calculated by MS Excel or whichever spreadsheet program was used to
* create the original spreadsheet file.
* Note that this value is not guaranteed to reflect the actual calculated value because it is
* possible that auto-calculation was disabled in the original spreadsheet, and underlying data
* values used by the formula have changed since it was last calculated.
*/
public function getOldCalculatedValue(): mixed
{
return $this->calculatedValue;
}
/**
* Get cell data type.
*/
public function getDataType(): string
{
return $this->dataType;
}
/**
* Set cell data type.
*
* @param string $dataType see DataType::TYPE_*
*/
public function setDataType(string $dataType): self
{
$this->setValueExplicit($this->value, $dataType);
return $this;
}
/**
* Identify if the cell contains a formula.
*/
public function isFormula(): bool
{
return $this->dataType === DataType::TYPE_FORMULA && $this->getStyle()->getQuotePrefix() === false;
}
/**
* Does this cell contain Data validation rules?
*
* @throws SpreadsheetException
*/
public function hasDataValidation(): bool
{
if (!isset($this->parent)) {
throw new SpreadsheetException('Cannot check for data validation when cell is not bound to a worksheet');
}
return $this->getWorksheet()->dataValidationExists($this->getCoordinate());
}
/**
* Get Data validation rules.
*
* @throws SpreadsheetException
*/
public function getDataValidation(): DataValidation
{
if (!isset($this->parent)) {
throw new SpreadsheetException('Cannot get data validation for cell that is not bound to a worksheet');
}
return $this->getWorksheet()->getDataValidation($this->getCoordinate());
}
/**
* Set Data validation rules.
*
* @throws SpreadsheetException
*/
public function setDataValidation(?DataValidation $dataValidation = null): self
{
if (!isset($this->parent)) {
throw new SpreadsheetException('Cannot set data validation for cell that is not bound to a worksheet');
}
$this->getWorksheet()->setDataValidation($this->getCoordinate(), $dataValidation);
return $this->updateInCollection();
}
/**
* Does this cell contain valid value?
*/
public function hasValidValue(): bool
{
$validator = new DataValidator();
return $validator->isValid($this);
}
/**
* Does this cell contain a Hyperlink?
*
* @throws SpreadsheetException
*/
public function hasHyperlink(): bool
{
if (!isset($this->parent)) {
throw new SpreadsheetException('Cannot check for hyperlink when cell is not bound to a worksheet');
}
return $this->getWorksheet()->hyperlinkExists($this->getCoordinate());
}
/**
* Get Hyperlink.
*
* @throws SpreadsheetException
*/
public function getHyperlink(): Hyperlink
{
if (!isset($this->parent)) {
throw new SpreadsheetException('Cannot get hyperlink for cell that is not bound to a worksheet');
}
return $this->getWorksheet()->getHyperlink($this->getCoordinate());
}
/**
* Set Hyperlink.
*
* @throws SpreadsheetException
*/
public function setHyperlink(?Hyperlink $hyperlink = null): self
{
if (!isset($this->parent)) {
throw new SpreadsheetException('Cannot set hyperlink for cell that is not bound to a worksheet');
}
$this->getWorksheet()->setHyperlink($this->getCoordinate(), $hyperlink);
return $this->updateInCollection();
}
/**
* Get cell collection.
*/
public function getParent(): ?Cells
{
return $this->parent;
}
/**
* Get parent worksheet.
*
* @throws SpreadsheetException
*/
public function getWorksheet(): Worksheet
{
$parent = $this->parent;
if ($parent !== null) {
$worksheet = $parent->getParent();
} else {
$worksheet = null;
}
if ($worksheet === null) {
throw new SpreadsheetException('Worksheet no longer exists');
}
return $worksheet;
}
public function getWorksheetOrNull(): ?Worksheet
{
$parent = $this->parent;
if ($parent !== null) {
$worksheet = $parent->getParent();
} else {
$worksheet = null;
}
return $worksheet;
}
/**
* Is this cell in a merge range.
*/
public function isInMergeRange(): bool
{
return (bool) $this->getMergeRange();
}
/**
* Is this cell the master (top left cell) in a merge range (that holds the actual data value).
*/
public function isMergeRangeValueCell(): bool
{
if ($mergeRange = $this->getMergeRange()) {
$mergeRange = Coordinate::splitRange($mergeRange);
[$startCell] = $mergeRange[0];
return $this->getCoordinate() === $startCell;
}
return false;
}
/**
* If this cell is in a merge range, then return the range.
*
* @return false|string
*/
public function getMergeRange()
{
foreach ($this->getWorksheet()->getMergeCells() as $mergeRange) {
if ($this->isInRange($mergeRange)) {
return $mergeRange;
}
}
return false;
}
/**
* Get cell style.
*/
public function getStyle(): Style
{
return $this->getWorksheet()->getStyle($this->getCoordinate());
}
/**
* Get cell style.
*/
public function getAppliedStyle(): Style
{
if ($this->getWorksheet()->conditionalStylesExists($this->getCoordinate()) === false) {
return $this->getStyle();
}
$range = $this->getWorksheet()->getConditionalRange($this->getCoordinate());
if ($range === null) {
return $this->getStyle();
}
$matcher = new CellStyleAssessor($this, $range);
return $matcher->matchConditions($this->getWorksheet()->getConditionalStyles($this->getCoordinate()));
}
/**
* Re-bind parent.
*/
public function rebindParent(Worksheet $parent): self
{
$this->parent = $parent->getCellCollection();
return $this->updateInCollection();
}
/**
* Is cell in a specific range?
*
* @param string $range Cell range (e.g. A1:A1)
*/
public function isInRange(string $range): bool
{
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
// Translate properties
$myColumn = Coordinate::columnIndexFromString($this->getColumn());
$myRow = $this->getRow();
// Verify if cell is in range
return ($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn)
&& ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow);
}
/**
* Compare 2 cells.
*
* @param Cell $a Cell a
* @param Cell $b Cell b
*
* @return int Result of comparison (always -1 or 1, never zero!)
*/
public static function compareCells(self $a, self $b): int
{
if ($a->getRow() < $b->getRow()) {
return -1;
} elseif ($a->getRow() > $b->getRow()) {
return 1;
} elseif (Coordinate::columnIndexFromString($a->getColumn()) < Coordinate::columnIndexFromString($b->getColumn())) {
return -1;
}
return 1;
}
/**
* Get value binder to use.
*/
public static function getValueBinder(): IValueBinder
{
if (self::$valueBinder === null) {
self::$valueBinder = new DefaultValueBinder();
}
return self::$valueBinder;
}
/**
* Set value binder to use.
*/
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | true |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/StringValueBinder.php | src/PhpSpreadsheet/Cell/StringValueBinder.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
use DateTimeInterface;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use Stringable;
class StringValueBinder extends DefaultValueBinder implements IValueBinder
{
protected bool $convertNull = true;
protected bool $convertBoolean = true;
protected bool $convertNumeric = true;
protected bool $convertFormula = true;
protected bool $setIgnoredErrors = false;
public function setSetIgnoredErrors(bool $setIgnoredErrors = false): self
{
$this->setIgnoredErrors = $setIgnoredErrors;
return $this;
}
public function setNullConversion(bool $suppressConversion = false): self
{
$this->convertNull = $suppressConversion;
return $this;
}
public function setBooleanConversion(bool $suppressConversion = false): self
{
$this->convertBoolean = $suppressConversion;
return $this;
}
public function getBooleanConversion(): bool
{
return $this->convertBoolean;
}
public function setNumericConversion(bool $suppressConversion = false): self
{
$this->convertNumeric = $suppressConversion;
return $this;
}
public function setFormulaConversion(bool $suppressConversion = false): self
{
$this->convertFormula = $suppressConversion;
return $this;
}
public function setConversionForAllValueTypes(bool $suppressConversion = false): self
{
$this->convertNull = $suppressConversion;
$this->convertBoolean = $suppressConversion;
$this->convertNumeric = $suppressConversion;
$this->convertFormula = $suppressConversion;
return $this;
}
/**
* Bind value to a cell.
*
* @param Cell $cell Cell to bind value to
* @param mixed $value Value to bind in cell
*/
public function bindValue(Cell $cell, mixed $value): bool
{
if (is_object($value)) {
return $this->bindObjectValue($cell, $value);
}
if ($value !== null && !is_scalar($value)) {
throw new SpreadsheetException('Unable to bind unstringable ' . gettype($value));
}
// sanitize UTF-8 strings
if (is_string($value)) {
$value = StringHelper::sanitizeUTF8($value);
}
$ignoredErrors = false;
if ($value === null && $this->convertNull === false) {
$cell->setValueExplicit($value, DataType::TYPE_NULL);
} elseif (is_bool($value) && $this->convertBoolean === false) {
$cell->setValueExplicit($value, DataType::TYPE_BOOL);
} elseif ((is_int($value) || is_float($value)) && $this->convertNumeric === false) {
$cell->setValueExplicit($value, DataType::TYPE_NUMERIC);
} elseif (is_string($value) && strlen($value) > 1 && $value[0] === '=' && $this->convertFormula === false && parent::dataTypeForValue($value) === DataType::TYPE_FORMULA) {
$cell->setValueExplicit($value, DataType::TYPE_FORMULA);
} else {
$ignoredErrors = is_numeric($value);
$cell->setValueExplicit((string) $value, DataType::TYPE_STRING);
}
if ($this->setIgnoredErrors) {
$cell->getIgnoredErrors()->setNumberStoredAsText($ignoredErrors);
}
return true;
}
protected function bindObjectValue(Cell $cell, object $value): bool
{
// Handle any objects that might be injected
$ignoredErrors = false;
if ($value instanceof DateTimeInterface) {
$value = $value->format('Y-m-d H:i:s');
$cell->setValueExplicit($value, DataType::TYPE_STRING);
} elseif ($value instanceof RichText) {
$cell->setValueExplicit($value, DataType::TYPE_INLINE);
$ignoredErrors = is_numeric($value->getPlainText());
} elseif ($value instanceof Stringable) {
$cell->setValueExplicit((string) $value, DataType::TYPE_STRING);
$ignoredErrors = is_numeric((string) $value);
} else {
throw new SpreadsheetException('Unable to bind unstringable object of type ' . get_class($value));
}
if ($this->setIgnoredErrors) {
$cell->getIgnoredErrors()->setNumberStoredAsText($ignoredErrors);
}
return true;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/CellRange.php | src/PhpSpreadsheet/Cell/CellRange.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Stringable;
/**
* @implements AddressRange<CellAddress>
*/
class CellRange implements AddressRange, Stringable
{
protected CellAddress $from;
protected CellAddress $to;
public function __construct(CellAddress $from, CellAddress $to)
{
$this->validateFromTo($from, $to);
}
private function validateFromTo(CellAddress $from, CellAddress $to): void
{
// Identify actual top-left and bottom-right values (in case we've been given top-right and bottom-left)
$firstColumn = min($from->columnId(), $to->columnId());
$firstRow = min($from->rowId(), $to->rowId());
$lastColumn = max($from->columnId(), $to->columnId());
$lastRow = max($from->rowId(), $to->rowId());
$fromWorksheet = $from->worksheet();
$toWorksheet = $to->worksheet();
$this->validateWorksheets($fromWorksheet, $toWorksheet);
$this->from = $this->cellAddressWrapper($firstColumn, $firstRow, $fromWorksheet);
$this->to = $this->cellAddressWrapper($lastColumn, $lastRow, $toWorksheet);
}
private function validateWorksheets(?Worksheet $fromWorksheet, ?Worksheet $toWorksheet): void
{
if ($fromWorksheet !== null && $toWorksheet !== null) {
// We could simply compare worksheets rather than worksheet titles; but at some point we may introduce
// support for 3d ranges; and at that point we drop this check and let the validation fall through
// to the check for same workbook; but unless we check on titles, this test will also detect if the
// worksheets are in different spreadsheets, and the next check will never execute or throw its
// own exception.
if ($fromWorksheet->getTitle() !== $toWorksheet->getTitle()) {
throw new Exception('3d Cell Ranges are not supported');
} elseif ($fromWorksheet->getParent() !== $toWorksheet->getParent()) {
throw new Exception('Worksheets must be in the same spreadsheet');
}
}
}
private function cellAddressWrapper(int $column, int $row, ?Worksheet $worksheet = null): CellAddress
{
$cellAddress = Coordinate::stringFromColumnIndex($column) . (string) $row;
return new class ($cellAddress, $worksheet) extends CellAddress {
public function nextRow(int $offset = 1): CellAddress
{
/** @var CellAddress $result */
$result = parent::nextRow($offset);
$this->rowId = $result->rowId;
$this->cellAddress = $result->cellAddress;
return $this;
}
public function previousRow(int $offset = 1): CellAddress
{
/** @var CellAddress $result */
$result = parent::previousRow($offset);
$this->rowId = $result->rowId;
$this->cellAddress = $result->cellAddress;
return $this;
}
public function nextColumn(int $offset = 1): CellAddress
{
/** @var CellAddress $result */
$result = parent::nextColumn($offset);
$this->columnId = $result->columnId;
$this->columnName = $result->columnName;
$this->cellAddress = $result->cellAddress;
return $this;
}
public function previousColumn(int $offset = 1): CellAddress
{
/** @var CellAddress $result */
$result = parent::previousColumn($offset);
$this->columnId = $result->columnId;
$this->columnName = $result->columnName;
$this->cellAddress = $result->cellAddress;
return $this;
}
};
}
public function from(): CellAddress
{
// Re-order from/to in case the cell addresses have been modified
$this->validateFromTo($this->from, $this->to);
return $this->from;
}
public function to(): CellAddress
{
// Re-order from/to in case the cell addresses have been modified
$this->validateFromTo($this->from, $this->to);
return $this->to;
}
public function __toString(): string
{
// Re-order from/to in case the cell addresses have been modified
$this->validateFromTo($this->from, $this->to);
if ($this->from->cellAddress() === $this->to->cellAddress()) {
return "{$this->from->fullCellAddress()}";
}
$fromAddress = $this->from->fullCellAddress();
$toAddress = $this->to->cellAddress();
return "{$fromAddress}:{$toAddress}";
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/IgnoredErrors.php | src/PhpSpreadsheet/Cell/IgnoredErrors.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
class IgnoredErrors
{
private bool $numberStoredAsText = false;
private bool $formula = false;
private bool $formulaRange = false;
private bool $twoDigitTextYear = false;
private bool $evalError = false;
public function setNumberStoredAsText(bool $value): self
{
$this->numberStoredAsText = $value;
return $this;
}
public function getNumberStoredAsText(): bool
{
return $this->numberStoredAsText;
}
public function setFormula(bool $value): self
{
$this->formula = $value;
return $this;
}
public function getFormula(): bool
{
return $this->formula;
}
public function setFormulaRange(bool $value): self
{
$this->formulaRange = $value;
return $this;
}
public function getFormulaRange(): bool
{
return $this->formulaRange;
}
public function setTwoDigitTextYear(bool $value): self
{
$this->twoDigitTextYear = $value;
return $this;
}
public function getTwoDigitTextYear(): bool
{
return $this->twoDigitTextYear;
}
public function setEvalError(bool $value): self
{
$this->evalError = $value;
return $this;
}
public function getEvalError(): bool
{
return $this->evalError;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/DataValidation.php | src/PhpSpreadsheet/Cell/DataValidation.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
class DataValidation
{
// Data validation types
const TYPE_NONE = 'none';
const TYPE_CUSTOM = 'custom';
const TYPE_DATE = 'date';
const TYPE_DECIMAL = 'decimal';
const TYPE_LIST = 'list';
const TYPE_TEXTLENGTH = 'textLength';
const TYPE_TIME = 'time';
const TYPE_WHOLE = 'whole';
// Data validation error styles
const STYLE_STOP = 'stop';
const STYLE_WARNING = 'warning';
const STYLE_INFORMATION = 'information';
// Data validation operators
const OPERATOR_BETWEEN = 'between';
const OPERATOR_EQUAL = 'equal';
const OPERATOR_GREATERTHAN = 'greaterThan';
const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual';
const OPERATOR_LESSTHAN = 'lessThan';
const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual';
const OPERATOR_NOTBETWEEN = 'notBetween';
const OPERATOR_NOTEQUAL = 'notEqual';
private const DEFAULT_OPERATOR = self::OPERATOR_BETWEEN;
/**
* Formula 1.
*/
private string $formula1 = '';
/**
* Formula 2.
*/
private string $formula2 = '';
/**
* Type.
*/
private string $type = self::TYPE_NONE;
/**
* Error style.
*/
private string $errorStyle = self::STYLE_STOP;
/**
* Operator.
*/
private string $operator = self::DEFAULT_OPERATOR;
/**
* Allow Blank.
*/
private bool $allowBlank = false;
/**
* Show DropDown.
*/
private bool $showDropDown = false;
/**
* Show InputMessage.
*/
private bool $showInputMessage = false;
/**
* Show ErrorMessage.
*/
private bool $showErrorMessage = false;
/**
* Error title.
*/
private string $errorTitle = '';
/**
* Error.
*/
private string $error = '';
/**
* Prompt title.
*/
private string $promptTitle = '';
/**
* Prompt.
*/
private string $prompt = '';
/**
* Get Formula 1.
*/
public function getFormula1(): string
{
return $this->formula1;
}
/**
* Set Formula 1.
*
* @return $this
*/
public function setFormula1(string $formula): static
{
$this->formula1 = $formula;
return $this;
}
/**
* Get Formula 2.
*/
public function getFormula2(): string
{
return $this->formula2;
}
/**
* Set Formula 2.
*
* @return $this
*/
public function setFormula2(string $formula): static
{
$this->formula2 = $formula;
return $this;
}
/**
* Get Type.
*/
public function getType(): string
{
return $this->type;
}
/**
* Set Type.
*
* @return $this
*/
public function setType(string $type): static
{
$this->type = $type;
return $this;
}
/**
* Get Error style.
*/
public function getErrorStyle(): string
{
return $this->errorStyle;
}
/**
* Set Error style.
*
* @param string $errorStyle see self::STYLE_*
*
* @return $this
*/
public function setErrorStyle(string $errorStyle): static
{
$this->errorStyle = $errorStyle;
return $this;
}
/**
* Get Operator.
*/
public function getOperator(): string
{
return $this->operator;
}
/**
* Set Operator.
*
* @return $this
*/
public function setOperator(string $operator): static
{
$this->operator = ($operator === '') ? self::DEFAULT_OPERATOR : $operator;
return $this;
}
/**
* Get Allow Blank.
*/
public function getAllowBlank(): bool
{
return $this->allowBlank;
}
/**
* Set Allow Blank.
*
* @return $this
*/
public function setAllowBlank(bool $allowBlank): static
{
$this->allowBlank = $allowBlank;
return $this;
}
/**
* Get Show DropDown.
*/
public function getShowDropDown(): bool
{
return $this->showDropDown;
}
/**
* Set Show DropDown.
*
* @return $this
*/
public function setShowDropDown(bool $showDropDown): static
{
$this->showDropDown = $showDropDown;
return $this;
}
/**
* Get Show InputMessage.
*/
public function getShowInputMessage(): bool
{
return $this->showInputMessage;
}
/**
* Set Show InputMessage.
*
* @return $this
*/
public function setShowInputMessage(bool $showInputMessage): static
{
$this->showInputMessage = $showInputMessage;
return $this;
}
/**
* Get Show ErrorMessage.
*/
public function getShowErrorMessage(): bool
{
return $this->showErrorMessage;
}
/**
* Set Show ErrorMessage.
*
* @return $this
*/
public function setShowErrorMessage(bool $showErrorMessage): static
{
$this->showErrorMessage = $showErrorMessage;
return $this;
}
/**
* Get Error title.
*/
public function getErrorTitle(): string
{
return $this->errorTitle;
}
/**
* Set Error title.
*
* @return $this
*/
public function setErrorTitle(string $errorTitle): static
{
$this->errorTitle = $errorTitle;
return $this;
}
/**
* Get Error.
*/
public function getError(): string
{
return $this->error;
}
/**
* Set Error.
*
* @return $this
*/
public function setError(string $error): static
{
$this->error = $error;
return $this;
}
/**
* Get Prompt title.
*/
public function getPromptTitle(): string
{
return $this->promptTitle;
}
/**
* Set Prompt title.
*
* @return $this
*/
public function setPromptTitle(string $promptTitle): static
{
$this->promptTitle = $promptTitle;
return $this;
}
/**
* Get Prompt.
*/
public function getPrompt(): string
{
return $this->prompt;
}
/**
* Set Prompt.
*
* @return $this
*/
public function setPrompt(string $prompt): static
{
$this->prompt = $prompt;
return $this;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
return md5(
$this->formula1
. $this->formula2
. $this->type
. $this->errorStyle
. $this->operator
. ($this->allowBlank ? 't' : 'f')
. ($this->showDropDown ? 't' : 'f')
. ($this->showInputMessage ? 't' : 'f')
. ($this->showErrorMessage ? 't' : 'f')
. $this->errorTitle
. $this->error
. $this->promptTitle
. $this->prompt
. $this->sqref
. __CLASS__
);
}
private ?string $sqref = null;
public function getSqref(): ?string
{
return $this->sqref;
}
public function setSqref(?string $str): self
{
$this->sqref = $str;
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/IValueBinder.php | src/PhpSpreadsheet/Cell/IValueBinder.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
interface IValueBinder
{
/**
* Bind value to a cell.
*
* @param Cell $cell Cell to bind value to
* @param mixed $value Value to bind in cell
*/
public function bindValue(Cell $cell, mixed $value): bool;
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/AddressRange.php | src/PhpSpreadsheet/Cell/AddressRange.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
/**
* @template T
*/
interface AddressRange
{
public const MAX_ROW = 1048576;
public const MAX_COLUMN = 'XFD';
public const MAX_COLUMN_INT = 16384;
/**
* @return T
*/
public function from(): mixed;
/**
* @return T
*/
public function to(): mixed;
public function __toString(): string;
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/RowRange.php | src/PhpSpreadsheet/Cell/RowRange.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Stringable;
/**
* @implements AddressRange<int>
*/
class RowRange implements AddressRange, Stringable
{
protected ?Worksheet $worksheet;
protected int $from;
protected int $to;
public function __construct(int $from, ?int $to = null, ?Worksheet $worksheet = null)
{
$this->validateFromTo($from, $to ?? $from);
$this->worksheet = $worksheet;
}
public function __destruct()
{
$this->worksheet = null;
}
/** @param array{int, int} $array */
public static function fromArray(array $array, ?Worksheet $worksheet = null): self
{
[$from, $to] = $array;
return new self($from, $to, $worksheet);
}
private function validateFromTo(int $from, int $to): void
{
// Identify actual top and bottom values (in case we've been given bottom and top)
$this->from = min($from, $to);
$this->to = max($from, $to);
}
public function from(): int
{
return $this->from;
}
public function to(): int
{
return $this->to;
}
public function rowCount(): int
{
return $this->to - $this->from + 1;
}
public function shiftRight(int $offset = 1): self
{
$newFrom = $this->from + $offset;
$newFrom = ($newFrom < 1) ? 1 : $newFrom;
$newTo = $this->to + $offset;
$newTo = ($newTo < 1) ? 1 : $newTo;
return new self($newFrom, $newTo, $this->worksheet);
}
public function shiftLeft(int $offset = 1): self
{
return $this->shiftRight(0 - $offset);
}
public function toCellRange(): CellRange
{
return new CellRange(
CellAddress::fromColumnAndRow(Coordinate::columnIndexFromString('A'), $this->from, $this->worksheet),
CellAddress::fromColumnAndRow(Coordinate::columnIndexFromString(AddressRange::MAX_COLUMN), $this->to)
);
}
public function __toString(): string
{
if ($this->worksheet !== null) {
$title = str_replace("'", "''", $this->worksheet->getTitle());
return "'{$title}'!{$this->from}:{$this->to}";
}
return "{$this->from}:{$this->to}";
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/DefaultValueBinder.php | src/PhpSpreadsheet/Cell/DefaultValueBinder.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
use Composer\Pcre\Preg;
use DateTimeInterface;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalculationException;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use Stringable;
class DefaultValueBinder implements IValueBinder
{
// 123 456 789 012 345
private const FIFTEEN_NINES = 999_999_999_999_999;
/**
* Bind value to a cell.
*
* @param Cell $cell Cell to bind value to
* @param mixed $value Value to bind in cell
*/
public function bindValue(Cell $cell, mixed $value): bool
{
// sanitize UTF-8 strings
if (is_string($value)) {
$value = StringHelper::sanitizeUTF8($value);
} elseif ($value === null || is_scalar($value) || $value instanceof RichText) {
// No need to do anything
} elseif ($value instanceof DateTimeInterface) {
$value = $value->format('Y-m-d H:i:s');
} elseif ($value instanceof Stringable) {
$value = (string) $value;
} else {
throw new SpreadsheetException('Unable to bind unstringable ' . gettype($value));
}
// Set value explicit
$cell->setValueExplicit($value, static::dataTypeForValue($value));
// Done!
return true;
}
/**
* DataType for value.
*/
public static function dataTypeForValue(mixed $value): string
{
// Match the value against a few data types
if ($value === null) {
return DataType::TYPE_NULL;
}
if (is_int($value) && abs($value) > self::FIFTEEN_NINES) {
return DataType::TYPE_STRING;
}
if (is_float($value) || is_int($value)) {
return DataType::TYPE_NUMERIC;
}
if (is_bool($value)) {
return DataType::TYPE_BOOL;
}
if ($value === '') {
return DataType::TYPE_STRING;
}
if ($value instanceof RichText) {
return DataType::TYPE_INLINE;
}
if ($value instanceof Stringable) {
$value = (string) $value;
}
if (!is_string($value)) {
$gettype = is_object($value) ? get_class($value) : gettype($value);
throw new SpreadsheetException("unusable type $gettype");
}
if (strlen($value) > 1 && $value[0] === '=') {
$calculation = new Calculation();
$calculation->disableBranchPruning();
try {
if (empty($calculation->parseFormula($value))) {
return DataType::TYPE_STRING;
}
} catch (CalculationException $e) {
$message = $e->getMessage();
if (
$message === 'Formula Error: An unexpected error occurred'
|| str_contains($message, 'has no operands')
) {
return DataType::TYPE_STRING;
}
}
return DataType::TYPE_FORMULA;
}
if (Preg::isMatch('/^[\+\-]?(\d+\.?\d*|\d*\.?\d+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $value)) {
$tValue = ltrim($value, '+-');
if (strlen($tValue) > 1 && $tValue[0] === '0' && $tValue[1] !== '.') {
return DataType::TYPE_STRING;
}
if (!Preg::isMatch('/[eE.]/', $value)) {
$aValue = abs((float) $value);
if ($aValue > self::FIFTEEN_NINES) {
return DataType::TYPE_STRING;
}
}
if (!is_numeric($value) || !is_finite((float) $value)) {
return DataType::TYPE_STRING;
}
return DataType::TYPE_NUMERIC;
}
$errorCodes = DataType::getErrorCodes();
if (isset($errorCodes[$value])) {
return DataType::TYPE_ERROR;
}
return DataType::TYPE_STRING;
}
protected bool $preserveCr = false;
public function getPreserveCr(): bool
{
return $this->preserveCr;
}
public function setPreserveCr(bool $preserveCr): self
{
$this->preserveCr = $preserveCr;
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/CellAddress.php | src/PhpSpreadsheet/Cell/CellAddress.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Stringable;
class CellAddress implements Stringable
{
protected ?Worksheet $worksheet;
protected string $cellAddress;
protected string $columnName = '';
protected int $columnId;
protected int $rowId;
public function __construct(string $cellAddress, ?Worksheet $worksheet = null)
{
$this->cellAddress = str_replace('$', '', $cellAddress);
[$this->columnId, $this->rowId, $this->columnName] = Coordinate::indexesFromString($this->cellAddress);
$this->worksheet = $worksheet;
}
public function __destruct()
{
unset($this->worksheet);
}
/**
* @phpstan-assert int|numeric-string $columnId
* @phpstan-assert int|numeric-string $rowId
*/
private static function validateColumnAndRow(int|string $columnId, int|string $rowId): void
{
if (!is_numeric($columnId) || $columnId <= 0 || !is_numeric($rowId) || $rowId <= 0) {
throw new Exception('Row and Column Ids must be positive integer values');
}
}
public static function fromColumnAndRow(int|string $columnId, int|string $rowId, ?Worksheet $worksheet = null): self
{
self::validateColumnAndRow($columnId, $rowId);
return new self(Coordinate::stringFromColumnIndex($columnId) . $rowId, $worksheet);
}
/** @param array<int, int> $array */
public static function fromColumnRowArray(array $array, ?Worksheet $worksheet = null): self
{
[$columnId, $rowId] = $array;
return self::fromColumnAndRow($columnId, $rowId, $worksheet);
}
public static function fromCellAddress(string $cellAddress, ?Worksheet $worksheet = null): self
{
return new self($cellAddress, $worksheet);
}
/**
* The returned address string will contain the worksheet name as well, if available,
* (ie. if a Worksheet was provided to the constructor).
* e.g. "'Mark''s Worksheet'!C5".
*/
public function fullCellAddress(): string
{
if ($this->worksheet !== null) {
$title = str_replace("'", "''", $this->worksheet->getTitle());
return "'{$title}'!{$this->cellAddress}";
}
return $this->cellAddress;
}
public function worksheet(): ?Worksheet
{
return $this->worksheet;
}
/**
* The returned address string will contain just the column/row address,
* (even if a Worksheet was provided to the constructor).
* e.g. "C5".
*/
public function cellAddress(): string
{
return $this->cellAddress;
}
public function rowId(): int
{
return $this->rowId;
}
public function columnId(): int
{
return $this->columnId;
}
public function columnName(): string
{
return $this->columnName;
}
public function nextRow(int $offset = 1): self
{
$newRowId = $this->rowId + $offset;
if ($newRowId < 1) {
$newRowId = 1;
}
return self::fromColumnAndRow($this->columnId, $newRowId);
}
public function previousRow(int $offset = 1): self
{
return $this->nextRow(0 - $offset);
}
public function nextColumn(int $offset = 1): self
{
$newColumnId = $this->columnId + $offset;
if ($newColumnId < 1) {
$newColumnId = 1;
}
return self::fromColumnAndRow($newColumnId, $this->rowId);
}
public function previousColumn(int $offset = 1): self
{
return $this->nextColumn(0 - $offset);
}
/**
* The returned address string will contain the worksheet name as well, if available,
* (ie. if a Worksheet was provided to the constructor).
* e.g. "'Mark''s Worksheet'!C5".
*/
public function __toString(): string
{
return $this->fullCellAddress();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/Hyperlink.php | src/PhpSpreadsheet/Cell/Hyperlink.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
class Hyperlink
{
/**
* URL to link the cell to.
*/
private string $url;
/**
* Tooltip to display on the hyperlink.
*/
private string $tooltip;
private string $display = '';
/**
* Create a new Hyperlink.
*
* @param string $url Url to link the cell to
* @param string $tooltip Tooltip to display on the hyperlink
*/
public function __construct(string $url = '', string $tooltip = '')
{
// Initialise member variables
$this->url = $url;
$this->tooltip = $tooltip;
}
/**
* Get URL.
*/
public function getUrl(): string
{
return $this->url;
}
/**
* Set URL.
*
* @return $this
*/
public function setUrl(string $url): static
{
$this->url = $url;
return $this;
}
/**
* Get tooltip.
*/
public function getTooltip(): string
{
return $this->tooltip;
}
/**
* Set tooltip.
*
* @return $this
*/
public function setTooltip(string $tooltip): static
{
$this->tooltip = $tooltip;
return $this;
}
/**
* Is this hyperlink internal? (to another worksheet or a cell in this worksheet).
*/
public function isInternal(): bool
{
return str_starts_with($this->url, 'sheet://') || str_starts_with($this->url, '#');
}
public function getTypeHyperlink(): string
{
return $this->isInternal() ? '' : 'External';
}
public function getDisplay(): string
{
return $this->display;
}
/**
* This can be displayed in cell rather than actual cell contents.
* It seems to be ignored by Excel.
* It may be used by Google Sheets.
*/
public function setDisplay(string $display): self
{
$this->display = $display;
return $this;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
return md5(
$this->url
. ','
. $this->tooltip
. ','
. $this->display
. ','
. __CLASS__
);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/AddressHelper.php | src/PhpSpreadsheet/Cell/AddressHelper.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Exception;
class AddressHelper
{
public const R1C1_COORDINATE_REGEX = '/(R((?:\[-?\d*\])|(?:\d*))?)(C((?:\[-?\d*\])|(?:\d*))?)/i';
/** @return string[] */
public static function getRowAndColumnChars(): array
{
$rowChar = 'R';
$colChar = 'C';
if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_EXCEL) {
$rowColChars = Calculation::localeFunc('*RC');
if (mb_strlen($rowColChars) === 2) {
$rowChar = mb_substr($rowColChars, 0, 1);
$colChar = mb_substr($rowColChars, 1, 1);
}
}
return [$rowChar, $colChar];
}
/**
* Converts an R1C1 format cell address to an A1 format cell address.
*/
public static function convertToA1(
string $address,
int $currentRowNumber = 1,
int $currentColumnNumber = 1,
bool $useLocale = true
): string {
[$rowChar, $colChar] = $useLocale ? self::getRowAndColumnChars() : ['R', 'C'];
$regex = '/^(' . $rowChar . '(\[?[-+]?\d*\]?))(' . $colChar . '(\[?[-+]?\d*\]?))$/i';
$validityCheck = preg_match($regex, $address, $cellReference);
if (empty($validityCheck)) {
throw new Exception('Invalid R1C1-format Cell Reference');
}
$rowReference = $cellReference[2];
// Empty R reference is the current row
if ($rowReference === '') {
$rowReference = (string) $currentRowNumber;
}
// Bracketed R references are relative to the current row
if ($rowReference[0] === '[') {
$rowReference = $currentRowNumber + (int) trim($rowReference, '[]');
}
$columnReference = $cellReference[4];
// Empty C reference is the current column
if ($columnReference === '') {
$columnReference = (string) $currentColumnNumber;
}
// Bracketed C references are relative to the current column
if (is_string($columnReference) && $columnReference[0] === '[') { // @phpstan-ignore-line
$columnReference = $currentColumnNumber + (int) trim($columnReference, '[]');
}
$columnReference = (int) $columnReference;
if ($columnReference <= 0 || $rowReference <= 0) {
throw new Exception('Invalid R1C1-format Cell Reference, Value out of range');
}
$A1CellReference = Coordinate::stringFromColumnIndex($columnReference) . $rowReference;
return $A1CellReference;
}
protected static function convertSpreadsheetMLFormula(string $formula): string
{
$formula = substr($formula, 3);
$temp = explode('"', $formula);
$key = false;
foreach ($temp as &$value) {
// Only replace in alternate array entries (i.e. non-quoted blocks)
$key = $key === false;
if ($key) {
$value = str_replace(['[.', ':.', ']'], ['', ':', ''], $value);
}
}
unset($value);
return implode('"', $temp);
}
/**
* Converts a formula that uses R1C1/SpreadsheetXML format cell address to an A1 format cell address.
*/
public static function convertFormulaToA1(
string $formula,
int $currentRowNumber = 1,
int $currentColumnNumber = 1
): string {
if (str_starts_with($formula, 'of:')) {
// We have an old-style SpreadsheetML Formula
return self::convertSpreadsheetMLFormula($formula);
}
// Convert R1C1 style references to A1 style references (but only when not quoted)
$temp = explode('"', $formula);
$key = false;
foreach ($temp as &$value) {
// Only replace in alternate array entries (i.e. non-quoted blocks)
$key = $key === false;
if ($key) {
preg_match_all(self::R1C1_COORDINATE_REGEX, $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
// Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
// through the formula from left to right. Reversing means that we work right to left.through
// the formula
$cellReferences = array_reverse($cellReferences);
// Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
// then modify the formula to use that new reference
foreach ($cellReferences as $cellReference) {
$A1CellReference = self::convertToA1($cellReference[0][0], $currentRowNumber, $currentColumnNumber, false);
$value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0]));
}
}
}
unset($value);
// Then rebuild the formula string
return implode('"', $temp);
}
/**
* Converts an A1 format cell address to an R1C1 format cell address.
* If $currentRowNumber or $currentColumnNumber are provided, then the R1C1 address will be formatted as a relative address.
*/
public static function convertToR1C1(
string $address,
?int $currentRowNumber = null,
?int $currentColumnNumber = null
): string {
if (1 !== preg_match(Coordinate::A1_COORDINATE_REGEX, $address, $cellReference)) {
throw new Exception('Invalid A1-format Cell Reference');
}
if ($cellReference['col'][0] === '$') {
// Column must be absolute address
$currentColumnNumber = null;
}
$columnId = Coordinate::columnIndexFromString(ltrim($cellReference['col'], '$'));
if ($cellReference['row'][0] === '$') {
// Row must be absolute address
$currentRowNumber = null;
}
$rowId = (int) ltrim($cellReference['row'], '$');
if ($currentRowNumber !== null) {
if ($rowId === $currentRowNumber) {
$rowId = '';
} else {
$rowId = '[' . ($rowId - $currentRowNumber) . ']';
}
}
if ($currentColumnNumber !== null) {
if ($columnId === $currentColumnNumber) {
$columnId = '';
} else {
$columnId = '[' . ($columnId - $currentColumnNumber) . ']';
}
}
$R1C1Address = "R{$rowId}C{$columnId}";
return $R1C1Address;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/Coordinate.php | src/PhpSpreadsheet/Cell/Coordinate.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Worksheet\Validations;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
/**
* Helper class to manipulate cell coordinates.
*
* Columns indexes and rows are always based on 1, **not** on 0. This match the behavior
* that Excel users are used to, and also match the Excel functions `COLUMN()` and `ROW()`.
*/
abstract class Coordinate
{
public const A1_COORDINATE_REGEX = '/^(?<col>\$?[A-Z]{1,3})(?<row>\$?\d{1,7})$/i';
public const FULL_REFERENCE_REGEX = '/^(?:(?<worksheet>[^!]*)!)?(?<localReference>(?<firstCoordinate>[$]?[A-Z]{1,3}[$]?\d{1,7})(?:\:(?<secondCoordinate>[$]?[A-Z]{1,3}[$]?\d{1,7}))?)$/i';
/**
* Default range variable constant.
*
* @var string
*/
const DEFAULT_RANGE = 'A1:A1';
/**
* Convert string coordinate to [0 => int column index, 1 => int row index].
*
* @param string $cellAddress eg: 'A1'
*
* @return array{0: string, 1: string} Array containing column and row (indexes 0 and 1)
*/
public static function coordinateFromString(string $cellAddress): array
{
if (preg_match(self::A1_COORDINATE_REGEX, $cellAddress, $matches)) {
return [$matches['col'], $matches['row']];
} elseif (self::coordinateIsRange($cellAddress)) {
throw new Exception('Cell coordinate string can not be a range of cells');
} elseif ($cellAddress == '') {
throw new Exception('Cell coordinate can not be zero-length string');
}
throw new Exception('Invalid cell coordinate ' . $cellAddress);
}
/**
* Convert string coordinate to [0 => int column index, 1 => int row index, 2 => string column string].
*
* @param string $coordinates eg: 'A1', '$B$12'
*
* @return array{0: int, 1: int, 2: string} Array containing column and row index, and column string
*/
public static function indexesFromString(string $coordinates): array
{
[$column, $row] = self::coordinateFromString($coordinates);
$column = ltrim($column, '$');
return [
self::columnIndexFromString($column),
(int) ltrim($row, '$'),
$column,
];
}
/**
* Checks if a Cell Address represents a range of cells.
*
* @param string $cellAddress eg: 'A1' or 'A1:A2' or 'A1:A2,C1:C2'
*
* @return bool Whether the coordinate represents a range of cells
*/
public static function coordinateIsRange(string $cellAddress): bool
{
return str_contains($cellAddress, ':') || str_contains($cellAddress, ',');
}
/**
* Make string row, column or cell coordinate absolute.
*
* @param int|string $cellAddress e.g. 'A' or '1' or 'A1'
* Note that this value can be a row or column reference as well as a cell reference
*
* @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1'
*/
public static function absoluteReference(int|string $cellAddress): string
{
$cellAddress = (string) $cellAddress;
if (self::coordinateIsRange($cellAddress)) {
throw new Exception('Cell coordinate string can not be a range of cells');
}
// Split out any worksheet name from the reference
[$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
if ($worksheet > '') {
$worksheet .= '!';
}
// Create absolute coordinate
$cellAddress = "$cellAddress";
if (ctype_digit($cellAddress)) {
return $worksheet . '$' . $cellAddress;
} elseif (ctype_alpha($cellAddress)) {
return $worksheet . '$' . strtoupper($cellAddress);
}
return $worksheet . self::absoluteCoordinate($cellAddress);
}
/**
* Make string coordinate absolute.
*
* @param string $cellAddress e.g. 'A1'
*
* @return string Absolute coordinate e.g. '$A$1'
*/
public static function absoluteCoordinate(string $cellAddress): string
{
if (self::coordinateIsRange($cellAddress)) {
throw new Exception('Cell coordinate string can not be a range of cells');
}
// Split out any worksheet name from the coordinate
[$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
if ($worksheet > '') {
$worksheet .= '!';
}
// Create absolute coordinate
[$column, $row] = self::coordinateFromString($cellAddress ?? 'A1');
$column = ltrim($column, '$');
$row = ltrim($row, '$');
return $worksheet . '$' . $column . '$' . $row;
}
/**
* Split range into coordinate strings, using comma for union
* and ignoring intersection (space).
*
* @param string $range e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4'
*
* @return array<array<string>> Array containing one or more arrays containing one or two coordinate strings
* e.g. ['B4','D9'] or [['B4','D9'], ['H2','O11']]
* or ['B4']
*/
public static function splitRange(string $range): array
{
// Ensure $pRange is a valid range
if (empty($range)) {
$range = self::DEFAULT_RANGE;
}
$exploded = explode(',', $range);
$outArray = [];
foreach ($exploded as $value) {
$outArray[] = explode(':', $value);
}
return $outArray;
}
/**
* Split range into coordinate strings, resolving unions and intersections.
*
* @param string $range e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4'
* @param bool $unionIsComma true=comma is union, space is intersection
* false=space is union, comma is intersection
*
* @return array<array<string>> Array containing one or more arrays containing one or two coordinate strings
* e.g. ['B4','D9'] or [['B4','D9'], ['H2','O11']]
* or ['B4']
*/
public static function allRanges(string $range, bool $unionIsComma = true): array
{
if (!$unionIsComma) {
$range = str_replace([',', ' ', "\0"], ["\0", ',', ' '], $range);
}
return self::splitRange(
self::resolveUnionAndIntersection($range)
);
}
/**
* Build range from coordinate strings.
*
* @param mixed[] $range Array containing one or more arrays containing one or two coordinate strings
*
* @return string String representation of $pRange
*/
public static function buildRange(array $range): string
{
// Verify range
if (empty($range)) {
throw new Exception('Range does not contain any information');
}
// Build range
$counter = count($range);
for ($i = 0; $i < $counter; ++$i) {
if (!is_array($range[$i])) {
throw new Exception('Each array entry must be an array');
}
$range[$i] = implode(':', $range[$i]);
}
return implode(',', $range);
}
/**
* Calculate range boundaries.
*
* @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3)
*
* @return array{array{int, int}, array{int, int}} Range coordinates [Start Cell, End Cell]
* where Start Cell and End Cell are arrays (Column Number, Row Number)
*/
public static function rangeBoundaries(string $range): array
{
// Ensure $pRange is a valid range
if (empty($range)) {
$range = self::DEFAULT_RANGE;
}
// Uppercase coordinate
$range = strtoupper($range);
// Extract range
if (!str_contains($range, ':')) {
$rangeA = $rangeB = $range;
} else {
[$rangeA, $rangeB] = explode(':', $range);
}
if (is_numeric($rangeA) && is_numeric($rangeB)) {
$rangeA = 'A' . $rangeA;
$rangeB = AddressRange::MAX_COLUMN . $rangeB;
}
if (ctype_alpha($rangeA) && ctype_alpha($rangeB)) {
$rangeA = $rangeA . '1';
$rangeB = $rangeB . AddressRange::MAX_ROW;
}
// Calculate range outer borders
$rangeStart = self::coordinateFromString($rangeA);
$rangeEnd = self::coordinateFromString($rangeB);
// Translate column into index
$rangeStart[0] = self::columnIndexFromString($rangeStart[0]);
$rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]);
$rangeStart[1] = (int) $rangeStart[1];
$rangeEnd[1] = (int) $rangeEnd[1];
return [$rangeStart, $rangeEnd];
}
/**
* Calculate range dimension.
*
* @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3)
*
* @return array{int, int} Range dimension (width, height)
*/
public static function rangeDimension(string $range): array
{
// Calculate range outer borders
[$rangeStart, $rangeEnd] = self::rangeBoundaries($range);
return [($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1)];
}
/**
* Calculate range boundaries.
*
* @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3)
*
* @return array{array{string, int}, array{string, int}} Range coordinates [Start Cell, End Cell]
* where Start Cell and End Cell are arrays [Column ID, Row Number]
*/
public static function getRangeBoundaries(string $range): array
{
[$rangeA, $rangeB] = self::rangeBoundaries($range);
return [
[self::stringFromColumnIndex($rangeA[0]), $rangeA[1]],
[self::stringFromColumnIndex($rangeB[0]), $rangeB[1]],
];
}
/**
* Check if cell or range reference is valid and return an array with type of reference (cell or range), worksheet (if it was given)
* and the coordinate or the first coordinate and second coordinate if it is a range.
*
* @param string $reference Coordinate or Range (e.g. A1:A1, B2, B:C, 2:3)
*
* @return array{type: string, firstCoordinate?: string, secondCoordinate?: string, coordinate?: string, worksheet?: string, localReference?: string} reference data
*/
private static function validateReferenceAndGetData($reference): array
{
$data = [];
if (1 !== preg_match(self::FULL_REFERENCE_REGEX, $reference, $matches)) {
return ['type' => 'invalid'];
}
if (isset($matches['secondCoordinate'])) {
$data['type'] = 'range';
$data['firstCoordinate'] = str_replace('$', '', $matches['firstCoordinate']);
$data['secondCoordinate'] = str_replace('$', '', $matches['secondCoordinate']);
} else {
$data['type'] = 'coordinate';
$data['coordinate'] = str_replace('$', '', $matches['firstCoordinate']);
}
$worksheet = $matches['worksheet'];
if ($worksheet !== '') {
if (str_starts_with($worksheet, "'") && str_ends_with($worksheet, "'")) {
$worksheet = substr($worksheet, 1, -1);
}
$data['worksheet'] = strtolower($worksheet);
}
$data['localReference'] = str_replace('$', '', $matches['localReference']);
return $data;
}
/**
* Check if coordinate is inside a range.
*
* @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3)
* @param string $coordinate Cell coordinate (e.g. A1)
*
* @return bool true if coordinate is inside range
*/
public static function coordinateIsInsideRange(string $range, string $coordinate): bool
{
$range = Validations::convertWholeRowColumn($range);
$rangeData = self::validateReferenceAndGetData($range);
if ($rangeData['type'] === 'invalid') {
throw new Exception('First argument needs to be a range');
}
$coordinateData = self::validateReferenceAndGetData($coordinate);
if ($coordinateData['type'] === 'invalid') {
throw new Exception('Second argument needs to be a single coordinate');
}
if (isset($coordinateData['worksheet']) && !isset($rangeData['worksheet'])) {
return false;
}
if (!isset($coordinateData['worksheet']) && isset($rangeData['worksheet'])) {
return false;
}
if (isset($coordinateData['worksheet'], $rangeData['worksheet'])) {
if ($coordinateData['worksheet'] !== $rangeData['worksheet']) {
return false;
}
}
if (!isset($rangeData['localReference'])) {
return false;
}
$boundaries = self::rangeBoundaries($rangeData['localReference']);
if (!isset($coordinateData['localReference'])) {
return false;
}
$coordinates = self::indexesFromString($coordinateData['localReference']);
$columnIsInside = $boundaries[0][0] <= $coordinates[0] && $coordinates[0] <= $boundaries[1][0];
if (!$columnIsInside) {
return false;
}
$rowIsInside = $boundaries[0][1] <= $coordinates[1] && $coordinates[1] <= $boundaries[1][1];
if (!$rowIsInside) {
return false;
}
return true;
}
/**
* Column index from string.
*
* @param ?string $columnAddress eg 'A'
*
* @return int Column index (A = 1)
*/
public static function columnIndexFromString(?string $columnAddress): int
{
// Using a lookup cache adds a slight memory overhead, but boosts speed
// caching using a static within the method is faster than a class static,
// though it's additional memory overhead
/** @var int[] */
static $indexCache = [];
$columnAddress = $columnAddress ?? '';
if (isset($indexCache[$columnAddress])) {
return $indexCache[$columnAddress];
}
// It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array
// rather than use ord() and make it case-insensitive to get rid of the strtoupper() as well.
// Because it's a static, there's no significant memory overhead either.
/** @var array<string, int> */
static $columnLookup = [
'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10,
'K' => 11, 'L' => 12, 'M' => 13, 'N' => 14, 'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19,
'T' => 20, 'U' => 21, 'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26,
'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10,
'k' => 11, 'l' => 12, 'm' => 13, 'n' => 14, 'o' => 15, 'p' => 16, 'q' => 17, 'r' => 18, 's' => 19,
't' => 20, 'u' => 21, 'v' => 22, 'w' => 23, 'x' => 24, 'y' => 25, 'z' => 26,
];
// We also use the language construct isset() rather than the more costly strlen() function to match the
// length of $columnAddress for improved performance
if (isset($columnAddress[0])) {
if (!isset($columnAddress[1])) {
$indexCache[$columnAddress] = $columnLookup[$columnAddress];
return $indexCache[$columnAddress];
} elseif (!isset($columnAddress[2])) {
$indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 26
+ $columnLookup[$columnAddress[1]];
return $indexCache[$columnAddress];
} elseif (!isset($columnAddress[3])) {
$indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 676
+ $columnLookup[$columnAddress[1]] * 26
+ $columnLookup[$columnAddress[2]];
return $indexCache[$columnAddress];
}
}
throw new Exception(
'Column string index can not be ' . ((isset($columnAddress[0])) ? 'longer than 3 characters' : 'empty')
);
}
private const LOOKUP_CACHE = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ';
/**
* String from column index.
*
* @param int|numeric-string $columnIndex Column index (A = 1)
*/
public static function stringFromColumnIndex(int|string $columnIndex): string
{
/** @var string[] */
static $indexCache = [];
if (!isset($indexCache[$columnIndex])) {
$indexValue = $columnIndex;
$base26 = '';
do {
$characterValue = ($indexValue % 26) ?: 26;
$indexValue = ($indexValue - $characterValue) / 26;
$base26 = self::LOOKUP_CACHE[$characterValue] . $base26;
} while ($indexValue > 0);
$indexCache[$columnIndex] = $base26;
}
return $indexCache[$columnIndex];
}
/**
* Extract all cell references in range, which may be comprised of multiple cell ranges.
*
* @param string $cellRange Range: e.g. 'A1' or 'A1:C10' or 'A1:E10,A20:E25' or 'A1:E5 C3:G7' or 'A1:C1,A3:C3 B1:C3'
*
* @return string[] Array containing single cell references
*/
public static function extractAllCellReferencesInRange(string $cellRange): array
{
if (substr_count($cellRange, '!') > 1) {
throw new Exception('3-D Range References are not supported');
}
[$worksheet, $cellRange] = Worksheet::extractSheetTitle($cellRange, true);
$quoted = '';
if ($worksheet) {
$quoted = Worksheet::nameRequiresQuotes($worksheet) ? "'" : '';
if (str_starts_with($worksheet, "'") && str_ends_with($worksheet, "'")) {
$worksheet = substr($worksheet, 1, -1);
}
$worksheet = str_replace("'", "''", $worksheet);
}
[$ranges, $operators] = self::getCellBlocksFromRangeString($cellRange ?? 'A1');
$cells = [];
foreach ($ranges as $range) {
/** @var string $range */
$cells[] = self::getReferencesForCellBlock($range);
}
/** @var mixed[] */
$cells = self::processRangeSetOperators($operators, $cells);
if (empty($cells)) {
return [];
}
/** @var string[] */
$cellList = array_merge(...$cells); //* @phpstan-ignore-line
// Unsure how to satisfy phpstan in line above
$retVal = array_map(
fn (string $cellAddress) => ($worksheet !== '') ? "{$quoted}{$worksheet}{$quoted}!{$cellAddress}" : $cellAddress,
self::sortCellReferenceArray($cellList)
);
return $retVal;
}
/**
* @param mixed[] $operators
* @param mixed[][] $cells
*
* @return mixed[]
*/
private static function processRangeSetOperators(array $operators, array $cells): array
{
$operatorCount = count($operators);
for ($offset = 0; $offset < $operatorCount; ++$offset) {
$operator = $operators[$offset];
if ($operator !== ' ') {
continue;
}
$cells[$offset] = array_intersect($cells[$offset], $cells[$offset + 1]);
unset($operators[$offset], $cells[$offset + 1]);
$operators = array_values($operators);
$cells = array_values($cells);
--$offset;
--$operatorCount;
}
return $cells;
}
/**
* @param string[] $cellList
*
* @return string[]
*/
private static function sortCellReferenceArray(array $cellList): array
{
// Sort the result by column and row
$sortKeys = [];
foreach ($cellList as $coordinate) {
$column = '';
$row = 0;
sscanf($coordinate, '%[A-Z]%d', $column, $row);
/** @var int $row */
$key = (--$row * 16384) + self::columnIndexFromString((string) $column);
$sortKeys[$key] = $coordinate;
}
ksort($sortKeys);
return array_values($sortKeys);
}
/**
* Get all cell references applying union and intersection.
*
* @param string $cellBlock A cell range e.g. A1:B5,D1:E5 B2:C4
*
* @return string A string without intersection operator.
* If there was no intersection to begin with, return original argument.
* Otherwise, return cells and/or cell ranges in that range separated by comma.
*/
public static function resolveUnionAndIntersection(string $cellBlock, string $implodeCharacter = ','): string
{
$cellBlock = preg_replace('/ +/', ' ', trim($cellBlock)) ?? $cellBlock;
$cellBlock = preg_replace('/ ,/', ',', $cellBlock) ?? $cellBlock;
$cellBlock = preg_replace('/, /', ',', $cellBlock) ?? $cellBlock;
$array1 = [];
$blocks = explode(',', $cellBlock);
foreach ($blocks as $block) {
$block0 = explode(' ', $block);
if (count($block0) === 1) {
$array1 = array_merge($array1, $block0);
} else {
$blockIdx = -1;
$array2 = [];
foreach ($block0 as $block00) {
++$blockIdx;
if ($blockIdx === 0) {
$array2 = self::getReferencesForCellBlock($block00);
} else {
$array2 = array_intersect($array2, self::getReferencesForCellBlock($block00));
}
}
$array1 = array_merge($array1, $array2);
}
}
return implode($implodeCharacter, $array1);
}
/**
* Get all cell references for an individual cell block.
*
* @param string $cellBlock A cell range e.g. A4:B5
*
* @return string[] All individual cells in that range
*/
private static function getReferencesForCellBlock(string $cellBlock): array
{
$returnValue = [];
// Single cell?
if (!self::coordinateIsRange($cellBlock)) {
return (array) $cellBlock;
}
// Range...
$ranges = self::splitRange($cellBlock);
foreach ($ranges as $range) {
// Single cell?
if (!isset($range[1])) {
$returnValue[] = $range[0];
continue;
}
// Range...
[$rangeStart, $rangeEnd] = $range;
[$startColumn, $startRow] = self::coordinateFromString($rangeStart);
[$endColumn, $endRow] = self::coordinateFromString($rangeEnd);
$startColumnIndex = self::columnIndexFromString($startColumn);
$endColumnIndex = self::columnIndexFromString($endColumn);
++$endColumnIndex;
// Current data
$currentColumnIndex = $startColumnIndex;
$currentRow = $startRow;
self::validateRange($cellBlock, $startColumnIndex, $endColumnIndex, (int) $currentRow, (int) $endRow);
// Loop cells
while ($currentColumnIndex < $endColumnIndex) {
/** @var int $currentRow */
/** @var int $endRow */
while ($currentRow <= $endRow) {
$returnValue[] = self::stringFromColumnIndex($currentColumnIndex) . $currentRow;
++$currentRow;
}
++$currentColumnIndex;
$currentRow = $startRow;
}
}
return $returnValue;
}
/**
* Convert an associative array of single cell coordinates to values to an associative array
* of cell ranges to values. Only adjacent cell coordinates with the same
* value will be merged. If the value is an object, it must implement the method getHashCode().
*
* For example, this function converts:
*
* [ 'A1' => 'x', 'A2' => 'x', 'A3' => 'x', 'A4' => 'y' ]
*
* to:
*
* [ 'A1:A3' => 'x', 'A4' => 'y' ]
*
* @param array<string, mixed> $coordinateCollection associative array mapping coordinates to values
*
* @return array<string, mixed> associative array mapping coordinate ranges to values
*/
public static function mergeRangesInCollection(array $coordinateCollection): array
{
$hashedValues = [];
$mergedCoordCollection = [];
foreach ($coordinateCollection as $coord => $value) {
if (self::coordinateIsRange($coord)) {
$mergedCoordCollection[$coord] = $value;
continue;
}
[$column, $row] = self::coordinateFromString($coord);
$row = (int) (ltrim($row, '$'));
$hashCode = $column . '-' . StringHelper::convertToString((is_object($value) && method_exists($value, 'getHashCode')) ? $value->getHashCode() : $value);
if (!isset($hashedValues[$hashCode])) {
$hashedValues[$hashCode] = (object) [
'value' => $value,
'col' => $column,
'rows' => [$row],
];
} else {
$hashedValues[$hashCode]->rows[] = $row;
}
}
ksort($hashedValues);
foreach ($hashedValues as $hashedValue) {
sort($hashedValue->rows);
$rowStart = null;
$rowEnd = null;
$ranges = [];
foreach ($hashedValue->rows as $row) {
if ($rowStart === null) {
$rowStart = $row;
$rowEnd = $row;
} elseif ($rowEnd === $row - 1) {
$rowEnd = $row;
} else {
if ($rowStart == $rowEnd) {
$ranges[] = $hashedValue->col . $rowStart;
} else {
$ranges[] = $hashedValue->col . $rowStart . ':' . $hashedValue->col . $rowEnd;
}
$rowStart = $row;
$rowEnd = $row;
}
}
if ($rowStart !== null) { // @phpstan-ignore-line
if ($rowStart == $rowEnd) {
$ranges[] = $hashedValue->col . $rowStart;
} else {
$ranges[] = $hashedValue->col . $rowStart . ':' . $hashedValue->col . $rowEnd;
}
}
foreach ($ranges as $range) {
$mergedCoordCollection[$range] = $hashedValue->value;
}
}
return $mergedCoordCollection;
}
/**
* Get the individual cell blocks from a range string, removing any $ characters.
* then splitting by operators and returning an array with ranges and operators.
*
* @return mixed[][]
*/
private static function getCellBlocksFromRangeString(string $rangeString): array
{
$rangeString = str_replace('$', '', strtoupper($rangeString));
// split range sets on intersection (space) or union (,) operators
$tokens = preg_split('/([ ,])/', $rangeString, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [];
$split = array_chunk($tokens, 2);
$ranges = array_column($split, 0);
$operators = array_column($split, 1);
return [$ranges, $operators];
}
/**
* Check that the given range is valid, i.e. that the start column and row are not greater than the end column and
* row.
*
* @param string $cellBlock The original range, for displaying a meaningful error message
*/
private static function validateRange(string $cellBlock, int $startColumnIndex, int $endColumnIndex, int $currentRow, int $endRow): void
{
if ($startColumnIndex >= $endColumnIndex || $currentRow > $endRow) {
throw new Exception('Invalid range: "' . $cellBlock . '"');
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php | src/PhpSpreadsheet/Cell/AdvancedValueBinder.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Engine\FormattedNumber;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
{
/**
* Bind value to a cell.
*
* @param Cell $cell Cell to bind value to
* @param mixed $value Value to bind in cell
*/
public function bindValue(Cell $cell, mixed $value = null): bool
{
if ($value === null) {
return parent::bindValue($cell, $value);
} elseif (is_string($value)) {
// sanitize UTF-8 strings
$value = StringHelper::sanitizeUTF8($value);
}
// Find out data type
$dataType = parent::dataTypeForValue($value);
// Style logic - strings
if ($dataType === DataType::TYPE_STRING && is_string($value)) {
// Test for booleans using locale-setting
if (StringHelper::strToUpper($value) === Calculation::getTRUE()) {
$cell->setValueExplicit(true, DataType::TYPE_BOOL);
return true;
} elseif (StringHelper::strToUpper($value) === Calculation::getFALSE()) {
$cell->setValueExplicit(false, DataType::TYPE_BOOL);
return true;
}
// Check for fractions
if (preg_match('~^([+-]?)\s*(\d+)\s*/\s*(\d+)$~', $value, $matches)) {
return $this->setProperFraction($matches, $cell);
} elseif (preg_match('~^([+-]?)(\d+)\s+(\d+)\s*/\s*(\d+)$~', $value, $matches)) {
return $this->setImproperFraction($matches, $cell);
}
$decimalSeparatorNoPreg = StringHelper::getDecimalSeparator();
$decimalSeparator = preg_quote($decimalSeparatorNoPreg, '/');
$thousandsSeparator = preg_quote(StringHelper::getThousandsSeparator(), '/');
// Check for percentage
if (preg_match('/^\-?\d*' . $decimalSeparator . '?\d*\s?\%$/', (string) preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $value))) {
return $this->setPercentage((string) preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $value), $cell);
}
// Check for currency
if (preg_match(FormattedNumber::currencyMatcherRegexp(), (string) preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $value), $matches, PREG_UNMATCHED_AS_NULL)) {
// Convert value to number
$sign = ($matches['PrefixedSign'] ?? $matches['PrefixedSign2'] ?? $matches['PostfixedSign']) ?? null;
$currencyCode = $matches['PrefixedCurrency'] ?? $matches['PostfixedCurrency'] ?? '';
/** @var string */
$temp = str_replace([$decimalSeparatorNoPreg, $currencyCode, ' ', '-'], ['.', '', '', ''], (string) preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $value));
$value = (float) ($sign . trim($temp));
return $this->setCurrency($value, $cell, $currencyCode);
}
// Check for time without seconds e.g. '9:45', '09:45'
if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d$/', $value)) {
return $this->setTimeHoursMinutes($value, $cell);
}
// Check for time with seconds '9:45:59', '09:45:59'
if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)) {
return $this->setTimeHoursMinutesSeconds($value, $cell);
}
// Check for datetime, e.g. '2008-12-31', '2008-12-31 15:59', '2008-12-31 15:59:10'
if (($d = Date::stringToExcel($value)) !== false) {
// Convert value to number
$cell->setValueExplicit($d, DataType::TYPE_NUMERIC);
// Determine style. Either there is a time part or not. Look for ':'
if (str_contains($value, ':')) {
$formatCode = 'yyyy-mm-dd h:mm';
} else {
$formatCode = 'yyyy-mm-dd';
}
$cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode($formatCode);
return true;
}
// Check for newline character "\n"
if (str_contains($value, "\n")) {
$cell->setValueExplicit($value, DataType::TYPE_STRING);
// Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate())
->getAlignment()->setWrapText(true);
return true;
}
}
// Not bound yet? Use parent...
return parent::bindValue($cell, $value);
}
/** @param array{0: string, 1: ?string, 2: numeric-string, 3: numeric-string, 4: numeric-string} $matches */
protected function setImproperFraction(array $matches, Cell $cell): bool
{
// Convert value to number
$value = $matches[2] + ($matches[3] / $matches[4]);
if ($matches[1] === '-') {
$value = 0 - $value;
}
$cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC);
// Build the number format mask based on the size of the matched values
$dividend = str_repeat('?', strlen($matches[3]));
$divisor = str_repeat('?', strlen($matches[4]));
$fractionMask = "# {$dividend}/{$divisor}";
// Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode($fractionMask);
return true;
}
/** @param array{0: string, 1: ?string, 2: numeric-string, 3: numeric-string} $matches */
protected function setProperFraction(array $matches, Cell $cell): bool
{
// Convert value to number
$value = $matches[2] / $matches[3];
if ($matches[1] === '-') {
$value = 0 - $value;
}
$cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC);
// Build the number format mask based on the size of the matched values
$dividend = str_repeat('?', strlen($matches[2]));
$divisor = str_repeat('?', strlen($matches[3]));
$fractionMask = "{$dividend}/{$divisor}";
// Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode($fractionMask);
return true;
}
protected function setPercentage(string $value, Cell $cell): bool
{
// Convert value to number
$value = ((float) str_replace('%', '', $value)) / 100;
$cell->setValueExplicit($value, DataType::TYPE_NUMERIC);
// Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_PERCENTAGE_00);
return true;
}
protected function setCurrency(float $value, Cell $cell, string $currencyCode): bool
{
$cell->setValueExplicit($value, DataType::TYPE_NUMERIC);
// Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode(
str_replace('$', '[$' . $currencyCode . ']', NumberFormat::FORMAT_CURRENCY_USD)
);
return true;
}
protected function setTimeHoursMinutes(string $value, Cell $cell): bool
{
// Convert value to number
[$hours, $minutes] = explode(':', $value);
$hours = (int) $hours;
$minutes = (int) $minutes;
$days = ($hours / 24) + ($minutes / 1440);
$cell->setValueExplicit($days, DataType::TYPE_NUMERIC);
// Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME3);
return true;
}
protected function setTimeHoursMinutesSeconds(string $value, Cell $cell): bool
{
// Convert value to number
[$hours, $minutes, $seconds] = explode(':', $value);
$hours = (int) $hours;
$minutes = (int) $minutes;
$seconds = (int) $seconds;
$days = ($hours / 24) + ($minutes / 1440) + ($seconds / 86400);
$cell->setValueExplicit($days, DataType::TYPE_NUMERIC);
// Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate())
->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME4);
return true;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/DataType.php | src/PhpSpreadsheet/Cell/DataType.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
class DataType
{
// Data types
const TYPE_STRING2 = 'str';
const TYPE_STRING = 's';
const TYPE_FORMULA = 'f';
const TYPE_NUMERIC = 'n';
const TYPE_BOOL = 'b';
const TYPE_NULL = 'null';
const TYPE_INLINE = 'inlineStr';
const TYPE_ERROR = 'e';
const TYPE_ISO_DATE = 'd';
/**
* List of error codes.
*
* @var array<string, int>
*/
private static array $errorCodes = [
'#NULL!' => 0,
'#DIV/0!' => 1,
'#VALUE!' => 2,
'#REF!' => 3,
'#NAME?' => 4,
'#NUM!' => 5,
'#N/A' => 6,
'#CALC!' => 7,
];
public const MAX_STRING_LENGTH = 32767;
/**
* Get list of error codes.
*
* @return array<string, int>
*/
public static function getErrorCodes(): array
{
return self::$errorCodes;
}
/**
* Check a string that it satisfies Excel requirements.
*
* @param null|RichText|string $textValue Value to sanitize to an Excel string
*
* @return RichText|string Sanitized value
*/
public static function checkString(null|RichText|string $textValue, bool $preserveCr = false): RichText|string
{
if ($textValue instanceof RichText) {
// TODO: Sanitize Rich-Text string (max. character count is 32,767)
return $textValue;
}
// string must never be longer than 32,767 characters, truncate if necessary
$textValue = StringHelper::substring((string) $textValue, 0, self::MAX_STRING_LENGTH);
// we require that newline is represented as "\n" in core, not as "\r\n" or "\r"
if (!$preserveCr) {
$textValue = str_replace(["\r\n", "\r"], "\n", $textValue);
}
return $textValue;
}
/**
* Check a value that it is a valid error code.
*
* @param mixed $value Value to sanitize to an Excel error code
*
* @return string Sanitized value
*/
public static function checkErrorCode(mixed $value): string
{
$default = '#NULL!';
$value = ($value === null) ? $default : StringHelper::convertToString($value, false, $default);
if (!isset(self::$errorCodes[$value])) {
$value = $default;
}
return $value;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Cell/DataValidator.php | src/PhpSpreadsheet/Cell/DataValidator.php | <?php
namespace PhpOffice\PhpSpreadsheet\Cell;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
/**
* Validate a cell value according to its validation rules.
*/
class DataValidator
{
/**
* Does this cell contain valid value?
*
* @param Cell $cell Cell to check the value
*/
public function isValid(Cell $cell): bool
{
if (!$cell->hasDataValidation() || $cell->getDataValidation()->getType() === DataValidation::TYPE_NONE) {
return true;
}
$cellValue = $cell->getValue();
$dataValidation = $cell->getDataValidation();
if (!$dataValidation->getAllowBlank() && ($cellValue === null || $cellValue === '')) {
return false;
}
$returnValue = false;
$type = $dataValidation->getType();
if ($type === DataValidation::TYPE_LIST) {
$returnValue = $this->isValueInList($cell);
} elseif ($type === DataValidation::TYPE_WHOLE) {
if (!is_numeric($cellValue) || fmod((float) $cellValue, 1) != 0) {
$returnValue = false;
} else {
$returnValue = $this->numericOperator($dataValidation, (int) $cellValue, $cell);
}
} elseif ($type === DataValidation::TYPE_DECIMAL || $type === DataValidation::TYPE_DATE || $type === DataValidation::TYPE_TIME) {
if (!is_numeric($cellValue)) {
$returnValue = false;
} else {
$returnValue = $this->numericOperator($dataValidation, (float) $cellValue, $cell);
}
} elseif ($type === DataValidation::TYPE_TEXTLENGTH) {
$returnValue = $this->numericOperator($dataValidation, mb_strlen($cell->getValueString()), $cell);
}
return $returnValue;
}
private const TWO_FORMULAS = [DataValidation::OPERATOR_BETWEEN, DataValidation::OPERATOR_NOTBETWEEN];
private static function evaluateNumericFormula(mixed $formula, Cell $cell): mixed
{
if (!is_numeric($formula)) {
$calculation = Calculation::getInstance($cell->getWorksheet()->getParent());
try {
$formula2 = StringHelper::convertToString($formula);
$result = $calculation
->calculateFormula("=$formula2", $cell->getCoordinate(), $cell);
while (is_array($result)) {
$result = array_pop($result);
}
$formula = $result;
} catch (Exception) {
// do nothing
}
}
return $formula;
}
private function numericOperator(DataValidation $dataValidation, int|float $cellValue, Cell $cell): bool
{
$operator = $dataValidation->getOperator();
$formula1 = self::evaluateNumericFormula(
$dataValidation->getFormula1(),
$cell
);
$formula2 = 0;
if (in_array($operator, self::TWO_FORMULAS, true)) {
$formula2 = self::evaluateNumericFormula(
$dataValidation->getFormula2(),
$cell
);
}
return match ($operator) {
DataValidation::OPERATOR_BETWEEN => $cellValue >= $formula1 && $cellValue <= $formula2,
DataValidation::OPERATOR_NOTBETWEEN => $cellValue < $formula1 || $cellValue > $formula2,
DataValidation::OPERATOR_EQUAL => $cellValue == $formula1,
DataValidation::OPERATOR_NOTEQUAL => $cellValue != $formula1,
DataValidation::OPERATOR_LESSTHAN => $cellValue < $formula1,
DataValidation::OPERATOR_LESSTHANOREQUAL => $cellValue <= $formula1,
DataValidation::OPERATOR_GREATERTHAN => $cellValue > $formula1,
DataValidation::OPERATOR_GREATERTHANOREQUAL => $cellValue >= $formula1,
default => false,
};
}
/**
* Does this cell contain valid value, based on list?
*
* @param Cell $cell Cell to check the value
*/
private function isValueInList(Cell $cell): bool
{
$cellValueString = $cell->getValueString();
$dataValidation = $cell->getDataValidation();
$formula1 = $dataValidation->getFormula1();
if (!empty($formula1)) {
// inline values list
if ($formula1[0] === '"') {
return in_array(strtolower($cellValueString), explode(',', strtolower(trim($formula1, '"'))), true);
}
$calculation = Calculation::getInstance($cell->getWorksheet()->getParent());
try {
$result = $calculation->calculateFormula("=$formula1", $cell->getCoordinate(), $cell);
$result = is_array($result) ? Functions::flattenArray($result) : [$result];
foreach ($result as $oneResult) {
if (is_scalar($oneResult) && strcasecmp((string) $oneResult, $cellValueString) === 0) {
return true;
}
}
} catch (Exception) {
// do nothing
}
return false;
}
return true;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/BaseWriter.php | src/PhpSpreadsheet/Writer/BaseWriter.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer;
abstract class BaseWriter implements IWriter
{
/**
* Write charts that are defined in the workbook?
* Identifies whether the Writer should write definitions for any charts that exist in the PhpSpreadsheet object.
*/
protected bool $includeCharts = false;
/**
* Pre-calculate formulas
* Forces PhpSpreadsheet to recalculate all formulae in a workbook when saving, so that the pre-calculated values are
* immediately available to MS Excel or other office spreadsheet viewer when opening the file.
*/
protected bool $preCalculateFormulas = true;
/**
* Use disk caching where possible?
*/
private bool $useDiskCaching = false;
/**
* Disk caching directory.
*/
private string $diskCachingDirectory = './';
/**
* @var resource
*/
protected $fileHandle;
private bool $shouldCloseFile;
public function getIncludeCharts(): bool
{
return $this->includeCharts;
}
public function setIncludeCharts(bool $includeCharts): self
{
$this->includeCharts = $includeCharts;
return $this;
}
public function getPreCalculateFormulas(): bool
{
return $this->preCalculateFormulas;
}
public function setPreCalculateFormulas(bool $precalculateFormulas): self
{
$this->preCalculateFormulas = $precalculateFormulas;
return $this;
}
public function getUseDiskCaching(): bool
{
return $this->useDiskCaching;
}
public function setUseDiskCaching(bool $useDiskCache, ?string $cacheDirectory = null): self
{
$this->useDiskCaching = $useDiskCache;
if ($cacheDirectory !== null) {
if (is_dir($cacheDirectory)) {
$this->diskCachingDirectory = $cacheDirectory;
} else {
throw new Exception("Directory does not exist: $cacheDirectory");
}
}
return $this;
}
public function getDiskCachingDirectory(): string
{
return $this->diskCachingDirectory;
}
protected function processFlags(int $flags): void
{
if (((bool) ($flags & self::SAVE_WITH_CHARTS)) === true) {
$this->setIncludeCharts(true);
}
if (((bool) ($flags & self::DISABLE_PRECALCULATE_FORMULAE)) === true) {
$this->setPreCalculateFormulas(false);
}
}
/**
* Open file handle.
*
* @param resource|string $filename
*/
public function openFileHandle($filename): void
{
if (!is_string($filename)) {
$this->fileHandle = $filename;
$this->shouldCloseFile = false;
return;
}
$mode = 'wb';
$scheme = parse_url($filename, PHP_URL_SCHEME);
if ($scheme === 's3') {
// @codeCoverageIgnoreStart
$mode = 'w';
// @codeCoverageIgnoreEnd
}
$fileHandle = $filename ? fopen($filename, $mode) : false;
if ($fileHandle === false) {
throw new Exception('Could not open file "' . $filename . '" for writing.');
}
$this->fileHandle = $fileHandle;
$this->shouldCloseFile = true;
}
protected function tryClose(): bool
{
return fclose($this->fileHandle);
}
/**
* Close file handle only if we opened it ourselves.
*/
protected function maybeCloseFileHandle(): void
{
if ($this->shouldCloseFile) {
if (!$this->tryClose()) {
throw new Exception('Could not close file after writing.');
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/IWriter.php | src/PhpSpreadsheet/Writer/IWriter.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
interface IWriter
{
public const SAVE_WITH_CHARTS = 1;
public const DISABLE_PRECALCULATE_FORMULAE = 2;
/**
* IWriter constructor.
*
* @param Spreadsheet $spreadsheet The spreadsheet that we want to save using this Writer
*/
public function __construct(Spreadsheet $spreadsheet);
/**
* Write charts in workbook?
* If this is true, then the Writer will write definitions for any charts that exist in the PhpSpreadsheet object.
* If false (the default) it will ignore any charts defined in the PhpSpreadsheet object.
*/
public function getIncludeCharts(): bool;
/**
* Set write charts in workbook
* Set to true, to advise the Writer to include any charts that exist in the PhpSpreadsheet object.
* Set to false (the default) to ignore charts.
*
* @return $this
*/
public function setIncludeCharts(bool $includeCharts): self;
/**
* Get Pre-Calculate Formulas flag
* If this is true (the default), then the writer will recalculate all formulae in a workbook when saving,
* so that the pre-calculated values are immediately available to MS Excel or other office spreadsheet
* viewer when opening the file
* If false, then formulae are not calculated on save. This is faster for saving in PhpSpreadsheet, but slower
* when opening the resulting file in MS Excel, because Excel has to recalculate the formulae itself.
*/
public function getPreCalculateFormulas(): bool;
/**
* Set Pre-Calculate Formulas
* Set to true (the default) to advise the Writer to calculate all formulae on save
* Set to false to prevent precalculation of formulae on save.
*
* @param bool $precalculateFormulas Pre-Calculate Formulas?
*
* @return $this
*/
public function setPreCalculateFormulas(bool $precalculateFormulas): self;
/**
* Save PhpSpreadsheet to file.
*
* @param resource|string $filename Name of the file to save
* @param int $flags Flags that can change the behaviour of the Writer:
* self::SAVE_WITH_CHARTS Save any charts that are defined (if the Writer supports Charts)
* self::DISABLE_PRECALCULATE_FORMULAE Don't Precalculate formulae before saving the file
*
* @throws Exception
*/
public function save($filename, int $flags = 0): void;
/**
* Get use disk caching where possible?
*/
public function getUseDiskCaching(): bool;
/**
* Set use disk caching where possible?
*
* @param ?string $cacheDirectory Disk caching directory
*
* @return $this
*/
public function setUseDiskCaching(bool $useDiskCache, ?string $cacheDirectory = null): self;
/**
* Get disk caching directory.
*/
public function getDiskCachingDirectory(): string;
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/ZipStream0.php | src/PhpSpreadsheet/Writer/ZipStream0.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use ZipStream\Option\Archive;
use ZipStream\ZipStream;
class ZipStream0
{
/**
* @param resource $fileHandle
*/
public static function newZipStream($fileHandle): ZipStream
{
return class_exists(Archive::class) ? ZipStream2::newZipStream($fileHandle) : ZipStream3::newZipStream($fileHandle);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Exception.php | src/PhpSpreadsheet/Writer/Exception.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer;
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/Writer/Csv.php | src/PhpSpreadsheet/Writer/Csv.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use Composer\Pcre\Preg;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Csv extends BaseWriter
{
/**
* PhpSpreadsheet object.
*/
private Spreadsheet $spreadsheet;
/**
* Delimiter.
*/
private string $delimiter = ',';
/**
* Enclosure.
*/
private string $enclosure = '"';
/**
* Line ending.
*/
private string $lineEnding = PHP_EOL;
/**
* Sheet index to write.
*/
private int $sheetIndex = 0;
/**
* Whether to write a UTF8 BOM.
*/
private bool $useBOM = false;
/**
* Whether to write a Separator line as the first line of the file
* sep=x.
*/
private bool $includeSeparatorLine = false;
/**
* Whether to write a fully Excel compatible CSV file.
*/
private bool $excelCompatibility = false;
/**
* Output encoding.
*/
private string $outputEncoding = '';
/**
* Whether number of columns should be allowed to vary
* between rows, or use a fixed range based on the max
* column overall.
*/
private bool $variableColumns = false;
private bool $preferHyperlinkToLabel = false;
/**
* Create a new CSV.
*/
public function __construct(Spreadsheet $spreadsheet)
{
$this->spreadsheet = $spreadsheet;
}
/**
* Save PhpSpreadsheet to file.
*
* @param resource|string $filename
*/
public function save($filename, int $flags = 0): void
{
$this->processFlags($flags);
// Fetch sheet
$sheet = $this->spreadsheet->getSheet($this->sheetIndex);
$saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog();
Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false);
$sheet->calculateArrays($this->preCalculateFormulas);
// Open file
$this->openFileHandle($filename);
if ($this->excelCompatibility) {
$this->setUseBOM(true); // Enforce UTF-8 BOM Header
$this->setIncludeSeparatorLine(true); // Set separator line
$this->setEnclosure('"'); // Set enclosure to "
$this->setDelimiter(';'); // Set delimiter to a semicolon
$this->setLineEnding("\r\n");
}
if ($this->useBOM) {
// Write the UTF-8 BOM code if required
fwrite($this->fileHandle, "\xEF\xBB\xBF");
}
if ($this->includeSeparatorLine) {
// Write the separator line if required
fwrite($this->fileHandle, 'sep=' . $this->getDelimiter() . $this->lineEnding);
}
// Identify the range that we need to extract from the worksheet
$maxCol = $sheet->getHighestDataColumn();
$maxRow = $sheet->getHighestDataRow();
// Write rows to file
$row = 0;
foreach ($sheet->rangeToArrayYieldRows("A1:$maxCol$maxRow", '', $this->preCalculateFormulas) as $cellsArray) {
++$row;
if ($this->variableColumns) {
$column = $sheet->getHighestDataColumn($row);
if ($column === 'A' && !$sheet->cellExists("A$row")) {
$cellsArray = [];
} else {
array_splice($cellsArray, Coordinate::columnIndexFromString($column));
}
}
if ($this->preferHyperlinkToLabel) {
foreach ($cellsArray as $key => $value) {
$url = $sheet->getCell([$key + 1, $row])->getHyperlink()->getUrl();
if ($url !== '') {
$cellsArray[$key] = $url;
}
}
}
/** @var string[] $cellsArray */
$this->writeLine($this->fileHandle, $cellsArray);
}
$this->maybeCloseFileHandle();
Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
}
public function getDelimiter(): string
{
return $this->delimiter;
}
public function setDelimiter(string $delimiter): self
{
$this->delimiter = $delimiter;
return $this;
}
public function getEnclosure(): string
{
return $this->enclosure;
}
public function setEnclosure(string $enclosure = '"'): self
{
$this->enclosure = $enclosure;
return $this;
}
public function getLineEnding(): string
{
return $this->lineEnding;
}
public function setLineEnding(string $lineEnding): self
{
$this->lineEnding = $lineEnding;
return $this;
}
/**
* Get whether BOM should be used.
*/
public function getUseBOM(): bool
{
return $this->useBOM;
}
/**
* Set whether BOM should be used, typically when non-ASCII characters are used.
*/
public function setUseBOM(bool $useBOM): self
{
$this->useBOM = $useBOM;
return $this;
}
/**
* Get whether a separator line should be included.
*/
public function getIncludeSeparatorLine(): bool
{
return $this->includeSeparatorLine;
}
/**
* Set whether a separator line should be included as the first line of the file.
*/
public function setIncludeSeparatorLine(bool $includeSeparatorLine): self
{
$this->includeSeparatorLine = $includeSeparatorLine;
return $this;
}
/**
* Get whether the file should be saved with full Excel Compatibility.
*/
public function getExcelCompatibility(): bool
{
return $this->excelCompatibility;
}
/**
* Set whether the file should be saved with full Excel Compatibility.
*
* @param bool $excelCompatibility Set the file to be written as a fully Excel compatible csv file
* Note that this overrides other settings such as useBOM, enclosure and delimiter
*/
public function setExcelCompatibility(bool $excelCompatibility): self
{
$this->excelCompatibility = $excelCompatibility;
return $this;
}
public function getSheetIndex(): int
{
return $this->sheetIndex;
}
public function setSheetIndex(int $sheetIndex): self
{
$this->sheetIndex = $sheetIndex;
return $this;
}
public function getOutputEncoding(): string
{
return $this->outputEncoding;
}
public function setOutputEncoding(string $outputEncoding): self
{
$this->outputEncoding = $outputEncoding;
return $this;
}
private bool $enclosureRequired = true;
public function setEnclosureRequired(bool $value): self
{
$this->enclosureRequired = $value;
return $this;
}
public function getEnclosureRequired(): bool
{
return $this->enclosureRequired;
}
/**
* Write line to CSV file.
*
* @param resource $fileHandle PHP filehandle
* @param string[] $values Array containing values in a row
*/
private function writeLine($fileHandle, array $values): void
{
// No leading delimiter
$delimiter = '';
// Build the line
$line = '';
foreach ($values as $element) {
if (Preg::isMatch('/^([+-])?(\d+)[.](\d+)/', $element, $matches)) {
// Excel will "convert" file with pop-up
// if there are more than 15 digits precision.
$whole = $matches[2];
if ($whole !== '0') {
$wholeLen = strlen($whole);
$frac = $matches[3];
$maxFracLen = 15 - $wholeLen;
if ($maxFracLen >= 0 && strlen($frac) > $maxFracLen) {
$result = sprintf("%.{$maxFracLen}F", $element);
if (str_contains($result, '.')) {
$element = Preg::replace('/[.]?0+$/', '', $result); // strip trailing zeros
}
}
}
}
// Add delimiter
$line .= $delimiter;
$delimiter = $this->delimiter;
// Escape enclosures
$enclosure = $this->enclosure;
if ($enclosure) {
// If enclosure is not required, use enclosure only if
// element contains newline, delimiter, or enclosure.
if (!$this->enclosureRequired && strpbrk($element, "$delimiter$enclosure\n") === false) {
$enclosure = '';
} else {
$element = str_replace($enclosure, $enclosure . $enclosure, $element);
}
}
// Add enclosed string
$line .= $enclosure . $element . $enclosure;
}
// Add line ending
$line .= $this->lineEnding;
// Write to file
if ($this->outputEncoding != '') {
$line = (string) mb_convert_encoding($line, $this->outputEncoding);
}
fwrite($fileHandle, $line);
}
/**
* Get whether number of columns should be allowed to vary
* between rows, or use a fixed range based on the max
* column overall.
*/
public function getVariableColumns(): bool
{
return $this->variableColumns;
}
/**
* Set whether number of columns should be allowed to vary
* between rows, or use a fixed range based on the max
* column overall.
*/
public function setVariableColumns(bool $pValue): self
{
$this->variableColumns = $pValue;
return $this;
}
/**
* Get whether hyperlink or label should be output.
*/
public function getPreferHyperlinkToLabel(): bool
{
return $this->preferHyperlinkToLabel;
}
/**
* Set whether hyperlink or label should be output.
*/
public function setPreferHyperlinkToLabel(bool $preferHyperlinkToLabel): self
{
$this->preferHyperlinkToLabel = $preferHyperlinkToLabel;
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Pdf.php | src/PhpSpreadsheet/Writer/Pdf.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
abstract class Pdf extends Html
{
/**
* Temporary storage directory.
*/
protected string $tempDir;
/**
* Font.
*/
protected string $font = 'freesans';
/**
* Orientation (Over-ride).
*/
protected ?string $orientation = null;
/**
* Paper size (Over-ride).
*/
protected ?int $paperSize = null;
/**
* Paper Sizes xRef List.
*
* @var array<int, float[]|string>
*/
protected static array $paperSizes = [
PageSetup::PAPERSIZE_LETTER => 'LETTER', // (8.5 in. by 11 in.)
PageSetup::PAPERSIZE_LETTER_SMALL => 'LETTER', // (8.5 in. by 11 in.)
PageSetup::PAPERSIZE_TABLOID => [792.00, 1224.00], // (11 in. by 17 in.)
PageSetup::PAPERSIZE_LEDGER => [1224.00, 792.00], // (17 in. by 11 in.)
PageSetup::PAPERSIZE_LEGAL => 'LEGAL', // (8.5 in. by 14 in.)
PageSetup::PAPERSIZE_STATEMENT => [396.00, 612.00], // (5.5 in. by 8.5 in.)
PageSetup::PAPERSIZE_EXECUTIVE => 'EXECUTIVE', // (7.25 in. by 10.5 in.)
PageSetup::PAPERSIZE_A3 => 'A3', // (297 mm by 420 mm)
PageSetup::PAPERSIZE_A4 => 'A4', // (210 mm by 297 mm)
PageSetup::PAPERSIZE_A4_SMALL => 'A4', // (210 mm by 297 mm)
PageSetup::PAPERSIZE_A5 => 'A5', // (148 mm by 210 mm)
PageSetup::PAPERSIZE_B4 => 'B4', // (250 mm by 353 mm)
PageSetup::PAPERSIZE_B5 => 'B5', // (176 mm by 250 mm)
PageSetup::PAPERSIZE_FOLIO => 'FOLIO', // (8.5 in. by 13 in.)
PageSetup::PAPERSIZE_QUARTO => [609.45, 779.53], // (215 mm by 275 mm)
PageSetup::PAPERSIZE_STANDARD_1 => [720.00, 1008.00], // (10 in. by 14 in.)
PageSetup::PAPERSIZE_STANDARD_2 => [792.00, 1224.00], // (11 in. by 17 in.)
PageSetup::PAPERSIZE_NOTE => 'LETTER', // (8.5 in. by 11 in.)
PageSetup::PAPERSIZE_NO9_ENVELOPE => [279.00, 639.00], // (3.875 in. by 8.875 in.)
PageSetup::PAPERSIZE_NO10_ENVELOPE => [297.00, 684.00], // (4.125 in. by 9.5 in.)
PageSetup::PAPERSIZE_NO11_ENVELOPE => [324.00, 747.00], // (4.5 in. by 10.375 in.)
PageSetup::PAPERSIZE_NO12_ENVELOPE => [342.00, 792.00], // (4.75 in. by 11 in.)
PageSetup::PAPERSIZE_NO14_ENVELOPE => [360.00, 828.00], // (5 in. by 11.5 in.)
PageSetup::PAPERSIZE_C => [1224.00, 1584.00], // (17 in. by 22 in.)
PageSetup::PAPERSIZE_D => [1584.00, 2448.00], // (22 in. by 34 in.)
PageSetup::PAPERSIZE_E => [2448.00, 3168.00], // (34 in. by 44 in.)
PageSetup::PAPERSIZE_DL_ENVELOPE => [311.81, 623.62], // (110 mm by 220 mm)
PageSetup::PAPERSIZE_C5_ENVELOPE => 'C5', // (162 mm by 229 mm)
PageSetup::PAPERSIZE_C3_ENVELOPE => 'C3', // (324 mm by 458 mm)
PageSetup::PAPERSIZE_C4_ENVELOPE => 'C4', // (229 mm by 324 mm)
PageSetup::PAPERSIZE_C6_ENVELOPE => 'C6', // (114 mm by 162 mm)
PageSetup::PAPERSIZE_C65_ENVELOPE => [323.15, 649.13], // (114 mm by 229 mm)
PageSetup::PAPERSIZE_B4_ENVELOPE => 'B4', // (250 mm by 353 mm)
PageSetup::PAPERSIZE_B5_ENVELOPE => 'B5', // (176 mm by 250 mm)
PageSetup::PAPERSIZE_B6_ENVELOPE => [498.90, 354.33], // (176 mm by 125 mm)
PageSetup::PAPERSIZE_ITALY_ENVELOPE => [311.81, 651.97], // (110 mm by 230 mm)
PageSetup::PAPERSIZE_MONARCH_ENVELOPE => [279.00, 540.00], // (3.875 in. by 7.5 in.)
PageSetup::PAPERSIZE_6_3_4_ENVELOPE => [261.00, 468.00], // (3.625 in. by 6.5 in.)
PageSetup::PAPERSIZE_US_STANDARD_FANFOLD => [1071.00, 792.00], // (14.875 in. by 11 in.)
PageSetup::PAPERSIZE_GERMAN_STANDARD_FANFOLD => [612.00, 864.00], // (8.5 in. by 12 in.)
PageSetup::PAPERSIZE_GERMAN_LEGAL_FANFOLD => 'FOLIO', // (8.5 in. by 13 in.)
PageSetup::PAPERSIZE_ISO_B4 => 'B4', // (250 mm by 353 mm)
PageSetup::PAPERSIZE_JAPANESE_DOUBLE_POSTCARD => [566.93, 419.53], // (200 mm by 148 mm)
PageSetup::PAPERSIZE_STANDARD_PAPER_1 => [648.00, 792.00], // (9 in. by 11 in.)
PageSetup::PAPERSIZE_STANDARD_PAPER_2 => [720.00, 792.00], // (10 in. by 11 in.)
PageSetup::PAPERSIZE_STANDARD_PAPER_3 => [1080.00, 792.00], // (15 in. by 11 in.)
PageSetup::PAPERSIZE_INVITE_ENVELOPE => [623.62, 623.62], // (220 mm by 220 mm)
PageSetup::PAPERSIZE_LETTER_EXTRA_PAPER => [667.80, 864.00], // (9.275 in. by 12 in.)
PageSetup::PAPERSIZE_LEGAL_EXTRA_PAPER => [667.80, 1080.00], // (9.275 in. by 15 in.)
PageSetup::PAPERSIZE_TABLOID_EXTRA_PAPER => [841.68, 1296.00], // (11.69 in. by 18 in.)
PageSetup::PAPERSIZE_A4_EXTRA_PAPER => [668.98, 912.76], // (236 mm by 322 mm)
PageSetup::PAPERSIZE_LETTER_TRANSVERSE_PAPER => [595.80, 792.00], // (8.275 in. by 11 in.)
PageSetup::PAPERSIZE_A4_TRANSVERSE_PAPER => 'A4', // (210 mm by 297 mm)
PageSetup::PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER => [667.80, 864.00], // (9.275 in. by 12 in.)
PageSetup::PAPERSIZE_SUPERA_SUPERA_A4_PAPER => [643.46, 1009.13], // (227 mm by 356 mm)
PageSetup::PAPERSIZE_SUPERB_SUPERB_A3_PAPER => [864.57, 1380.47], // (305 mm by 487 mm)
PageSetup::PAPERSIZE_LETTER_PLUS_PAPER => [612.00, 913.68], // (8.5 in. by 12.69 in.)
PageSetup::PAPERSIZE_A4_PLUS_PAPER => [595.28, 935.43], // (210 mm by 330 mm)
PageSetup::PAPERSIZE_A5_TRANSVERSE_PAPER => 'A5', // (148 mm by 210 mm)
PageSetup::PAPERSIZE_JIS_B5_TRANSVERSE_PAPER => [515.91, 728.50], // (182 mm by 257 mm)
PageSetup::PAPERSIZE_A3_EXTRA_PAPER => [912.76, 1261.42], // (322 mm by 445 mm)
PageSetup::PAPERSIZE_A5_EXTRA_PAPER => [493.23, 666.14], // (174 mm by 235 mm)
PageSetup::PAPERSIZE_ISO_B5_EXTRA_PAPER => [569.76, 782.36], // (201 mm by 276 mm)
PageSetup::PAPERSIZE_A2_PAPER => 'A2', // (420 mm by 594 mm)
PageSetup::PAPERSIZE_A3_TRANSVERSE_PAPER => 'A3', // (297 mm by 420 mm)
PageSetup::PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER => [912.76, 1261.42], // (322 mm by 445 mm)
];
/**
* Create a new PDF Writer instance.
*
* @param Spreadsheet $spreadsheet Spreadsheet object
*/
public function __construct(Spreadsheet $spreadsheet)
{
parent::__construct($spreadsheet);
//$this->setUseInlineCss(true);
$this->tempDir = File::sysGetTempDir() . '/phpsppdf';
$this->isPdf = true;
}
/**
* Get Font.
*/
public function getFont(): string
{
return $this->font;
}
/**
* Set font. Examples:
* 'arialunicid0-chinese-simplified'
* 'arialunicid0-chinese-traditional'
* 'arialunicid0-korean'
* 'arialunicid0-japanese'.
*
* @return $this
*/
public function setFont(string $fontName)
{
$this->font = $fontName;
return $this;
}
/**
* Get Paper Size.
*/
public function getPaperSize(): ?int
{
return $this->paperSize;
}
/**
* Set Paper Size.
*
* @param int $paperSize Paper size see PageSetup::PAPERSIZE_*
*/
public function setPaperSize(int $paperSize): self
{
$this->paperSize = $paperSize;
return $this;
}
/**
* Get Orientation.
*/
public function getOrientation(): ?string
{
return $this->orientation;
}
/**
* Set Orientation.
*
* @param string $orientation Page orientation see PageSetup::ORIENTATION_*
*/
public function setOrientation(string $orientation): self
{
$this->orientation = $orientation;
return $this;
}
/**
* Get temporary storage directory.
*/
public function getTempDir(): string
{
return $this->tempDir;
}
/**
* Set temporary storage directory.
*
* @param string $temporaryDirectory Temporary storage directory
*/
public function setTempDir(string $temporaryDirectory): self
{
if (is_dir($temporaryDirectory)) {
$this->tempDir = $temporaryDirectory;
} else {
throw new WriterException("Directory does not exist: $temporaryDirectory");
}
return $this;
}
/**
* Save Spreadsheet to PDF file, pre-save.
*
* @param resource|string $filename Name of the file to save as
*
* @return resource
*/
protected function prepareForSave($filename)
{
// Open file
$this->openFileHandle($filename);
return $this->fileHandle;
}
/**
* Save PhpSpreadsheet to PDF file, post-save.
*/
protected function restoreStateAfterSave(): void
{
$this->maybeCloseFileHandle();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/ZipStream3.php | src/PhpSpreadsheet/Writer/ZipStream3.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use ZipStream\ZipStream;
class ZipStream3
{
/**
* @param resource $fileHandle
*/
public static function newZipStream($fileHandle): ZipStream
{
return new ZipStream(
enableZip64: false,
outputStream: $fileHandle,
sendHttpHeaders: false,
defaultEnableZeroHeader: false,
);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/ZipStream2.php | src/PhpSpreadsheet/Writer/ZipStream2.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use ZipStream\Option\Archive;
use ZipStream\ZipStream;
/**
* Either ZipStream2 or ZipStream3, but not both, may be used.
* For code coverage testing, it will always be ZipStream3.
*
* @codeCoverageIgnore
*/
class ZipStream2
{
/**
* @param resource $fileHandle
*/
public static function newZipStream($fileHandle): ZipStream
{
$options = new Archive();
$options->setEnableZip64(false);
$options->setOutputStream($fileHandle);
return new ZipStream(null, $options);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls.php | src/PhpSpreadsheet/Writer/Xls.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\RichText\Run;
use PhpOffice\PhpSpreadsheet\Shared\Escher;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE\Blip;
use PhpOffice\PhpSpreadsheet\Shared\OLE;
use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\File;
use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\Root;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
use PhpOffice\PhpSpreadsheet\Writer\Xls\Parser;
use PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook;
use PhpOffice\PhpSpreadsheet\Writer\Xls\Worksheet;
class Xls extends BaseWriter
{
/**
* PhpSpreadsheet object.
*/
private Spreadsheet $spreadsheet;
/**
* Total number of shared strings in workbook.
*/
private int $strTotal = 0;
/**
* Number of unique shared strings in workbook.
*/
private int $strUnique = 0;
/**
* Array of unique shared strings in workbook.
*
* @var array<string, int>
*/
private array $strTable = [];
/**
* Color cache. Mapping between RGB value and color index.
*
* @var mixed[]
*/
private array $colors;
/**
* Formula parser.
*/
private Parser $parser;
/**
* Identifier clusters for drawings. Used in MSODRAWINGGROUP record.
*
* @var mixed[]
*/
private array $IDCLs;
/**
* Basic OLE object summary information.
*/
private string $summaryInformation;
/**
* Extended OLE object document summary information.
*/
private string $documentSummaryInformation;
private Workbook $writerWorkbook;
/**
* @var Worksheet[]
*/
private array $writerWorksheets;
/**
* Create a new Xls Writer.
*
* @param Spreadsheet $spreadsheet PhpSpreadsheet object
*/
public function __construct(Spreadsheet $spreadsheet)
{
$this->spreadsheet = $spreadsheet;
$this->parser = new Parser($spreadsheet);
}
/**
* Save Spreadsheet to file.
*
* @param resource|string $filename
*/
public function save($filename, int $flags = 0): void
{
$this->processFlags($flags);
// garbage collect
$this->spreadsheet->garbageCollect();
$saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog();
Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false);
$saveDateReturnType = Functions::getReturnDateType();
Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
// initialize colors array
$this->colors = [];
// Initialise workbook writer
$this->writerWorkbook = new Workbook($this->spreadsheet, $this->strTotal, $this->strUnique, $this->strTable, $this->colors, $this->parser);
// Initialise worksheet writers
$countSheets = $this->spreadsheet->getSheetCount();
for ($i = 0; $i < $countSheets; ++$i) {
$this->writerWorksheets[$i] = new Worksheet($this->strTotal, $this->strUnique, $this->strTable, $this->colors, $this->parser, $this->preCalculateFormulas, $this->spreadsheet->getSheet($i), $this->writerWorkbook);
}
// build Escher objects. Escher objects for worksheets need to be built before Escher object for workbook.
$this->buildWorksheetEschers();
$this->buildWorkbookEscher();
// add 15 identical cell style Xfs
// for now, we use the first cellXf instead of cellStyleXf
$cellXfCollection = $this->spreadsheet->getCellXfCollection();
for ($i = 0; $i < 15; ++$i) {
$this->writerWorkbook->addXfWriter($cellXfCollection[0], true);
}
// add all the cell Xfs
foreach ($this->spreadsheet->getCellXfCollection() as $style) {
$this->writerWorkbook->addXfWriter($style, false);
}
// add fonts from rich text elements
for ($i = 0; $i < $countSheets; ++$i) {
foreach ($this->writerWorksheets[$i]->phpSheet->getCellCollection()->getCoordinates() as $coordinate) {
/** @var Cell $cell */
$cell = $this->writerWorksheets[$i]->phpSheet->getCellCollection()->get($coordinate);
$cVal = $cell->getValue();
if ($cVal instanceof RichText && (string) $cVal === '') {
$cVal = '';
}
if ($cVal instanceof RichText) {
$active = $this->spreadsheet->getActiveSheetIndex();
$sheet = $cell->getWorksheet();
$selected = $sheet->getSelectedCells();
$font = $cell->getStyle()->getFont();
$this->writerWorksheets[$i]
->fontHashIndex[$font->getHashCode()] = $this->writerWorkbook->addFont($font);
$sheet->setSelectedCells($selected);
if ($active > -1) {
$this->spreadsheet
->setActiveSheetIndex($active);
}
$elements = $cVal->getRichTextElements();
foreach ($elements as $element) {
if ($element instanceof Run) {
$font = $element->getFont();
if ($font !== null) {
$this->writerWorksheets[$i]
->fontHashIndex[
$font->getHashCode()
] = $this->writerWorkbook->addFont($font);
}
}
}
}
}
}
// initialize OLE file
$workbookStreamName = 'Workbook';
$OLE = new File(OLE::ascToUcs($workbookStreamName));
// Write the worksheet streams before the global workbook stream,
// because the byte sizes of these are needed in the global workbook stream
$worksheetSizes = [];
for ($i = 0; $i < $countSheets; ++$i) {
$this->writerWorksheets[$i]->close();
$worksheetSizes[] = $this->writerWorksheets[$i]->_datasize;
}
// add binary data for global workbook stream
$OLE->append($this->writerWorkbook->writeWorkbook($worksheetSizes));
// add binary data for sheet streams
for ($i = 0; $i < $countSheets; ++$i) {
$OLE->append($this->writerWorksheets[$i]->getData());
}
$this->documentSummaryInformation = $this->writeDocumentSummaryInformation();
// initialize OLE Document Summary Information
if (!empty($this->documentSummaryInformation)) {
$OLE_DocumentSummaryInformation = new File(OLE::ascToUcs(chr(5) . 'DocumentSummaryInformation'));
$OLE_DocumentSummaryInformation->append($this->documentSummaryInformation);
}
$this->summaryInformation = $this->writeSummaryInformation();
// initialize OLE Summary Information
if (!empty($this->summaryInformation)) {
$OLE_SummaryInformation = new File(OLE::ascToUcs(chr(5) . 'SummaryInformation'));
$OLE_SummaryInformation->append($this->summaryInformation);
}
// define OLE Parts
$arrRootData = [$OLE];
// initialize OLE Properties file
if (isset($OLE_SummaryInformation)) {
$arrRootData[] = $OLE_SummaryInformation;
}
// initialize OLE Extended Properties file
if (isset($OLE_DocumentSummaryInformation)) {
$arrRootData[] = $OLE_DocumentSummaryInformation;
}
$time = $this->spreadsheet->getProperties()->getModified();
$root = new Root($time, $time, $arrRootData);
// save the OLE file
$this->openFileHandle($filename);
$root->save($this->fileHandle);
$this->maybeCloseFileHandle();
Functions::setReturnDateType($saveDateReturnType);
Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
}
/**
* Build the Worksheet Escher objects.
*/
private function buildWorksheetEschers(): void
{
// 1-based index to BstoreContainer
$blipIndex = 0;
$lastReducedSpId = 0;
$lastSpId = 0;
foreach ($this->spreadsheet->getAllsheets() as $sheet) {
// sheet index
$sheetIndex = $sheet->getParentOrThrow()->getIndex($sheet);
// check if there are any shapes for this sheet
$filterRange = $sheet->getAutoFilter()->getRange();
if (count($sheet->getDrawingCollection()) == 0 && empty($filterRange)) {
continue;
}
// create intermediate Escher object
$escher = new Escher();
// dgContainer
$dgContainer = new DgContainer();
// set the drawing index (we use sheet index + 1)
$dgId = $sheet->getParentOrThrow()->getIndex($sheet) + 1;
$dgContainer->setDgId($dgId);
$escher->setDgContainer($dgContainer);
// spgrContainer
$spgrContainer = new SpgrContainer();
$dgContainer->setSpgrContainer($spgrContainer);
// add one shape which is the group shape
$spContainer = new SpContainer();
$spContainer->setSpgr(true);
$spContainer->setSpType(0);
$spContainer->setSpId(($sheet->getParentOrThrow()->getIndex($sheet) + 1) << 10);
$spgrContainer->addChild($spContainer);
// add the shapes
$countShapes[$sheetIndex] = 0; // count number of shapes (minus group shape), in sheet
foreach ($sheet->getDrawingCollection() as $drawing) {
++$blipIndex;
++$countShapes[$sheetIndex];
// add the shape
$spContainer = new SpContainer();
// set the shape type
$spContainer->setSpType(0x004B);
// set the shape flag
$spContainer->setSpFlag(0x02);
// set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index)
$reducedSpId = $countShapes[$sheetIndex];
$spId = $reducedSpId | ($sheet->getParentOrThrow()->getIndex($sheet) + 1) << 10;
$spContainer->setSpId($spId);
// keep track of last reducedSpId
$lastReducedSpId = $reducedSpId;
// keep track of last spId
$lastSpId = $spId;
// set the BLIP index
$spContainer->setOPT(0x4104, $blipIndex);
// set coordinates and offsets, client anchor
$coordinates = $drawing->getCoordinates();
$offsetX = $drawing->getOffsetX();
$offsetY = $drawing->getOffsetY();
$width = $drawing->getWidth();
$height = $drawing->getHeight();
$twoAnchor = \PhpOffice\PhpSpreadsheet\Shared\Xls::oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height);
if (is_array($twoAnchor)) {
/** @var array{startCoordinates: string, startOffsetX: float|int, startOffsetY: float|int, endCoordinates: string, endOffsetX: float|int, endOffsetY: float|int} $twoAnchor */
$spContainer->setStartCoordinates($twoAnchor['startCoordinates']);
$spContainer->setStartOffsetX($twoAnchor['startOffsetX']);
$spContainer->setStartOffsetY($twoAnchor['startOffsetY']);
$spContainer->setEndCoordinates($twoAnchor['endCoordinates']);
$spContainer->setEndOffsetX($twoAnchor['endOffsetX']);
$spContainer->setEndOffsetY($twoAnchor['endOffsetY']);
$spgrContainer->addChild($spContainer);
}
}
// AutoFilters
if (!empty($filterRange)) {
$rangeBounds = Coordinate::rangeBoundaries($filterRange);
$iNumColStart = $rangeBounds[0][0];
$iNumColEnd = $rangeBounds[1][0];
$iInc = $iNumColStart;
while ($iInc <= $iNumColEnd) {
++$countShapes[$sheetIndex];
// create a Drawing Object for the dropdown
$oDrawing = new BaseDrawing();
// get the coordinates of drawing
$cDrawing = Coordinate::stringFromColumnIndex($iInc) . $rangeBounds[0][1];
$oDrawing->setCoordinates($cDrawing);
$oDrawing->setWorksheet($sheet);
// add the shape
$spContainer = new SpContainer();
// set the shape type
$spContainer->setSpType(0x00C9);
// set the shape flag
$spContainer->setSpFlag(0x01);
// set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index)
$reducedSpId = $countShapes[$sheetIndex];
$spId = $reducedSpId | ($sheet->getParentOrThrow()->getIndex($sheet) + 1) << 10;
$spContainer->setSpId($spId);
// keep track of last reducedSpId
$lastReducedSpId = $reducedSpId;
// keep track of last spId
$lastSpId = $spId;
$spContainer->setOPT(0x007F, 0x01040104); // Protection -> fLockAgainstGrouping
$spContainer->setOPT(0x00BF, 0x00080008); // Text -> fFitTextToShape
$spContainer->setOPT(0x01BF, 0x00010000); // Fill Style -> fNoFillHitTest
$spContainer->setOPT(0x01FF, 0x00080000); // Line Style -> fNoLineDrawDash
$spContainer->setOPT(0x03BF, 0x000A0000); // Group Shape -> fPrint
// set coordinates and offsets, client anchor
$endCoordinates = Coordinate::stringFromColumnIndex($iInc);
$endCoordinates .= $rangeBounds[0][1] + 1;
$spContainer->setStartCoordinates($cDrawing);
$spContainer->setStartOffsetX(0);
$spContainer->setStartOffsetY(0);
$spContainer->setEndCoordinates($endCoordinates);
$spContainer->setEndOffsetX(0);
$spContainer->setEndOffsetY(0);
$spgrContainer->addChild($spContainer);
++$iInc;
}
}
// identifier clusters, used for workbook Escher object
$this->IDCLs[$dgId] = $lastReducedSpId;
// set last shape index
$dgContainer->setLastSpId($lastSpId);
// set the Escher object
$this->writerWorksheets[$sheetIndex]->setEscher($escher);
}
}
private function processMemoryDrawing(BstoreContainer &$bstoreContainer, MemoryDrawing $drawing, string $renderingFunctionx): void
{
switch ($renderingFunctionx) {
case MemoryDrawing::RENDERING_JPEG:
$blipType = BSE::BLIPTYPE_JPEG;
$renderingFunction = 'imagejpeg';
break;
default:
$blipType = BSE::BLIPTYPE_PNG;
$renderingFunction = 'imagepng';
break;
}
ob_start();
call_user_func($renderingFunction, $drawing->getImageResource()); // @phpstan-ignore-line
$blipData = ob_get_contents();
ob_end_clean();
$blip = new Blip();
$blip->setData("$blipData");
$BSE = new BSE();
$BSE->setBlipType($blipType);
$BSE->setBlip($blip);
$bstoreContainer->addBSE($BSE);
}
private static int $two = 2; // phpstan silliness
private function processDrawing(BstoreContainer &$bstoreContainer, Drawing $drawing): void
{
$blipType = 0;
$blipData = '';
$filename = $drawing->getPath();
$imageSize = getimagesize($filename);
$imageFormat = empty($imageSize) ? 0 : ($imageSize[self::$two] ?? 0);
switch ($imageFormat) {
case 1: // GIF, not supported by BIFF8, we convert to PNG
$blipType = BSE::BLIPTYPE_PNG;
$newImage = @imagecreatefromgif($filename);
if ($newImage === false) {
throw new Exception("Unable to create image from $filename");
}
ob_start();
imagepng($newImage);
$blipData = ob_get_contents();
ob_end_clean();
break;
case 2: // JPEG
$blipType = BSE::BLIPTYPE_JPEG;
$blipData = file_get_contents($filename);
break;
case 3: // PNG
$blipType = BSE::BLIPTYPE_PNG;
$blipData = file_get_contents($filename);
break;
case 6: // Windows DIB (BMP), we convert to PNG
$blipType = BSE::BLIPTYPE_PNG;
$newImage = @imagecreatefrombmp($filename);
if ($newImage === false) {
throw new Exception("Unable to create image from $filename");
}
ob_start();
imagepng($newImage);
$blipData = ob_get_contents();
ob_end_clean();
break;
}
if ($blipData) {
$blip = new Blip();
$blip->setData($blipData);
$BSE = new BSE();
$BSE->setBlipType($blipType);
$BSE->setBlip($blip);
$bstoreContainer->addBSE($BSE);
}
}
private function processBaseDrawing(BstoreContainer &$bstoreContainer, BaseDrawing $drawing): void
{
if ($drawing instanceof Drawing && $drawing->getPath() !== '') {
$this->processDrawing($bstoreContainer, $drawing);
} elseif ($drawing instanceof MemoryDrawing) {
$this->processMemoryDrawing($bstoreContainer, $drawing, $drawing->getRenderingFunction());
}
}
private function checkForDrawings(): bool
{
// any drawings in this workbook?
$found = false;
foreach ($this->spreadsheet->getAllSheets() as $sheet) {
if (count($sheet->getDrawingCollection()) > 0) {
$found = true;
break;
}
}
return $found;
}
/**
* Build the Escher object corresponding to the MSODRAWINGGROUP record.
*/
private function buildWorkbookEscher(): void
{
// nothing to do if there are no drawings
if (!$this->checkForDrawings()) {
return;
}
// if we reach here, then there are drawings in the workbook
$escher = new Escher();
// dggContainer
$dggContainer = new DggContainer();
$escher->setDggContainer($dggContainer);
// set IDCLs (identifier clusters)
$dggContainer->setIDCLs($this->IDCLs);
// this loop is for determining maximum shape identifier of all drawing
$spIdMax = 0;
$totalCountShapes = 0;
$countDrawings = 0;
foreach ($this->spreadsheet->getAllsheets() as $sheet) {
$sheetCountShapes = 0; // count number of shapes (minus group shape), in sheet
$addCount = 0;
foreach ($sheet->getDrawingCollection() as $drawing) {
$addCount = 1;
++$sheetCountShapes;
++$totalCountShapes;
$spId = $sheetCountShapes | ($this->spreadsheet->getIndex($sheet) + 1) << 10;
$spIdMax = max($spId, $spIdMax);
}
$countDrawings += $addCount;
}
$dggContainer->setSpIdMax($spIdMax + 1);
$dggContainer->setCDgSaved($countDrawings);
$dggContainer->setCSpSaved($totalCountShapes + $countDrawings); // total number of shapes incl. one group shapes per drawing
// bstoreContainer
$bstoreContainer = new BstoreContainer();
$dggContainer->setBstoreContainer($bstoreContainer);
// the BSE's (all the images)
foreach ($this->spreadsheet->getAllsheets() as $sheet) {
foreach ($sheet->getDrawingCollection() as $drawing) {
$this->processBaseDrawing($bstoreContainer, $drawing);
}
}
// Set the Escher object
$this->writerWorkbook->setEscher($escher);
}
/**
* Build the OLE Part for DocumentSummary Information.
*/
private function writeDocumentSummaryInformation(): string
{
// offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
$data = pack('v', 0xFFFE);
// offset: 2; size: 2;
$data .= pack('v', 0x0000);
// offset: 4; size: 2; OS version
$data .= pack('v', 0x0106);
// offset: 6; size: 2; OS indicator
$data .= pack('v', 0x0002);
// offset: 8; size: 16
$data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00);
// offset: 24; size: 4; section count
$data .= pack('V', 0x0001);
// offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae
$data .= pack('vvvvvvvv', 0xD502, 0xD5CD, 0x2E9C, 0x101B, 0x9793, 0x0008, 0x2C2B, 0xAEF9);
// offset: 44; size: 4; offset of the start
$data .= pack('V', 0x30);
// SECTION
$dataSection = [];
$dataSection_NumProps = 0;
$dataSection_Summary = '';
$dataSection_Content = '';
// GKPIDDSI_CODEPAGE: CodePage
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x01],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x02], // 2 byte signed integer
'data' => ['data' => 1252],
];
++$dataSection_NumProps;
// GKPIDDSI_CATEGORY : Category
$dataProp = $this->spreadsheet->getProperties()->getCategory();
if ($dataProp) {
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x02],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x1E],
'data' => ['data' => $dataProp, 'length' => strlen($dataProp)],
];
++$dataSection_NumProps;
}
// GKPIDDSI_VERSION :Version of the application that wrote the property storage
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x17],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x03],
'data' => ['pack' => 'V', 'data' => 0x000C0000],
];
++$dataSection_NumProps;
// GKPIDDSI_SCALE : FALSE
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x0B],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x0B],
'data' => ['data' => false],
];
++$dataSection_NumProps;
// GKPIDDSI_LINKSDIRTY : True if any of the values for the linked properties have changed outside of the application
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x10],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x0B],
'data' => ['data' => false],
];
++$dataSection_NumProps;
// GKPIDDSI_SHAREDOC : FALSE
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x13],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x0B],
'data' => ['data' => false],
];
++$dataSection_NumProps;
// GKPIDDSI_HYPERLINKSCHANGED : True if any of the values for the _PID_LINKS (hyperlink text) have changed outside of the application
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x16],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x0B],
'data' => ['data' => false],
];
++$dataSection_NumProps;
// GKPIDDSI_DOCSPARTS
// MS-OSHARED p75 (2.3.3.2.2.1)
// Structure is VtVecUnalignedLpstrValue (2.3.3.1.9)
// cElements
$dataProp = pack('v', 0x0001);
$dataProp .= pack('v', 0x0000);
// array of UnalignedLpstr
// cch
$dataProp .= pack('v', 0x000A);
$dataProp .= pack('v', 0x0000);
// value
$dataProp .= 'Worksheet' . chr(0);
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x0D],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x101E],
'data' => ['data' => $dataProp, 'length' => strlen($dataProp)],
];
++$dataSection_NumProps;
// GKPIDDSI_HEADINGPAIR
// VtVecHeadingPairValue
// cElements
$dataProp = pack('v', 0x0002);
$dataProp .= pack('v', 0x0000);
// Array of vtHeadingPair
// vtUnalignedString - headingString
// stringType
$dataProp .= pack('v', 0x001E);
// padding
$dataProp .= pack('v', 0x0000);
// UnalignedLpstr
// cch
$dataProp .= pack('v', 0x0013);
$dataProp .= pack('v', 0x0000);
// value
$dataProp .= 'Feuilles de calcul';
// vtUnalignedString - headingParts
// wType : 0x0003 = 32-bit signed integer
$dataProp .= pack('v', 0x0300);
// padding
$dataProp .= pack('v', 0x0000);
// value
$dataProp .= pack('v', 0x0100);
$dataProp .= pack('v', 0x0000);
$dataProp .= pack('v', 0x0000);
$dataProp .= pack('v', 0x0000);
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => 0x0C],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => 0x100C],
'data' => ['data' => $dataProp, 'length' => strlen($dataProp)],
];
++$dataSection_NumProps;
// 4 Section Length
// 4 Property count
// 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4))
$dataSection_Content_Offset = 8 + $dataSection_NumProps * 8;
foreach ($dataSection as $dataProp) {
// Summary
$dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']);
// Offset
$dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset);
// DataType
$dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']);
// Data
if ($dataProp['type']['data'] == 0x02) { // 2 byte signed integer
$dataSection_Content .= pack('V', $dataProp['data']['data']);
$dataSection_Content_Offset += 4 + 4;
} elseif ($dataProp['type']['data'] == 0x03) { // 4 byte signed integer
$dataSection_Content .= pack('V', $dataProp['data']['data']);
$dataSection_Content_Offset += 4 + 4;
} elseif ($dataProp['type']['data'] == 0x0B) { // Boolean
$dataSection_Content .= pack('V', (int) $dataProp['data']['data']);
$dataSection_Content_Offset += 4 + 4;
} elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length
// Null-terminated string
$dataProp['data']['data'] .= chr(0);
++$dataProp['data']['length'];
// Complete the string with null string for being a %4
$dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4) == 4 ? 0 : (4 - $dataProp['data']['length'] % 4));
$dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT);
$dataSection_Content .= pack('V', $dataProp['data']['length']);
$dataSection_Content .= $dataProp['data']['data'];
$dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']);
} else {
$dataSection_Content .= $dataProp['data']['data'];
$dataSection_Content_Offset += 4 + $dataProp['data']['length'];
}
}
// Now $dataSection_Content_Offset contains the size of the content
// section header
// offset: $secOffset; size: 4; section length
// + x Size of the content (summary + content)
$data .= pack('V', $dataSection_Content_Offset);
// offset: $secOffset+4; size: 4; property count
$data .= pack('V', $dataSection_NumProps);
// Section Summary
$data .= $dataSection_Summary;
// Section Content
$data .= $dataSection_Content;
return $data;
}
/** @param array<int, array{summary: array{pack: string, data: mixed}, offset: array{pack: string}, type: array{pack: string, data: int}, data: array{data: mixed}}> $dataSection */
private function writeSummaryPropOle(float|int $dataProp, int &$dataSection_NumProps, array &$dataSection, int $sumdata, int $typdata): void
{
if ($dataProp) {
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => $sumdata],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => $typdata], // null-terminated string prepended by dword string length
'data' => ['data' => OLE::localDateToOLE($dataProp)],
];
++$dataSection_NumProps;
}
}
/** @param array<int, array{summary: array{pack: string, data: mixed}, offset: array{pack: string}, type: array{pack: string, data: int}, data: array{data: mixed}}> $dataSection */
private function writeSummaryProp(string $dataProp, int &$dataSection_NumProps, array &$dataSection, int $sumdata, int $typdata): void
{
if ($dataProp) {
$dataSection[] = [
'summary' => ['pack' => 'V', 'data' => $sumdata],
'offset' => ['pack' => 'V'],
'type' => ['pack' => 'V', 'data' => $typdata], // null-terminated string prepended by dword string length
'data' => ['data' => $dataProp, 'length' => strlen($dataProp)],
];
++$dataSection_NumProps;
}
}
/**
* Build the OLE Part for Summary Information.
*/
private function writeSummaryInformation(): string
{
// offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
$data = pack('v', 0xFFFE);
// offset: 2; size: 2;
$data .= pack('v', 0x0000);
// offset: 4; size: 2; OS version
$data .= pack('v', 0x0106);
// offset: 6; size: 2; OS indicator
$data .= pack('v', 0x0002);
// offset: 8; size: 16
$data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00);
// offset: 24; size: 4; section count
$data .= pack('V', 0x0001);
// offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9
$data .= pack('vvvvvvvv', 0x85E0, 0xF29F, 0x4FF9, 0x1068, 0x91AB, 0x0008, 0x272B, 0xD9B3);
// offset: 44; size: 4; offset of the start
$data .= pack('V', 0x30);
// SECTION
$dataSection = [];
$dataSection_NumProps = 0;
$dataSection_Summary = '';
$dataSection_Content = '';
// CodePage : CP-1252
$dataSection[] = [
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | true |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Html.php | src/PhpSpreadsheet/Writer/Html.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer;
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\Chart\Chart;
use PhpOffice\PhpSpreadsheet\Comment;
use PhpOffice\PhpSpreadsheet\Document\Properties;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\RichText\Run;
use PhpOffice\PhpSpreadsheet\Settings;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Shared\Font as SharedFont;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
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\ConditionalFormatting\MergedCellStyle;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Font;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class Html extends BaseWriter
{
private const DEFAULT_CELL_WIDTH_POINTS = 42;
private const DEFAULT_CELL_WIDTH_PIXELS = 56;
/**
* Migration aid to tell if html tags will be treated as plaintext in comments.
* if (
* defined(
* \PhpOffice\PhpSpreadsheet\Writer\Html::class
* . '::COMMENT_HTML_TAGS_PLAINTEXT'
* )
* ) {
* new logic with styling in TextRun elements
* } else {
* old logic with styling via Html tags
* }.
*/
public const COMMENT_HTML_TAGS_PLAINTEXT = true;
/**
* Spreadsheet object.
*/
protected Spreadsheet $spreadsheet;
/**
* Sheet index to write.
*/
private ?int $sheetIndex = 0;
/**
* Images root.
*/
private string $imagesRoot = '';
/**
* embed images, or link to images.
*/
protected bool $embedImages = false;
/**
* Use inline CSS?
*/
private bool $useInlineCss = false;
/**
* Array of CSS styles.
*
* @var string[][]
*/
private ?array $cssStyles = null;
/**
* Array of column widths in points.
*
* @var array<array<float|int>>
*/
private array $columnWidths;
/**
* Default font.
*/
private Font $defaultFont;
/**
* Flag whether spans have been calculated.
*/
private bool $spansAreCalculated = false;
/**
* Excel cells that should not be written as HTML cells.
*
* @var mixed[][][][]
*/
private array $isSpannedCell = [];
/**
* Excel cells that are upper-left corner in a cell merge.
*
* @var int[][][][]
*/
private array $isBaseCell = [];
/**
* Is the current writer creating PDF?
*/
protected bool $isPdf = false;
/**
* Generate the Navigation block.
*/
private bool $generateSheetNavigationBlock = true;
/**
* Callback for editing generated html.
*
* @var null|callable(string): string
*/
private $editHtmlCallback;
/** @var BaseDrawing[] */
private $sheetDrawings;
/** @var Chart[] */
private $sheetCharts;
private bool $betterBoolean = true;
private string $getTrue = 'TRUE';
private string $getFalse = 'FALSE';
protected bool $rtlSheets = false;
protected bool $ltrSheets = false;
/**
* Table formats
* Enables table formats in writer, disabled here, must be enabled in writer via a setter.
*/
protected bool $tableFormats = false;
/**
* Table formats for unstyled tables.
* Enables default style for builtin table formats.
* If null, it takes on the same value as $tableFormats.
*/
protected ?bool $tableFormatsBuiltin = null;
/**
* Conditional Formatting
* Enables conditional formatting in writer, disabled here, must be enabled in writer via a setter.
*/
protected bool $conditionalFormatting = false;
/**
* Create a new HTML.
*/
public function __construct(Spreadsheet $spreadsheet)
{
$this->spreadsheet = $spreadsheet;
$this->defaultFont = $this->spreadsheet->getDefaultStyle()->getFont();
$calc = Calculation::getInstance($this->spreadsheet);
$this->getTrue = $calc->getTRUE();
$this->getFalse = $calc->getFALSE();
}
/**
* Save Spreadsheet to file.
*
* @param resource|string $filename
*/
public function save($filename, int $flags = 0): void
{
$this->processFlags($flags);
// Open file
$this->openFileHandle($filename);
// Write html
fwrite($this->fileHandle, $this->generateHTMLAll());
// Close file
$this->maybeCloseFileHandle();
}
protected function checkRtlAndLtr(): void
{
$this->rtlSheets = false;
$this->ltrSheets = false;
if ($this->sheetIndex === null) {
foreach ($this->spreadsheet->getAllSheets() as $sheet) {
if ($sheet->getRightToLeft()) {
$this->rtlSheets = true;
} else {
$this->ltrSheets = true;
}
}
} else {
if ($this->spreadsheet->getSheet($this->sheetIndex)->getRightToLeft()) {
$this->rtlSheets = true;
}
}
}
/**
* Save Spreadsheet as html to variable.
*/
public function generateHtmlAll(): string
{
$this->checkRtlAndLtr();
$sheets = $this->generateSheetPrep();
foreach ($sheets as $sheet) {
$sheet->calculateArrays($this->preCalculateFormulas);
}
// garbage collect
$this->spreadsheet->garbageCollect();
$saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog();
Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false);
// Build CSS
$this->buildCSS(!$this->useInlineCss);
$html = '';
// Write headers
$html .= $this->generateHTMLHeader(!$this->useInlineCss);
// Write navigation (tabs)
if ((!$this->isPdf) && ($this->generateSheetNavigationBlock)) {
$html .= $this->generateNavigation();
}
// Write data
$html .= $this->generateSheetData();
// Write footer
$html .= $this->generateHTMLFooter();
$callback = $this->editHtmlCallback;
if ($callback) {
$html = $callback($html);
}
Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
return $html;
}
/**
* Set a callback to edit the entire HTML.
*
* The callback must accept the HTML as string as first parameter,
* and it must return the edited HTML as string.
*/
public function setEditHtmlCallback(?callable $callback): void
{
$this->editHtmlCallback = $callback;
}
/**
* Map VAlign.
*
* @param string $vAlign Vertical alignment
*/
private function mapVAlign(string $vAlign): string
{
return Alignment::VERTICAL_ALIGNMENT_FOR_HTML[$vAlign] ?? '';
}
/**
* Map HAlign.
*
* @param string $hAlign Horizontal alignment
*/
private function mapHAlign(string $hAlign): string
{
return Alignment::HORIZONTAL_ALIGNMENT_FOR_HTML[$hAlign] ?? '';
}
const BORDER_NONE = 'none';
const BORDER_ARR = [
Border::BORDER_NONE => self::BORDER_NONE,
Border::BORDER_DASHDOT => '1px dashed',
Border::BORDER_DASHDOTDOT => '1px dotted',
Border::BORDER_DASHED => '1px dashed',
Border::BORDER_DOTTED => '1px dotted',
Border::BORDER_DOUBLE => '3px double',
Border::BORDER_HAIR => '1px solid',
Border::BORDER_MEDIUM => '2px solid',
Border::BORDER_MEDIUMDASHDOT => '2px dashed',
Border::BORDER_MEDIUMDASHDOTDOT => '2px dotted',
Border::BORDER_SLANTDASHDOT => '2px dashed',
Border::BORDER_THICK => '3px solid',
];
/**
* Map border style.
*
* @param int|string $borderStyle Sheet index
*/
private function mapBorderStyle($borderStyle): string
{
return self::BORDER_ARR[$borderStyle] ?? '1px solid';
}
/**
* Get sheet index.
*/
public function getSheetIndex(): ?int
{
return $this->sheetIndex;
}
/**
* Set sheet index.
*
* @param int $sheetIndex Sheet index
*
* @return $this
*/
public function setSheetIndex(int $sheetIndex): static
{
$this->sheetIndex = $sheetIndex;
return $this;
}
/**
* Get sheet index.
*/
public function getGenerateSheetNavigationBlock(): bool
{
return $this->generateSheetNavigationBlock;
}
/**
* Set sheet index.
*
* @param bool $generateSheetNavigationBlock Flag indicating whether the sheet navigation block should be generated or not
*
* @return $this
*/
public function setGenerateSheetNavigationBlock(bool $generateSheetNavigationBlock): static
{
$this->generateSheetNavigationBlock = (bool) $generateSheetNavigationBlock;
return $this;
}
/**
* Write all sheets (resets sheetIndex to NULL).
*
* @return $this
*/
public function writeAllSheets(): static
{
$this->sheetIndex = null;
return $this;
}
private static function generateMeta(?string $val, string $desc): string
{
return ($val || $val === '0')
? (' <meta name="' . $desc . '" content="' . htmlspecialchars($val, Settings::htmlEntityFlags()) . '" />' . PHP_EOL)
: '';
}
public const BODY_LINE = ' <body>' . PHP_EOL;
private const CUSTOM_TO_META = [
Properties::PROPERTY_TYPE_BOOLEAN => 'bool',
Properties::PROPERTY_TYPE_DATE => 'date',
Properties::PROPERTY_TYPE_FLOAT => 'float',
Properties::PROPERTY_TYPE_INTEGER => 'int',
Properties::PROPERTY_TYPE_STRING => 'string',
];
/**
* Generate HTML header.
*
* @param bool $includeStyles Include styles?
*/
public function generateHTMLHeader(bool $includeStyles = false): string
{
// Construct HTML
$properties = $this->spreadsheet->getProperties();
$html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . PHP_EOL;
$rtl = ($this->rtlSheets && !$this->ltrSheets) ? " dir='rtl'" : '';
$html .= '<html xmlns="http://www.w3.org/1999/xhtml"' . $rtl . '>' . PHP_EOL;
$html .= ' <head>' . PHP_EOL;
$html .= ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . PHP_EOL;
$html .= ' <meta name="generator" content="PhpSpreadsheet, https://github.com/PHPOffice/PhpSpreadsheet" />' . PHP_EOL;
$title = $properties->getTitle();
if ($title === '') {
$title = $this->spreadsheet->getActiveSheet()->getTitle();
}
$html .= ' <title>' . htmlspecialchars($title, Settings::htmlEntityFlags()) . '</title>' . PHP_EOL;
$html .= self::generateMeta($properties->getCreator(), 'author');
$html .= self::generateMeta($properties->getTitle(), 'title');
$html .= self::generateMeta($properties->getDescription(), 'description');
$html .= self::generateMeta($properties->getSubject(), 'subject');
$html .= self::generateMeta($properties->getKeywords(), 'keywords');
$html .= self::generateMeta($properties->getCategory(), 'category');
$html .= self::generateMeta($properties->getCompany(), 'company');
$html .= self::generateMeta($properties->getManager(), 'manager');
$html .= self::generateMeta($properties->getLastModifiedBy(), 'lastModifiedBy');
$html .= self::generateMeta($properties->getViewport(), 'viewport');
$date = Date::dateTimeFromTimestamp((string) $properties->getCreated());
$date->setTimeZone(Date::getDefaultOrLocalTimeZone());
$html .= self::generateMeta($date->format(DATE_W3C), 'created');
$date = Date::dateTimeFromTimestamp((string) $properties->getModified());
$date->setTimeZone(Date::getDefaultOrLocalTimeZone());
$html .= self::generateMeta($date->format(DATE_W3C), 'modified');
$customProperties = $properties->getCustomProperties();
foreach ($customProperties as $customProperty) {
$propertyValue = $properties->getCustomPropertyValue($customProperty);
$propertyType = $properties->getCustomPropertyType($customProperty);
$propertyQualifier = self::CUSTOM_TO_META[$propertyType] ?? null;
if ($propertyQualifier !== null) {
if ($propertyType === Properties::PROPERTY_TYPE_BOOLEAN) {
$propertyValue = $propertyValue ? '1' : '0';
} elseif ($propertyType === Properties::PROPERTY_TYPE_DATE) {
$date = Date::dateTimeFromTimestamp((string) $propertyValue);
$date->setTimeZone(Date::getDefaultOrLocalTimeZone());
$propertyValue = $date->format(DATE_W3C);
} else {
$propertyValue = (string) $propertyValue;
}
$html .= self::generateMeta($propertyValue, htmlspecialchars("custom.$propertyQualifier.$customProperty"));
}
}
if (!empty($properties->getHyperlinkBase())) {
$html .= ' <base href="' . htmlspecialchars($properties->getHyperlinkBase()) . '" />' . PHP_EOL;
}
$html .= $includeStyles ? $this->generateStyles(true) : $this->generatePageDeclarations(true);
$html .= ' </head>' . PHP_EOL;
$html .= '' . PHP_EOL;
$html .= self::BODY_LINE;
return $html;
}
/** @return Worksheet[] */
private function generateSheetPrep(): array
{
// Fetch sheets
if ($this->sheetIndex === null) {
$sheets = $this->spreadsheet->getAllSheets();
} else {
$sheets = [$this->spreadsheet->getSheet($this->sheetIndex)];
}
return $sheets;
}
/** @return array{int, int, int} */
private function generateSheetStarts(Worksheet $sheet, int $rowMin): array
{
// calculate start of <tbody>, <thead>
$tbodyStart = $rowMin;
$theadStart = $theadEnd = 0; // default: no <thead> no </thead>
if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
$rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop();
// we can only support repeating rows that start at top row
if ($rowsToRepeatAtTop[0] == 1) {
$theadStart = $rowsToRepeatAtTop[0];
$theadEnd = $rowsToRepeatAtTop[1];
$tbodyStart = $rowsToRepeatAtTop[1] + 1;
}
}
return [$theadStart, $theadEnd, $tbodyStart];
}
/** @return array{string, string, string} */
private function generateSheetTags(int $row, int $theadStart, int $theadEnd, int $tbodyStart): array
{
// <thead> ?
$startTag = ($row == $theadStart) ? (' <thead>' . PHP_EOL) : '';
if (!$startTag) {
$startTag = ($row == $tbodyStart) ? (' <tbody>' . PHP_EOL) : '';
}
$endTag = ($row == $theadEnd) ? (' </thead>' . PHP_EOL) : '';
$cellType = ($row >= $tbodyStart) ? 'td' : 'th';
return [$cellType, $startTag, $endTag];
}
private int $printAreaLowRow = -1;
private int $printAreaHighRow = -1;
private int $printAreaLowCol = -1;
private int $printAreaHighCol = -1;
/**
* Generate sheet data.
*/
public function generateSheetData(): string
{
// Ensure that Spans have been calculated?
$this->calculateSpans();
$sheets = $this->generateSheetPrep();
// Construct HTML
$html = '';
// Loop all sheets
$sheetId = 0;
$activeSheet = $this->spreadsheet->getActiveSheetIndex();
foreach ($sheets as $sheet) {
$this->printAreaLowRow = -1;
$this->printAreaHighRow = -1;
$this->printAreaLowCol = -1;
$this->printAreaHighCol = -1;
$printArea = $sheet->getPageSetup()->getPrintArea();
if (Preg::isMatch('/^([a-z]+)([0-9]+):([a-z]+)([0-9]+)$/i', $printArea, $matches)) {
$this->printAreaLowCol = Coordinate::columnIndexFromString($matches[1]);
$this->printAreaHighCol = Coordinate::columnIndexFromString($matches[3]);
$this->printAreaLowRow = (int) $matches[2];
$this->printAreaHighRow = (int) $matches[4];
}
// save active cells
$selectedCells = $sheet->getSelectedCells();
// Write table header
$html .= $this->generateTableHeader($sheet);
$this->sheetCharts = [];
$this->sheetDrawings = [];
$condStylesCollection = $sheet->getConditionalStylesCollection();
foreach ($condStylesCollection as $condStyles) {
foreach ($condStyles as $key => $cs) {
if ($cs->getConditionType() === Conditional::CONDITION_COLORSCALE) {
$cs->getColorScale()?->setScaleArray();
}
}
}
// Get worksheet dimension
[$min, $max] = explode(':', $sheet->calculateWorksheetDataDimension());
[$minCol, $minRow, $minColString] = Coordinate::indexesFromString($min);
[$maxCol, $maxRow] = Coordinate::indexesFromString($max);
$this->extendRowsAndColumns($sheet, $maxCol, $maxRow);
$this->extendRowsAndColumnsForMerge($sheet, $maxCol, $maxRow);
[$theadStart, $theadEnd, $tbodyStart] = $this->generateSheetStarts($sheet, $minRow);
// Loop through cells
$row = $minRow - 1;
while ($row++ < $maxRow) {
[$cellType, $startTag, $endTag] = $this->generateSheetTags($row, $theadStart, $theadEnd, $tbodyStart);
$html .= StringHelper::convertToString($startTag);
// Write row if there are HTML table cells in it
if ($this->shouldGenerateRow($sheet, $row)) {
// Start a new rowData
$rowData = [];
// Loop through columns
$column = $minCol;
$colStr = $minColString;
while ($column <= $maxCol) {
// Cell exists?
$cellAddress = Coordinate::stringFromColumnIndex($column) . $row;
if ($this->shouldGenerateColumn($sheet, $colStr)) {
$rowData[$column] = ($sheet->getCellCollection()->has($cellAddress)) ? $cellAddress : '';
}
++$column;
/** @var string $colStr */
StringHelper::stringIncrement($colStr);
}
$html .= $this->generateRow($sheet, $rowData, $row - 1, $cellType);
}
$html .= StringHelper::convertToString($endTag);
}
// Write table footer
$html .= $this->generateTableFooter();
// Writing PDF?
if ($this->isPdf && $this->useInlineCss) {
if ($this->sheetIndex === null && $sheetId + 1 < $this->spreadsheet->getSheetCount()) {
$html .= '<div style="page-break-before:always" ></div>';
}
}
// Next sheet
++$sheetId;
$sheet->setSelectedCells($selectedCells);
}
$this->spreadsheet->setActiveSheetIndex($activeSheet);
return $html;
}
/**
* Generate sheet tabs.
*/
public function generateNavigation(): string
{
// Fetch sheets
$sheets = [];
if ($this->sheetIndex === null) {
$sheets = $this->spreadsheet->getAllSheets();
} else {
$sheets[] = $this->spreadsheet->getSheet($this->sheetIndex);
}
// Construct HTML
$html = '';
// Only if there are more than 1 sheets
if (count($sheets) > 1) {
// Loop all sheets
$sheetId = 0;
$html .= '<ul class="navigation">' . PHP_EOL;
foreach ($sheets as $sheet) {
$html .= ' <li class="sheet' . $sheetId . '"><a href="#sheet' . $sheetId . '">' . htmlspecialchars($sheet->getTitle()) . '</a></li>' . PHP_EOL;
++$sheetId;
}
$html .= '</ul>' . PHP_EOL;
}
return $html;
}
private function extendRowsAndColumns(Worksheet $worksheet, int &$colMax, int &$rowMax): void
{
if ($this->includeCharts) {
foreach ($worksheet->getChartCollection() as $chart) {
$chartCoordinates = $chart->getTopLeftPosition();
$this->sheetCharts[$chartCoordinates['cell']] = $chart;
$chartTL = Coordinate::indexesFromString($chartCoordinates['cell']);
if ($chartTL[1] > $rowMax) {
$rowMax = $chartTL[1];
}
if ($chartTL[0] > $colMax) {
$colMax = $chartTL[0];
}
}
}
foreach ($worksheet->getDrawingCollection() as $drawing) {
if ($drawing instanceof Drawing && $drawing->getPath() === '') {
continue;
}
$imageTL = Coordinate::indexesFromString($drawing->getCoordinates());
$this->sheetDrawings[$drawing->getCoordinates()] = $drawing;
if ($imageTL[1] > $rowMax) {
$rowMax = $imageTL[1];
}
if ($imageTL[0] > $colMax) {
$colMax = $imageTL[0];
}
}
}
/**
* Convert Windows file name to file protocol URL.
*
* @param string $filename file name on local system
*/
public static function winFileToUrl(string $filename, bool $mpdf = false): string
{
// Windows filename
if (substr($filename, 1, 2) === ':\\') {
$protocol = $mpdf ? '' : 'file:///';
$filename = $protocol . str_replace('\\', '/', $filename);
}
return $filename;
}
/**
* Generate image tag in cell.
*
* @param string $coordinates Cell coordinates
*/
private function writeImageInCell(string $coordinates): string
{
// Construct HTML
$html = '';
// Write images
$drawing = $this->sheetDrawings[$coordinates] ?? null;
if ($drawing !== null) {
$opacity = '';
$opacityValue = $drawing->getOpacity();
if ($opacityValue !== null) {
$opacityValue = $opacityValue / 100000;
if ($opacityValue >= 0.0 && $opacityValue <= 1.0) {
$opacity = "opacity:$opacityValue; ";
}
}
$filedesc = $drawing->getDescription();
$filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded image';
if ($drawing instanceof Drawing && $drawing->getPath() !== '') {
$filename = $drawing->getPath();
// Strip off eventual '.'
$filename = Preg::replace('/^[.]/', '', $filename);
// Prepend images root
$filename = $this->getImagesRoot() . $filename;
// Strip off eventual '.' if followed by non-/
$filename = Preg::replace('@^[.]([^/])@', '$1', $filename);
// Convert UTF8 data to PCDATA
$filename = htmlspecialchars($filename, Settings::htmlEntityFlags());
$html .= PHP_EOL;
$imageData = self::winFileToUrl($filename, $this instanceof Pdf\Mpdf);
if ($this->embedImages || str_starts_with($imageData, 'zip://')) {
$imageData = 'data:,';
$picture = @file_get_contents($filename);
if ($picture !== false) {
$mimeContentType = (string) @mime_content_type($filename);
if (str_starts_with($mimeContentType, 'image/')) {
// base64 encode the binary data
$base64 = base64_encode($picture);
$imageData = 'data:' . $mimeContentType . ';base64,' . $base64;
}
}
}
$html .= '<img style="' . $opacity . 'position: absolute; z-index: 1; left: '
. $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px; width: '
. $drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="'
. $imageData . '" alt="' . $filedesc . '" />';
} elseif ($drawing instanceof MemoryDrawing) {
$imageResource = $drawing->getImageResource();
if ($imageResource) {
ob_start(); // Let's start output buffering.
imagepng($imageResource); // This will normally output the image, but because of ob_start(), it won't.
$contents = (string) ob_get_contents(); // Instead, output above is saved to $contents
ob_end_clean(); // End the output buffer.
$dataUri = 'data:image/png;base64,' . base64_encode($contents);
// Because of the nature of tables, width is more important than height.
// max-width: 100% ensures that image doesn't overflow containing cell
// However, PR #3535 broke test
// 25_In_memory_image, apparently because
// of the use of max-with. In addition,
// non-memory-drawings don't use max-width.
// Its use here is suspect and is being eliminated.
// width: X sets width of supplied image.
// As a result, images bigger than cell will be contained and images smaller will not get stretched
$html .= '<img alt="' . $filedesc . '" src="' . $dataUri . '" style="' . $opacity . 'width:' . $drawing->getWidth() . 'px;left: '
. $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px;position: absolute; z-index: 1;" />';
}
}
}
return $html;
}
/**
* Generate chart tag in cell.
* This code should be exercised by sample:
* Chart/32_Chart_read_write_PDF.php.
*/
private function writeChartInCell(Worksheet $worksheet, string $coordinates): string
{
// Construct HTML
$html = '';
// Write charts
$chart = $this->sheetCharts[$coordinates] ?? null;
if ($chart !== null) {
$chartCoordinates = $chart->getTopLeftPosition();
$chartFileName = File::sysGetTempDir() . '/' . uniqid('', true) . '.png';
$renderedWidth = $chart->getRenderedWidth();
$renderedHeight = $chart->getRenderedHeight();
if ($renderedWidth === null || $renderedHeight === null) {
$this->adjustRendererPositions($chart, $worksheet);
}
$title = $chart->getTitle();
$caption = null;
$filedesc = '';
if ($title !== null) {
$calculatedTitle = $title->getCalculatedTitle($worksheet->getParent());
if ($calculatedTitle !== null) {
$caption = $title->getCaption();
$title->setCaption($calculatedTitle);
}
$filedesc = $title->getCaptionText($worksheet->getParent());
}
$renderSuccessful = $chart->render($chartFileName);
$chart->setRenderedWidth($renderedWidth);
$chart->setRenderedHeight($renderedHeight);
if (isset($title, $caption)) {
$title->setCaption($caption);
}
if (!$renderSuccessful) {
return '';
}
$html .= PHP_EOL;
$imageDetails = getimagesize($chartFileName) ?: ['', '', 'mime' => ''];
$filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded chart';
$picture = file_get_contents($chartFileName);
unlink($chartFileName);
if ($picture !== false) {
$base64 = base64_encode($picture);
$imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64;
$html .= '<img style="position: absolute; z-index: 1; left: ' . $chartCoordinates['xOffset'] . 'px; top: ' . $chartCoordinates['yOffset'] . 'px; width: ' . $imageDetails[0] . 'px; height: ' . $imageDetails[1] . 'px;" src="' . $imageData . '" alt="' . $filedesc . '" />' . PHP_EOL;
}
}
// Return
return $html;
}
private function adjustRendererPositions(Chart $chart, Worksheet $sheet): void
{
$topLeft = $chart->getTopLeftPosition();
$bottomRight = $chart->getBottomRightPosition();
$tlCell = $topLeft['cell'];
/** @var string */
$brCell = $bottomRight['cell'];
if ($tlCell !== '' && $brCell !== '') {
$tlCoordinate = Coordinate::indexesFromString($tlCell);
$brCoordinate = Coordinate::indexesFromString($brCell);
$totalHeight = 0.0;
$totalWidth = 0.0;
$defaultRowHeight = $sheet->getDefaultRowDimension()->getRowHeight();
$defaultRowHeight = SharedDrawing::pointsToPixels(($defaultRowHeight >= 0) ? $defaultRowHeight : SharedFont::getDefaultRowHeightByFont($this->defaultFont));
if ($tlCoordinate[1] <= $brCoordinate[1] && $tlCoordinate[0] <= $brCoordinate[0]) {
for ($row = $tlCoordinate[1]; $row <= $brCoordinate[1]; ++$row) {
$height = $sheet->getRowDimension($row)->getRowHeight('pt');
$totalHeight += ($height >= 0) ? $height : $defaultRowHeight;
}
$rightEdge = $brCoordinate[2];
StringHelper::stringIncrement($rightEdge);
for ($column = $tlCoordinate[2]; $column !== $rightEdge;) {
$width = $sheet->getColumnDimension($column)->getWidth();
$width = ($width < 0) ? self::DEFAULT_CELL_WIDTH_PIXELS : SharedDrawing::cellDimensionToPixels($sheet->getColumnDimension($column)->getWidth(), $this->defaultFont);
$totalWidth += $width;
StringHelper::stringIncrement($column);
}
$chart->setRenderedWidth($totalWidth);
$chart->setRenderedHeight($totalHeight);
}
}
}
/**
* Generate CSS styles.
*
* @param bool $generateSurroundingHTML Generate surrounding HTML tags? (<style> and </style>)
*/
public function generateStyles(bool $generateSurroundingHTML = true): string
{
// Build CSS
$css = $this->buildCSS($generateSurroundingHTML);
// Construct HTML
$html = '';
// Start styles
if ($generateSurroundingHTML) {
$html .= ' <style type="text/css">' . PHP_EOL;
$html .= (array_key_exists('html', $css)) ? (' html { ' . $this->assembleCSS($css['html']) . ' }' . PHP_EOL) : '';
}
// Write all other styles
foreach ($css as $styleName => $styleDefinition) {
if ($styleName != 'html') {
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | true |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xlsx.php | src/PhpSpreadsheet/Writer/Xlsx.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\HashTable;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
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\Worksheet\BaseDrawing;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing as WorksheetDrawing;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Chart;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Comments;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\ContentTypes;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\DocProps;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Drawing;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsRibbon;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsVBA;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\StringTable;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Style;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Table;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Theme;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Workbook;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet;
use ZipArchive;
use ZipStream\Exception\OverflowException;
use ZipStream\ZipStream;
class Xlsx extends BaseWriter
{
/**
* Office2003 compatibility.
*/
private bool $office2003compatibility = false;
/**
* Private Spreadsheet.
*/
private Spreadsheet $spreadSheet;
/**
* Private string table.
*
* @var string[]
*/
private array $stringTable = [];
/**
* Private unique Conditional HashTable.
*
* @var HashTable<Conditional>
*/
private HashTable $stylesConditionalHashTable;
/**
* Private unique Style HashTable.
*
* @var HashTable<\PhpOffice\PhpSpreadsheet\Style\Style>
*/
private HashTable $styleHashTable;
/**
* Private unique Fill HashTable.
*
* @var HashTable<Fill>
*/
private HashTable $fillHashTable;
/**
* Private unique \PhpOffice\PhpSpreadsheet\Style\Font HashTable.
*
* @var HashTable<Font>
*/
private HashTable $fontHashTable;
/**
* Private unique Borders HashTable.
*
* @var HashTable<Borders>
*/
private HashTable $bordersHashTable;
/**
* Private unique NumberFormat HashTable.
*
* @var HashTable<NumberFormat>
*/
private HashTable $numFmtHashTable;
/**
* Private unique \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable.
*
* @var HashTable<BaseDrawing>
*/
private HashTable $drawingHashTable;
/**
* Private handle for zip stream.
*/
private ZipStream $zip;
private Chart $writerPartChart;
private Comments $writerPartComments;
private ContentTypes $writerPartContentTypes;
private DocProps $writerPartDocProps;
private Drawing $writerPartDrawing;
private Rels $writerPartRels;
private RelsRibbon $writerPartRelsRibbon;
private RelsVBA $writerPartRelsVBA;
private StringTable $writerPartStringTable;
private Style $writerPartStyle;
private Theme $writerPartTheme;
private Table $writerPartTable;
private Workbook $writerPartWorkbook;
private Worksheet $writerPartWorksheet;
private bool $explicitStyle0 = false;
private bool $useCSEArrays = false;
private bool $useDynamicArray = false;
public const DEFAULT_FORCE_FULL_CALC = false;
// Default changed from null in PhpSpreadsheet 4.0.0.
private ?bool $forceFullCalc = self::DEFAULT_FORCE_FULL_CALC;
protected bool $restrictMaxColumnWidth = false;
/**
* Create a new Xlsx Writer.
*/
public function __construct(Spreadsheet $spreadsheet)
{
// Assign PhpSpreadsheet
$this->setSpreadsheet($spreadsheet);
$this->writerPartChart = new Chart($this);
$this->writerPartComments = new Comments($this);
$this->writerPartContentTypes = new ContentTypes($this);
$this->writerPartDocProps = new DocProps($this);
$this->writerPartDrawing = new Drawing($this);
$this->writerPartRels = new Rels($this);
$this->writerPartRelsRibbon = new RelsRibbon($this);
$this->writerPartRelsVBA = new RelsVBA($this);
$this->writerPartStringTable = new StringTable($this);
$this->writerPartStyle = new Style($this);
$this->writerPartTheme = new Theme($this);
$this->writerPartTable = new Table($this);
$this->writerPartWorkbook = new Workbook($this);
$this->writerPartWorksheet = new Worksheet($this);
// Set HashTable variables
$this->bordersHashTable = new HashTable();
$this->drawingHashTable = new HashTable();
$this->fillHashTable = new HashTable();
$this->fontHashTable = new HashTable();
$this->numFmtHashTable = new HashTable();
$this->styleHashTable = new HashTable();
$this->stylesConditionalHashTable = new HashTable();
$this->determineUseDynamicArrays();
}
public function getWriterPartChart(): Chart
{
return $this->writerPartChart;
}
public function getWriterPartComments(): Comments
{
return $this->writerPartComments;
}
public function getWriterPartContentTypes(): ContentTypes
{
return $this->writerPartContentTypes;
}
public function getWriterPartDocProps(): DocProps
{
return $this->writerPartDocProps;
}
public function getWriterPartDrawing(): Drawing
{
return $this->writerPartDrawing;
}
public function getWriterPartRels(): Rels
{
return $this->writerPartRels;
}
public function getWriterPartRelsRibbon(): RelsRibbon
{
return $this->writerPartRelsRibbon;
}
public function getWriterPartRelsVBA(): RelsVBA
{
return $this->writerPartRelsVBA;
}
public function getWriterPartStringTable(): StringTable
{
return $this->writerPartStringTable;
}
public function getWriterPartStyle(): Style
{
return $this->writerPartStyle;
}
public function getWriterPartTheme(): Theme
{
return $this->writerPartTheme;
}
public function getWriterPartTable(): Table
{
return $this->writerPartTable;
}
public function getWriterPartWorkbook(): Workbook
{
return $this->writerPartWorkbook;
}
public function getWriterPartWorksheet(): Worksheet
{
return $this->writerPartWorksheet;
}
public function createStyleDictionaries(): void
{
$this->styleHashTable->addFromSource(
$this->getWriterPartStyle()->allStyles(
$this->spreadSheet
)
);
$this->stylesConditionalHashTable->addFromSource(
$this->getWriterPartStyle()->allConditionalStyles(
$this->spreadSheet
)
);
$this->fillHashTable->addFromSource(
$this->getWriterPartStyle()->allFills(
$this->spreadSheet
)
);
$this->fontHashTable->addFromSource(
$this->getWriterPartStyle()->allFonts(
$this->spreadSheet
)
);
$this->bordersHashTable->addFromSource(
$this->getWriterPartStyle()->allBorders(
$this->spreadSheet
)
);
$this->numFmtHashTable->addFromSource(
$this->getWriterPartStyle()->allNumberFormats(
$this->spreadSheet
)
);
}
/**
* @return (RichText|string)[] $stringTable
*/
public function createStringTable(): array
{
$this->stringTable = [];
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
$this->stringTable = $this->getWriterPartStringTable()->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable);
}
return $this->stringTable;
}
/**
* Save PhpSpreadsheet to file.
*
* @param resource|string $filename
*/
public function save($filename, int $flags = 0): void
{
$this->processFlags($flags);
$this->determineUseDynamicArrays();
// garbage collect
$this->pathNames = [];
$this->spreadSheet->garbageCollect();
$saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog();
Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false);
$saveDateReturnType = Functions::getReturnDateType();
Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
// Create string lookup table
$this->createStringTable();
// Create styles dictionaries
$this->createStyleDictionaries();
// Create drawing dictionary
$this->drawingHashTable->addFromSource($this->getWriterPartDrawing()->allDrawings($this->spreadSheet));
/** @var string[] */
$zipContent = [];
// Add [Content_Types].xml to ZIP file
$zipContent['[Content_Types].xml'] = $this->getWriterPartContentTypes()->writeContentTypes($this->spreadSheet, $this->includeCharts);
$metadataData = (new Xlsx\Metadata($this))->writeMetadata();
if ($metadataData !== '') {
$zipContent['xl/metadata.xml'] = $metadataData;
}
//if hasMacros, add the vbaProject.bin file, Certificate file(if exists)
if ($this->spreadSheet->hasMacros()) {
$macrosCode = $this->spreadSheet->getMacrosCode();
if ($macrosCode !== null) {
// we have the code ?
$zipContent['xl/vbaProject.bin'] = $macrosCode; //allways in 'xl', allways named vbaProject.bin
if ($this->spreadSheet->hasMacrosCertificate()) {
//signed macros ?
// Yes : add the certificate file and the related rels file
$zipContent['xl/vbaProjectSignature.bin'] = $this->spreadSheet->getMacrosCertificate();
$zipContent['xl/_rels/vbaProject.bin.rels'] = $this->getWriterPartRelsVBA()->writeVBARelationships();
}
}
}
//a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels)
if ($this->spreadSheet->hasRibbon()) {
$tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target');
$tmpRibbonTarget = is_string($tmpRibbonTarget) ? $tmpRibbonTarget : '';
$zipContent[$tmpRibbonTarget] = $this->spreadSheet->getRibbonXMLData('data');
if ($this->spreadSheet->hasRibbonBinObjects()) {
$tmpRootPath = dirname($tmpRibbonTarget) . '/';
$ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write
if (is_array($ribbonBinObjects)) {
foreach ($ribbonBinObjects as $aPath => $aContent) {
$zipContent[$tmpRootPath . $aPath] = $aContent;
}
}
//the rels for files
$zipContent[$tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels'] = $this->getWriterPartRelsRibbon()->writeRibbonRelationships($this->spreadSheet);
}
}
// Add relationships to ZIP file
$zipContent['_rels/.rels'] = $this->getWriterPartRels()->writeRelationships($this->spreadSheet);
$zipContent['xl/_rels/workbook.xml.rels'] = $this->getWriterPartRels()->writeWorkbookRelationships($this->spreadSheet);
// Add document properties to ZIP file
$zipContent['docProps/app.xml'] = $this->getWriterPartDocProps()->writeDocPropsApp($this->spreadSheet);
$zipContent['docProps/core.xml'] = $this->getWriterPartDocProps()->writeDocPropsCore($this->spreadSheet);
$customPropertiesPart = $this->getWriterPartDocProps()->writeDocPropsCustom($this->spreadSheet);
if ($customPropertiesPart !== null) {
$zipContent['docProps/custom.xml'] = $customPropertiesPart;
}
// Add theme to ZIP file
$zipContent['xl/theme/theme1.xml'] = $this->getWriterPartTheme()->writeTheme($this->spreadSheet);
// Add string table to ZIP file
$zipContent['xl/sharedStrings.xml'] = $this->getWriterPartStringTable()->writeStringTable($this->stringTable);
// Add styles to ZIP file
$zipContent['xl/styles.xml'] = $this->getWriterPartStyle()->writeStyles($this->spreadSheet);
// Add workbook to ZIP file
$zipContent['xl/workbook.xml'] = $this->getWriterPartWorkbook()->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas, $this->forceFullCalc);
$chartCount = 0;
// Add worksheets
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
$zipContent['xl/worksheets/sheet' . ($i + 1) . '.xml'] = $this->getWriterPartWorksheet()->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts);
if ($this->includeCharts) {
$charts = $this->spreadSheet->getSheet($i)->getChartCollection();
if (count($charts) > 0) {
foreach ($charts as $chart) {
$zipContent['xl/charts/chart' . ($chartCount + 1) . '.xml'] = $this->getWriterPartChart()->writeChart($chart, $this->preCalculateFormulas);
++$chartCount;
}
}
}
}
$chartRef1 = 0;
$tableRef1 = 1;
// Add worksheet relationships (drawings, ...)
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
// Add relationships
/** @var string[] $zipContent */
$zipContent['xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts, $tableRef1, $zipContent);
// Add unparsedLoadedData
$sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName();
/** @var mixed[][][] */
$unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData();
/** @var mixed[][] */
$unparsedSheet = $unparsedLoadedData['sheets'][$sheetCodeName] ?? [];
foreach (($unparsedSheet['ctrlProps'] ?? []) as $ctrlProp) {
/** @var string[] $ctrlProp */
$zipContent[$ctrlProp['filePath']] = $ctrlProp['content'];
}
foreach (($unparsedSheet['printerSettings'] ?? []) as $ctrlProp) {
/** @var string[] $ctrlProp */
$zipContent[$ctrlProp['filePath']] = $ctrlProp['content'];
}
$drawings = $this->spreadSheet->getSheet($i)->getDrawingCollection();
$drawingCount = count($drawings);
if ($this->includeCharts) {
$chartCount = $this->spreadSheet->getSheet($i)->getChartCount();
}
// Add drawing and image relationship parts
/** @var bool $hasPassThroughDrawing */
$hasPassThroughDrawing = $unparsedSheet['drawingPassThroughEnabled'] ?? false;
if (($drawingCount > 0) || ($chartCount > 0) || $hasPassThroughDrawing) {
// Drawing relationships
$zipContent['xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts);
// Drawings
$zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts);
} elseif (isset($unparsedSheet['drawingAlternateContents'])) {
// Drawings
$zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts);
}
// Add unparsed drawings
if (isset($unparsedSheet['Drawings']) && !isset($zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'])) {
foreach ($unparsedSheet['Drawings'] as $relId => $drawingXml) {
$drawingFile = array_search($relId, $unparsedSheet['drawingOriginalIds']);
if ($drawingFile !== false) {
//$drawingFile = ltrim($drawingFile, '.');
//$zipContent['xl' . $drawingFile] = $drawingXml;
$zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $drawingXml;
}
}
}
if (isset($unparsedSheet['drawingOriginalIds']) && !isset($zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'])) {
$zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = '<xml></xml>';
}
// Add comment relationship parts
/** @var mixed[][] */
$legacyTemp = $unparsedLoadedData['sheets'] ?? [];
$legacyTemp = $legacyTemp[$this->spreadSheet->getSheet($i)->getCodeName()] ?? [];
$legacy = $legacyTemp['legacyDrawing'] ?? null;
if (count($this->spreadSheet->getSheet($i)->getComments()) > 0 || $legacy !== null) {
// VML Comments relationships
$zipContent['xl/drawings/_rels/vmlDrawing' . ($i + 1) . '.vml.rels'] = $this->getWriterPartRels()->writeVMLDrawingRelationships($this->spreadSheet->getSheet($i));
// VML Comments
$zipContent['xl/drawings/vmlDrawing' . ($i + 1) . '.vml'] = $legacy ?? $this->getWriterPartComments()->writeVMLComments($this->spreadSheet->getSheet($i));
}
// Comments
if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) {
$zipContent['xl/comments' . ($i + 1) . '.xml'] = $this->getWriterPartComments()->writeComments($this->spreadSheet->getSheet($i));
// Media
foreach ($this->spreadSheet->getSheet($i)->getComments() as $comment) {
if ($comment->hasBackgroundImage()) {
$image = $comment->getBackgroundImage();
$zipContent['xl/media/' . $image->getMediaFilename()] = $this->processDrawing($image);
}
}
}
// Add unparsed relationship parts
if (isset($unparsedSheet['vmlDrawings'])) {
foreach ($unparsedSheet['vmlDrawings'] as $vmlDrawing) {
/** @var string[] $vmlDrawing */
if (!isset($zipContent[$vmlDrawing['filePath']])) {
$zipContent[$vmlDrawing['filePath']] = $vmlDrawing['content'];
}
}
}
// Add header/footer relationship parts
if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
// VML Drawings
$zipContent['xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml'] = $this->getWriterPartDrawing()->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i));
// VML Drawing relationships
$zipContent['xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels'] = $this->getWriterPartRels()->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i));
// Media
foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
if ($image->getPath() !== '') {
$zipContent['xl/media/' . $image->getIndexedFilename()] = file_get_contents($image->getPath());
}
}
}
// Add Table parts
$tables = $this->spreadSheet->getSheet($i)->getTableCollection();
foreach ($tables as $table) {
$zipContent['xl/tables/table' . $tableRef1 . '.xml'] = $this->getWriterPartTable()->writeTable($table, $tableRef1++);
}
}
// Add media
for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) {
if ($this->getDrawingHashTable()->getByIndex($i) instanceof WorksheetDrawing) {
$imageContents = null;
$imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
if ($imagePath === '') {
continue;
}
if (str_contains($imagePath, 'zip://')) {
$imagePath = substr($imagePath, 6);
$imagePathSplitted = explode('#', $imagePath);
$imageZip = new ZipArchive();
$imageZip->open($imagePathSplitted[0]);
$imageContents = $imageZip->getFromName($imagePathSplitted[1]);
$imageZip->close();
unset($imageZip);
} else {
$imageContents = file_get_contents($imagePath);
}
$zipContent['xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()] = $imageContents;
} elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) {
ob_start();
$callable = $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction();
call_user_func(
$callable,
$this->getDrawingHashTable()->getByIndex($i)->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
$zipContent['xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()] = $imageContents;
}
}
// Add pass-through media files (original media that may not be in the drawing collection)
$this->addPassThroughMediaFiles($zipContent); // @phpstan-ignore argument.type
Functions::setReturnDateType($saveDateReturnType);
Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
$this->openFileHandle($filename);
$this->zip = ZipStream0::newZipStream($this->fileHandle);
/** @var string[] $zipContent */
$this->addZipFiles($zipContent);
// Close file
try {
$this->zip->finish();
} catch (OverflowException) {
throw new WriterException('Could not close resource.');
}
$this->maybeCloseFileHandle();
}
/**
* Get Spreadsheet object.
*/
public function getSpreadsheet(): Spreadsheet
{
return $this->spreadSheet;
}
/**
* Set Spreadsheet object.
*
* @param Spreadsheet $spreadsheet PhpSpreadsheet object
*
* @return $this
*/
public function setSpreadsheet(Spreadsheet $spreadsheet): static
{
$this->spreadSheet = $spreadsheet;
return $this;
}
/**
* Get string table.
*
* @return string[]
*/
public function getStringTable(): array
{
return $this->stringTable;
}
/**
* Get Style HashTable.
*
* @return HashTable<\PhpOffice\PhpSpreadsheet\Style\Style>
*/
public function getStyleHashTable(): HashTable
{
return $this->styleHashTable;
}
/**
* Get Conditional HashTable.
*
* @return HashTable<Conditional>
*/
public function getStylesConditionalHashTable(): HashTable
{
return $this->stylesConditionalHashTable;
}
/**
* Get Fill HashTable.
*
* @return HashTable<Fill>
*/
public function getFillHashTable(): HashTable
{
return $this->fillHashTable;
}
/**
* Get \PhpOffice\PhpSpreadsheet\Style\Font HashTable.
*
* @return HashTable<Font>
*/
public function getFontHashTable(): HashTable
{
return $this->fontHashTable;
}
/**
* Get Borders HashTable.
*
* @return HashTable<Borders>
*/
public function getBordersHashTable(): HashTable
{
return $this->bordersHashTable;
}
/**
* Get NumberFormat HashTable.
*
* @return HashTable<NumberFormat>
*/
public function getNumFmtHashTable(): HashTable
{
return $this->numFmtHashTable;
}
/**
* Get \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable.
*
* @return HashTable<BaseDrawing>
*/
public function getDrawingHashTable(): HashTable
{
return $this->drawingHashTable;
}
/**
* Get Office2003 compatibility.
*/
public function getOffice2003Compatibility(): bool
{
return $this->office2003compatibility;
}
/**
* Set Office2003 compatibility.
*
* @param bool $office2003compatibility Office2003 compatibility?
*
* @return $this
*/
public function setOffice2003Compatibility(bool $office2003compatibility): static
{
$this->office2003compatibility = $office2003compatibility;
return $this;
}
/** @var string[] */
private array $pathNames = [];
private function addZipFile(string $path, string $content): void
{
if (!in_array($path, $this->pathNames)) {
$this->pathNames[] = $path;
$this->zip->addFile($path, $content);
}
}
/** @param string[] $zipContent */
private function addZipFiles(array $zipContent): void
{
foreach ($zipContent as $path => $content) {
$this->addZipFile($path, $content);
}
}
private function processDrawing(WorksheetDrawing $drawing): string|null|false
{
$data = null;
$filename = $drawing->getPath();
if ($filename === '') {
return null;
}
$imageData = getimagesize($filename);
if (!empty($imageData)) {
switch ($imageData[2]) {
case 1: // GIF, not supported by BIFF8, we convert to PNG
$image = imagecreatefromgif($filename);
if ($image !== false) {
ob_start();
imagepng($image);
$data = ob_get_contents();
ob_end_clean();
}
break;
case 2: // JPEG
$data = file_get_contents($filename);
break;
case 3: // PNG
$data = file_get_contents($filename);
break;
case 6: // Windows DIB (BMP), we convert to PNG
$image = imagecreatefrombmp($filename);
if ($image !== false) {
ob_start();
imagepng($image);
$data = ob_get_contents();
ob_end_clean();
}
break;
}
}
return $data;
}
public function getExplicitStyle0(): bool
{
return $this->explicitStyle0;
}
/**
* This may be useful if non-default Alignment is part of default style
* and you think you might want to open the spreadsheet
* with LibreOffice or Gnumeric.
*/
public function setExplicitStyle0(bool $explicitStyle0): self
{
$this->explicitStyle0 = $explicitStyle0;
return $this;
}
public function setUseCSEArrays(?bool $useCSEArrays): void
{
if ($useCSEArrays !== null) {
$this->useCSEArrays = $useCSEArrays;
}
$this->determineUseDynamicArrays();
}
public function useDynamicArrays(): bool
{
return $this->useDynamicArray;
}
private function determineUseDynamicArrays(): void
{
$this->useDynamicArray = $this->preCalculateFormulas && Calculation::getInstance($this->spreadSheet)->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY && !$this->useCSEArrays;
}
/**
* If this is set when a spreadsheet is opened,
* values may not be automatically re-calculated,
* and a button will be available to force re-calculation.
* This may apply to all spreadsheets open at that time.
* If null, this will be set to the opposite of $preCalculateFormulas.
* It is likely that false is the desired setting, although
* cases have been reported where true is required (issue #456).
* Nevertheless, default is set to false in PhpSpreadsheet 4.0.0.
*/
public function setForceFullCalc(?bool $forceFullCalc): self
{
$this->forceFullCalc = $forceFullCalc;
return $this;
}
/**
* Excel has a nominal width limint of 255 for a column.
* Surprisingly, Xlsx can read and write larger values,
* and the file will appear as desired,
* but the User Interface does not allow you to set the width beyond 255,
* either directly or though auto-fit width.
* Xls sets its own value when the width is beyond 255.
* This method gets whether PhpSpreadsheet should restrict the
* column widths which it writes to the Excel limit, for formats
* which allow it to exceed 255.
*/
public function setRestrictMaxColumnWidth(bool $restrictMaxColumnWidth): self
{
$this->restrictMaxColumnWidth = $restrictMaxColumnWidth;
return $this;
}
public function getRestrictMaxColumnWidth(): bool
{
return $this->restrictMaxColumnWidth;
}
/**
* Add pass-through media files from original spreadsheet.
* This copies media files that are referenced in pass-through drawing XML
* but may not be in the drawing collection (e.g., unsupported formats like SVG).
*
* @param string[] $zipContent
*/
private function addPassThroughMediaFiles(array &$zipContent): void
{
/** @var array<string, array<string, mixed>> $sheets */
$sheets = $this->spreadSheet->getUnparsedLoadedData()['sheets'] ?? [];
foreach ($sheets as $sheetData) {
/** @var string[] $mediaFiles */
$mediaFiles = $sheetData['drawingMediaFiles'] ?? [];
/** @var ?string $sourceFile */
$sourceFile = $sheetData['drawingSourceFile'] ?? null;
if (($sheetData['drawingPassThroughEnabled'] ?? false) !== true || $mediaFiles === [] || !is_string($sourceFile) || !file_exists($sourceFile)) {
continue;
}
$sourceZip = new ZipArchive();
if ($sourceZip->open($sourceFile) !== true) {
continue; // @codeCoverageIgnore
}
foreach ($mediaFiles as $mediaPath) {
$zipPath = 'xl/media/' . basename($mediaPath);
if (!isset($zipContent[$zipPath])) {
$mediaContent = $sourceZip->getFromName($mediaPath);
if ($mediaContent !== false) {
$zipContent[$zipPath] = $mediaContent;
}
}
}
$sourceZip->close();
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Ods.php | src/PhpSpreadsheet/Writer/Ods.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Content;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Meta;
use PhpOffice\PhpSpreadsheet\Writer\Ods\MetaInf;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Mimetype;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Settings;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Styles;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Thumbnails;
use ZipStream\Exception\OverflowException;
use ZipStream\ZipStream;
class Ods extends BaseWriter
{
/**
* Private PhpSpreadsheet.
*/
private Spreadsheet $spreadSheet;
private Content $writerPartContent;
private Meta $writerPartMeta;
private MetaInf $writerPartMetaInf;
private Mimetype $writerPartMimetype;
private Settings $writerPartSettings;
private Styles $writerPartStyles;
private Thumbnails $writerPartThumbnails;
/**
* Create a new Ods.
*/
public function __construct(Spreadsheet $spreadsheet)
{
$this->setSpreadsheet($spreadsheet);
$this->writerPartContent = new Content($this);
$this->writerPartMeta = new Meta($this);
$this->writerPartMetaInf = new MetaInf($this);
$this->writerPartMimetype = new Mimetype($this);
$this->writerPartSettings = new Settings($this);
$this->writerPartStyles = new Styles($this);
$this->writerPartThumbnails = new Thumbnails($this);
}
public function getWriterPartContent(): Content
{
return $this->writerPartContent;
}
public function getWriterPartMeta(): Meta
{
return $this->writerPartMeta;
}
public function getWriterPartMetaInf(): MetaInf
{
return $this->writerPartMetaInf;
}
public function getWriterPartMimetype(): Mimetype
{
return $this->writerPartMimetype;
}
public function getWriterPartSettings(): Settings
{
return $this->writerPartSettings;
}
public function getWriterPartStyles(): Styles
{
return $this->writerPartStyles;
}
public function getWriterPartThumbnails(): Thumbnails
{
return $this->writerPartThumbnails;
}
/**
* Save PhpSpreadsheet to file.
*
* @param resource|string $filename
*/
public function save($filename, int $flags = 0): void
{
$this->processFlags($flags);
// garbage collect
$this->spreadSheet->garbageCollect();
$this->openFileHandle($filename);
$zip = $this->createZip();
$zip->addFile('META-INF/manifest.xml', $this->getWriterPartMetaInf()->write());
$zip->addFile('Thumbnails/thumbnail.png', $this->getWriterPartthumbnails()->write());
// Settings always need to be written before Content; Styles after Content
$zip->addFile('settings.xml', $this->getWriterPartsettings()->write());
$zip->addFile('content.xml', $this->getWriterPartcontent()->write());
$zip->addFile('meta.xml', $this->getWriterPartmeta()->write());
$zip->addFile('mimetype', $this->getWriterPartmimetype()->write());
$zip->addFile('styles.xml', $this->getWriterPartstyles()->write());
// Close file
try {
$zip->finish();
} catch (OverflowException) {
throw new WriterException('Could not close resource.');
}
$this->maybeCloseFileHandle();
}
/**
* Create zip object.
*/
private function createZip(): ZipStream
{
// Try opening the ZIP file
if (!is_resource($this->fileHandle)) {
throw new WriterException('Could not open resource for writing.');
}
// Create new ZIP stream
return ZipStream0::newZipStream($this->fileHandle);
}
/**
* Get Spreadsheet object.
*/
public function getSpreadsheet(): Spreadsheet
{
return $this->spreadSheet;
}
/**
* Set Spreadsheet object.
*
* @param Spreadsheet $spreadsheet PhpSpreadsheet object
*
* @return $this
*/
public function setSpreadsheet(Spreadsheet $spreadsheet): static
{
$this->spreadSheet = $spreadsheet;
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls/Workbook.php | src/PhpSpreadsheet/Writer/Xls/Workbook.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
use Composer\Pcre\Preg;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Style;
// Original file header of PEAR::Spreadsheet_Excel_Writer_Workbook (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 Workbook extends BIFFwriter
{
/**
* Formula parser.
*/
private Parser $parser;
/*
* The BIFF file size for the workbook. Not currently used.
*
* @see calcSheetOffsets()
*/
//private int $biffSize;
/**
* XF Writers.
*
* @var Xf[]
*/
private array $xfWriters = [];
/**
* Array containing the colour palette.
*
* @var array<int, array{int, int, int, int}>
*/
private array $palette;
/**
* The codepage indicates the text encoding used for strings.
*/
private int $codepage;
/**
* The country code used for localization.
*/
private int $countryCode;
/**
* Workbook.
*/
private Spreadsheet $spreadsheet;
/**
* Fonts writers.
*
* @var Font[]
*/
private array $fontWriters = [];
/**
* Added fonts. Maps from font's hash => index in workbook.
*
* @var int[]
*/
private array $addedFonts = [];
/**
* Shared number formats.
*
* @var NumberFormat[]
*/
private array $numberFormats = [];
/**
* Added number formats. Maps from numberFormat's hash => index in workbook.
*
* @var int[]
*/
private array $addedNumberFormats = [];
/**
* Sizes of the binary worksheet streams.
*
* @var int[]
*/
private array $worksheetSizes = [];
/**
* Offsets of the binary worksheet streams relative to the start of the global workbook stream.
*
* @var int[]
*/
private array $worksheetOffsets = [];
/**
* Total number of shared strings in workbook.
*/
private int $stringTotal;
/**
* Number of unique shared strings in workbook.
*/
private int $stringUnique;
/**
* Array of unique shared strings in workbook.
*
* @var array<string, int>
*/
private array $stringTable;
/**
* Color cache.
*
* @var int[]
*/
private array $colors;
/**
* Escher object corresponding to MSODRAWINGGROUP.
*/
private ?\PhpOffice\PhpSpreadsheet\Shared\Escher $escher = null;
/**
* Class constructor.
*
* @param Spreadsheet $spreadsheet The Workbook
* @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 int[] $colors Colour Table
* @param Parser $parser The formula parser created for the Workbook
*/
public function __construct(Spreadsheet $spreadsheet, int &$str_total, int &$str_unique, array &$str_table, array &$colors, Parser $parser)
{
// It needs to call its parent's constructor explicitly
parent::__construct();
$this->parser = $parser;
//$this->biffSize = 0;
$this->palette = [];
$this->countryCode = -1;
$this->stringTotal = &$str_total;
$this->stringUnique = &$str_unique;
$this->stringTable = &$str_table;
$this->colors = &$colors;
$this->setPaletteXl97();
$this->spreadsheet = $spreadsheet;
$this->codepage = 0x04B0;
// Add empty sheets and Build color cache
$countSheets = $spreadsheet->getSheetCount();
for ($i = 0; $i < $countSheets; ++$i) {
$phpSheet = $spreadsheet->getSheet($i);
$this->parser->setExtSheet($phpSheet->getTitle(), $i); // Register worksheet name with parser
$supbook_index = 0x00;
$ref = pack('vvv', $supbook_index, $i, $i);
$this->parser->references[] = $ref; // Register reference with parser
// Sheet tab colors?
if ($phpSheet->isTabColorSet()) {
$this->addColor($phpSheet->getTabColor()->getRGB());
}
}
}
/**
* Add a new XF writer.
*
* @param bool $isStyleXf Is it a style XF?
*
* @return int Index to XF record
*/
public function addXfWriter(Style $style, bool $isStyleXf = false): int
{
$xfWriter = new Xf($style);
$xfWriter->setIsStyleXf($isStyleXf);
// Add the font if not already added
$fontIndex = $this->addFont($style->getFont());
// Assign the font index to the xf record
$xfWriter->setFontIndex($fontIndex);
// Background colors, best to treat these after the font so black will come after white in custom palette
if ($style->getFill()->getStartColor()->getRGB()) {
$xfWriter->setFgColor(
$this->addColor(
$style->getFill()->getStartColor()->getRGB()
)
);
}
if ($style->getFill()->getEndColor()->getRGB()) {
$xfWriter->setBgColor(
$this->addColor(
$style->getFill()->getEndColor()->getRGB()
)
);
}
$xfWriter->setBottomColor($this->addColor($style->getBorders()->getBottom()->getColor()->getRGB()));
$xfWriter->setTopColor($this->addColor($style->getBorders()->getTop()->getColor()->getRGB()));
$xfWriter->setRightColor($this->addColor($style->getBorders()->getRight()->getColor()->getRGB()));
$xfWriter->setLeftColor($this->addColor($style->getBorders()->getLeft()->getColor()->getRGB()));
$xfWriter->setDiagColor($this->addColor($style->getBorders()->getDiagonal()->getColor()->getRGB()));
// Add the number format if it is not a built-in one and not already added
if ($style->getNumberFormat()->getBuiltInFormatCode() === false) {
$numberFormatHashCode = $style->getNumberFormat()->getHashCode();
if (isset($this->addedNumberFormats[$numberFormatHashCode])) {
$numberFormatIndex = $this->addedNumberFormats[$numberFormatHashCode];
} else {
$numberFormatIndex = 164 + count($this->numberFormats);
$this->numberFormats[$numberFormatIndex] = $style->getNumberFormat();
$this->addedNumberFormats[$numberFormatHashCode] = $numberFormatIndex;
}
} else {
$numberFormatIndex = (int) $style->getNumberFormat()->getBuiltInFormatCode();
}
// Assign the number format index to xf record
$xfWriter->setNumberFormatIndex($numberFormatIndex);
$this->xfWriters[] = $xfWriter;
return count($this->xfWriters) - 1;
}
/**
* Add a font to added fonts.
*
* @return int Index to FONT record
*/
public function addFont(\PhpOffice\PhpSpreadsheet\Style\Font $font): int
{
$fontHashCode = $font->getHashCode();
if (isset($this->addedFonts[$fontHashCode])) {
$fontIndex = $this->addedFonts[$fontHashCode];
} else {
$countFonts = count($this->fontWriters);
$fontIndex = ($countFonts < 4) ? $countFonts : $countFonts + 1;
$fontWriter = new Font($font);
$fontWriter->setColorIndex($this->addColor($font->getColor()->getRGB()));
$this->fontWriters[] = $fontWriter;
$this->addedFonts[$fontHashCode] = $fontIndex;
}
return $fontIndex;
}
/**
* Alter color palette adding a custom color.
*
* @param string $rgb E.g. 'FF00AA'
*
* @return int Color index
*/
public function addColor(string $rgb, int $default = 0): int
{
if (!isset($this->colors[$rgb])) {
$color
= [
(int) hexdec(substr($rgb, 0, 2)),
(int) hexdec(substr($rgb, 2, 2)),
(int) hexdec(substr($rgb, 4)),
0,
];
$colorIndex = array_search($color, $this->palette);
if ($colorIndex) {
$this->colors[$rgb] = $colorIndex;
} else {
if (count($this->colors) === 0) {
$lastColor = 7;
} else {
$lastColor = end($this->colors);
}
if ($lastColor < 57) {
// then we add a custom color altering the palette
$colorIndex = $lastColor + 1;
$this->palette[$colorIndex] = $color;
$this->colors[$rgb] = $colorIndex;
} else {
// no room for more custom colors, just map to black
$colorIndex = $default;
}
}
} else {
// fetch already added custom color
$colorIndex = $this->colors[$rgb];
}
return $colorIndex;
}
/**
* Sets the colour palette to the Excel 97+ default.
*/
private function setPaletteXl97(): void
{
$this->palette = [
0x08 => [0x00, 0x00, 0x00, 0x00],
0x09 => [0xFF, 0xFF, 0xFF, 0x00],
0x0A => [0xFF, 0x00, 0x00, 0x00],
0x0B => [0x00, 0xFF, 0x00, 0x00],
0x0C => [0x00, 0x00, 0xFF, 0x00],
0x0D => [0xFF, 0xFF, 0x00, 0x00],
0x0E => [0xFF, 0x00, 0xFF, 0x00],
0x0F => [0x00, 0xFF, 0xFF, 0x00],
0x10 => [0x80, 0x00, 0x00, 0x00],
0x11 => [0x00, 0x80, 0x00, 0x00],
0x12 => [0x00, 0x00, 0x80, 0x00],
0x13 => [0x80, 0x80, 0x00, 0x00],
0x14 => [0x80, 0x00, 0x80, 0x00],
0x15 => [0x00, 0x80, 0x80, 0x00],
0x16 => [0xC0, 0xC0, 0xC0, 0x00],
0x17 => [0x80, 0x80, 0x80, 0x00],
0x18 => [0x99, 0x99, 0xFF, 0x00],
0x19 => [0x99, 0x33, 0x66, 0x00],
0x1A => [0xFF, 0xFF, 0xCC, 0x00],
0x1B => [0xCC, 0xFF, 0xFF, 0x00],
0x1C => [0x66, 0x00, 0x66, 0x00],
0x1D => [0xFF, 0x80, 0x80, 0x00],
0x1E => [0x00, 0x66, 0xCC, 0x00],
0x1F => [0xCC, 0xCC, 0xFF, 0x00],
0x20 => [0x00, 0x00, 0x80, 0x00],
0x21 => [0xFF, 0x00, 0xFF, 0x00],
0x22 => [0xFF, 0xFF, 0x00, 0x00],
0x23 => [0x00, 0xFF, 0xFF, 0x00],
0x24 => [0x80, 0x00, 0x80, 0x00],
0x25 => [0x80, 0x00, 0x00, 0x00],
0x26 => [0x00, 0x80, 0x80, 0x00],
0x27 => [0x00, 0x00, 0xFF, 0x00],
0x28 => [0x00, 0xCC, 0xFF, 0x00],
0x29 => [0xCC, 0xFF, 0xFF, 0x00],
0x2A => [0xCC, 0xFF, 0xCC, 0x00],
0x2B => [0xFF, 0xFF, 0x99, 0x00],
0x2C => [0x99, 0xCC, 0xFF, 0x00],
0x2D => [0xFF, 0x99, 0xCC, 0x00],
0x2E => [0xCC, 0x99, 0xFF, 0x00],
0x2F => [0xFF, 0xCC, 0x99, 0x00],
0x30 => [0x33, 0x66, 0xFF, 0x00],
0x31 => [0x33, 0xCC, 0xCC, 0x00],
0x32 => [0x99, 0xCC, 0x00, 0x00],
0x33 => [0xFF, 0xCC, 0x00, 0x00],
0x34 => [0xFF, 0x99, 0x00, 0x00],
0x35 => [0xFF, 0x66, 0x00, 0x00],
0x36 => [0x66, 0x66, 0x99, 0x00],
0x37 => [0x96, 0x96, 0x96, 0x00],
0x38 => [0x00, 0x33, 0x66, 0x00],
0x39 => [0x33, 0x99, 0x66, 0x00],
0x3A => [0x00, 0x33, 0x00, 0x00],
0x3B => [0x33, 0x33, 0x00, 0x00],
0x3C => [0x99, 0x33, 0x00, 0x00],
0x3D => [0x99, 0x33, 0x66, 0x00],
0x3E => [0x33, 0x33, 0x99, 0x00],
0x3F => [0x33, 0x33, 0x33, 0x00],
];
}
/**
* Assemble worksheets into a workbook and send the BIFF data to an OLE
* storage.
*
* @param int[] $worksheetSizes The sizes in bytes of the binary worksheet streams
*
* @return string Binary data for workbook stream
*/
public function writeWorkbook(array $worksheetSizes): string
{
$this->worksheetSizes = $worksheetSizes;
// Calculate the number of selected worksheet tabs and call the finalization
// methods for each worksheet
$total_worksheets = $this->spreadsheet->getSheetCount();
// Add part 1 of the Workbook globals, what goes before the SHEET records
$this->storeBof(0x0005);
$this->writeCodepage();
$this->writeWindow1();
$this->writeDateMode();
$this->writeAllFonts();
$this->writeAllNumberFormats();
$this->writeAllXfs();
$this->writeAllStyles();
$this->writePalette();
// Prepare part 3 of the workbook global stream, what goes after the SHEET records
$part3 = '';
if ($this->countryCode !== -1) {
$part3 .= $this->writeCountry();
}
$part3 .= $this->writeRecalcId();
$part3 .= $this->writeSupbookInternal();
/* TODO: store external SUPBOOK records and XCT and CRN records
in case of external references for BIFF8 */
$part3 .= $this->writeExternalsheetBiff8();
$part3 .= $this->writeAllDefinedNamesBiff8();
$part3 .= $this->writeMsoDrawingGroup();
$part3 .= $this->writeSharedStringsTable();
$part3 .= $this->writeEof();
// Add part 2 of the Workbook globals, the SHEET records
$this->calcSheetOffsets();
for ($i = 0; $i < $total_worksheets; ++$i) {
$this->writeBoundSheet($this->spreadsheet->getSheet($i), $this->worksheetOffsets[$i]);
}
// Add part 3 of the Workbook globals
$this->_data .= $part3;
return $this->_data;
}
/**
* Calculate offsets for Worksheet BOF records.
*/
private function calcSheetOffsets(): void
{
$boundsheet_length = 10; // fixed length for a BOUNDSHEET record
// size of Workbook globals part 1 + 3
$offset = $this->_datasize;
// add size of Workbook globals part 2, the length of the SHEET records
$total_worksheets = count($this->spreadsheet->getAllSheets());
foreach ($this->spreadsheet->getWorksheetIterator() as $sheet) {
$offset += $boundsheet_length + strlen(StringHelper::UTF8toBIFF8UnicodeShort($sheet->getTitle()));
}
// add the sizes of each of the Sheet substreams, respectively
for ($i = 0; $i < $total_worksheets; ++$i) {
$this->worksheetOffsets[$i] = $offset;
$offset += $this->worksheetSizes[$i];
}
//$this->biffSize = $offset;
}
/**
* Store the Excel FONT records.
*/
private function writeAllFonts(): void
{
foreach ($this->fontWriters as $fontWriter) {
$this->append($fontWriter->writeFont());
}
}
/**
* Store user defined numerical formats i.e. FORMAT records.
*/
private function writeAllNumberFormats(): void
{
foreach ($this->numberFormats as $numberFormatIndex => $numberFormat) {
$this->writeNumberFormat((string) $numberFormat->getFormatCode(), $numberFormatIndex);
}
}
/**
* Write all XF records.
*/
private function writeAllXfs(): void
{
foreach ($this->xfWriters as $xfWriter) {
$this->append($xfWriter->writeXf());
}
}
/**
* Write all STYLE records.
*/
private function writeAllStyles(): void
{
$this->writeStyle();
}
private function parseDefinedNameValue(DefinedName $definedName): string
{
$definedRange = $definedName->getValue();
$splitCount = Preg::matchAllWithOffsets(
'/' . Calculation::CALCULATION_REGEXP_CELLREF . '/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
$worksheet = $definedName->getWorksheet()?->getTitle();
}
} else {
$worksheet = str_replace("''", "'", trim($worksheet, "'"));
}
if (!empty($worksheet)) {
$newRange = "'" . str_replace("'", "''", $worksheet) . "'!";
}
if (!empty($column)) {
$newRange .= "\${$column}";
}
if (!empty($row)) {
$newRange .= "\${$row}";
}
$definedRange = substr($definedRange, 0, $offset) . $newRange . substr($definedRange, $offset + $length);
}
return $definedRange;
}
/**
* Writes all the DEFINEDNAME records (BIFF8).
* So far this is only used for repeating rows/columns (print titles) and print areas.
*/
private function writeAllDefinedNamesBiff8(): string
{
$chunk = '';
// Named ranges
$definedNames = $this->spreadsheet->getDefinedNames();
if (count($definedNames) > 0) {
// Loop named ranges
foreach ($definedNames as $definedName) {
$range = $this->parseDefinedNameValue($definedName);
// parse formula
try {
$this->parser->parse($range);
$formulaData = $this->parser->toReversePolish();
// make sure tRef3d is of type tRef3dR (0x3A)
if (isset($formulaData[0]) && ($formulaData[0] == "\x7A" || $formulaData[0] == "\x5A")) {
$formulaData = "\x3A" . substr($formulaData, 1);
}
if ($definedName->getLocalOnly()) {
// local scope
$scopeWs = $definedName->getScope();
$scope = ($scopeWs === null) ? 0 : ($this->spreadsheet->getIndex($scopeWs) + 1);
} else {
// global scope
$scope = 0;
}
$chunk .= $this->writeData($this->writeDefinedNameBiff8($definedName->getName(), $formulaData, $scope, false));
} catch (PhpSpreadsheetException) {
// do nothing
}
}
}
// total number of sheets
$total_worksheets = $this->spreadsheet->getSheetCount();
// write the print titles (repeating rows, columns), if any
for ($i = 0; $i < $total_worksheets; ++$i) {
$sheetSetup = $this->spreadsheet->getSheet($i)->getPageSetup();
// simultaneous repeatColumns repeatRows
if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) {
$repeat = $sheetSetup->getColumnsToRepeatAtLeft();
$colmin = Coordinate::columnIndexFromString($repeat[0]) - 1;
$colmax = Coordinate::columnIndexFromString($repeat[1]) - 1;
$repeat = $sheetSetup->getRowsToRepeatAtTop();
$rowmin = $repeat[0] - 1;
$rowmax = $repeat[1] - 1;
// construct formula data manually
$formulaData = pack('Cv', 0x29, 0x17); // tMemFunc
$formulaData .= pack('Cvvvvv', 0x3B, $i, 0, 65535, $colmin, $colmax); // tArea3d
$formulaData .= pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, 0, 255); // tArea3d
$formulaData .= pack('C', 0x10); // tList
// store the DEFINEDNAME record
$chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true));
} elseif ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) {
// (exclusive) either repeatColumns or repeatRows.
// Columns to repeat
if ($sheetSetup->isColumnsToRepeatAtLeftSet()) {
$repeat = $sheetSetup->getColumnsToRepeatAtLeft();
$colmin = Coordinate::columnIndexFromString($repeat[0]) - 1;
$colmax = Coordinate::columnIndexFromString($repeat[1]) - 1;
} else {
$colmin = 0;
$colmax = 255;
}
// Rows to repeat
if ($sheetSetup->isRowsToRepeatAtTopSet()) {
$repeat = $sheetSetup->getRowsToRepeatAtTop();
$rowmin = $repeat[0] - 1;
$rowmax = $repeat[1] - 1;
} else {
$rowmin = 0;
$rowmax = 65535;
}
// construct formula data manually because parser does not recognize absolute 3d cell references
$formulaData = pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, $colmin, $colmax);
// store the DEFINEDNAME record
$chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true));
}
}
// write the print areas, if any
for ($i = 0; $i < $total_worksheets; ++$i) {
$sheetSetup = $this->spreadsheet->getSheet($i)->getPageSetup();
if ($sheetSetup->isPrintAreaSet()) {
// Print area, e.g. A3:J6,H1:X20
$printArea = Coordinate::splitRange($sheetSetup->getPrintArea());
$countPrintArea = count($printArea);
$formulaData = '';
for ($j = 0; $j < $countPrintArea; ++$j) {
$printAreaRect = $printArea[$j]; // e.g. A3:J6
$printAreaRect[0] = Coordinate::indexesFromString($printAreaRect[0]);
/** @var string */
$printAreaRect1 = $printAreaRect[1];
$printAreaRect[1] = Coordinate::indexesFromString($printAreaRect1);
$print_rowmin = $printAreaRect[0][1] - 1;
$print_rowmax = $printAreaRect[1][1] - 1;
$print_colmin = $printAreaRect[0][0] - 1;
$print_colmax = $printAreaRect[1][0] - 1;
// construct formula data manually because parser does not recognize absolute 3d cell references
$formulaData .= pack('Cvvvvv', 0x3B, $i, $print_rowmin, $print_rowmax, $print_colmin, $print_colmax);
if ($j > 0) {
$formulaData .= pack('C', 0x10); // list operator token ','
}
}
// store the DEFINEDNAME record
$chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x06), $formulaData, $i + 1, true));
}
}
// write autofilters, if any
for ($i = 0; $i < $total_worksheets; ++$i) {
$sheetAutoFilter = $this->spreadsheet->getSheet($i)->getAutoFilter();
$autoFilterRange = $sheetAutoFilter->getRange();
if (!empty($autoFilterRange)) {
$rangeBounds = Coordinate::rangeBoundaries($autoFilterRange);
//Autofilter built in name
$name = pack('C', 0x0D);
$chunk .= $this->writeData($this->writeShortNameBiff8($name, $i + 1, $rangeBounds, true));
}
}
return $chunk;
}
/**
* Write a DEFINEDNAME record for BIFF8 using explicit binary formula data.
*
* @param string $name The name in UTF-8
* @param string $formulaData The binary formula data
* @param int $sheetIndex 1-based sheet index the defined name applies to. 0 = global
* @param bool $isBuiltIn Built-in name?
*
* @return string Complete binary record data
*/
private function writeDefinedNameBiff8(string $name, string $formulaData, int $sheetIndex = 0, bool $isBuiltIn = false): string
{
$record = 0x0018;
// option flags
$options = $isBuiltIn ? 0x20 : 0x00;
// length of the name, character count
$nlen = StringHelper::countCharacters($name);
// name with stripped length field
$name = substr(StringHelper::UTF8toBIFF8UnicodeLong($name), 2);
// size of the formula (in bytes)
$sz = strlen($formulaData);
// combine the parts
$data = pack('vCCvvvCCCC', $options, 0, $nlen, $sz, 0, $sheetIndex, 0, 0, 0, 0)
. $name . $formulaData;
$length = strlen($data);
$header = pack('vv', $record, $length);
return $header . $data;
}
/**
* Write a short NAME record.
*
* @param int $sheetIndex 1-based sheet index the defined name applies to. 0 = global
* @param int[][] $rangeBounds range boundaries
*
* @return string Complete binary record data
* */
private function writeShortNameBiff8(string $name, int $sheetIndex, array $rangeBounds, bool $isHidden = false): string
{
$record = 0x0018;
// option flags
$options = ($isHidden ? 0x21 : 0x00);
$extra = pack(
'Cvvvvv',
0x3B,
$sheetIndex - 1,
$rangeBounds[0][1] - 1,
$rangeBounds[1][1] - 1,
$rangeBounds[0][0] - 1,
$rangeBounds[1][0] - 1
);
// size of the formula (in bytes)
$sz = strlen($extra);
// combine the parts
$data = pack('vCCvvvCCCCC', $options, 0, 1, $sz, 0, $sheetIndex, 0, 0, 0, 0, 0)
. $name . $extra;
$length = strlen($data);
$header = pack('vv', $record, $length);
return $header . $data;
}
/**
* Stores the CODEPAGE biff record.
*/
private function writeCodepage(): void
{
$record = 0x0042; // Record identifier
$length = 0x0002; // Number of bytes to follow
$cv = $this->codepage; // The code page
$header = pack('vv', $record, $length);
$data = pack('v', $cv);
$this->append($header . $data);
}
/**
* Write Excel BIFF WINDOW1 record.
*/
private function writeWindow1(): void
{
$record = 0x003D; // Record identifier
$length = 0x0012; // Number of bytes to follow
$xWn = 0x0000; // Horizontal position of window
$yWn = 0x0000; // Vertical position of window
$dxWn = 0x25BC; // Width of window
$dyWn = 0x1572; // Height of window
$grbit = 0x0038; // Option flags
// not supported by PhpSpreadsheet, so there is only one selected sheet, the active
$ctabsel = 1; // Number of workbook tabs selected
$wTabRatio = 0x0258; // Tab to scrollbar ratio
// not supported by PhpSpreadsheet, set to 0
$itabFirst = 0; // 1st displayed worksheet
$itabCur = $this->spreadsheet->getActiveSheetIndex(); // Active worksheet
$header = pack('vv', $record, $length);
$data = pack('vvvvvvvvv', $xWn, $yWn, $dxWn, $dyWn, $grbit, $itabCur, $itabFirst, $ctabsel, $wTabRatio);
$this->append($header . $data);
}
/**
* Writes Excel BIFF BOUNDSHEET record.
*
* @param int $offset Location of worksheet BOF
*/
private function writeBoundSheet(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet, int $offset): void
{
$sheetname = $sheet->getTitle();
$record = 0x0085; // Record identifier
$ss = match ($sheet->getSheetState()) {
\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VISIBLE => 0x00,
\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_HIDDEN => 0x01,
\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VERYHIDDEN => 0x02,
default => 0x00,
};
// sheet type
$st = 0x00;
//$grbit = 0x0000; // Visibility and sheet type
$data = pack('VCC', $offset, $ss, $st);
$data .= StringHelper::UTF8toBIFF8UnicodeShort($sheetname);
$length = strlen($data);
$header = pack('vv', $record, $length);
$this->append($header . $data);
}
/**
* Write Internal SUPBOOK record.
*/
private function writeSupbookInternal(): string
{
$record = 0x01AE; // Record identifier
$length = 0x0004; // Bytes to follow
$header = pack('vv', $record, $length);
$data = pack('vv', $this->spreadsheet->getSheetCount(), 0x0401);
return $this->writeData($header . $data);
}
/**
* Writes the Excel BIFF EXTERNSHEET record. These references are used by
* formulas.
*/
private function writeExternalsheetBiff8(): string
{
$totalReferences = count($this->parser->references);
$record = 0x0017; // Record identifier
$length = 2 + 6 * $totalReferences; // Number of bytes to follow
//$supbook_index = 0; // FIXME: only using internal SUPBOOK record
$header = pack('vv', $record, $length);
$data = pack('v', $totalReferences);
for ($i = 0; $i < $totalReferences; ++$i) {
$data .= $this->parser->references[$i];
}
return $this->writeData($header . $data);
}
/**
* Write Excel BIFF STYLE records.
*/
private function writeStyle(): void
{
$record = 0x0293; // Record identifier
$length = 0x0004; // Bytes to follow
$ixfe = 0x8000; // Index to cell style XF
$BuiltIn = 0x00; // Built-in style
$iLevel = 0xFF; // Outline style level
$header = pack('vv', $record, $length);
$data = pack('vCC', $ixfe, $BuiltIn, $iLevel);
$this->append($header . $data);
}
/**
* Writes Excel FORMAT record for non "built-in" numerical formats.
*
* @param string $format Custom format string
* @param int $ifmt Format index code
*/
private function writeNumberFormat(string $format, int $ifmt): void
{
$record = 0x041E; // Record identifier
$numberFormatString = StringHelper::UTF8toBIFF8UnicodeLong($format);
$length = 2 + strlen($numberFormatString); // Number of bytes to follow
$header = pack('vv', $record, $length);
$data = pack('v', $ifmt) . $numberFormatString;
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | true |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls/Font.php | src/PhpSpreadsheet/Writer/Xls/Font.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
class Font
{
/**
* Color index.
*/
private int $colorIndex;
/**
* Font.
*/
private \PhpOffice\PhpSpreadsheet\Style\Font $font;
/**
* Constructor.
*/
public function __construct(\PhpOffice\PhpSpreadsheet\Style\Font $font)
{
$this->colorIndex = 0x7FFF;
$this->font = $font;
}
/**
* Set the color index.
*/
public function setColorIndex(int $colorIndex): void
{
$this->colorIndex = $colorIndex;
}
private static int $notImplemented = 0;
/**
* Get font record data.
*/
public function writeFont(): string
{
$font_outline = self::$notImplemented;
$font_shadow = self::$notImplemented;
$icv = $this->colorIndex; // Index to color palette
if ($this->font->getSuperscript()) {
$sss = 1;
} elseif ($this->font->getSubscript()) {
$sss = 2;
} else {
$sss = 0;
}
$bFamily = 0; // Font family
$bCharSet = \PhpOffice\PhpSpreadsheet\Shared\Font::getCharsetFromFontName((string) $this->font->getName()); // Character set
$record = 0x31; // Record identifier
$reserved = 0x00; // Reserved
$grbit = 0x00; // Font attributes
if ($this->font->getItalic()) {
$grbit |= 0x02;
}
if ($this->font->getStrikethrough()) {
$grbit |= 0x08;
}
if ($font_outline) {
$grbit |= 0x10;
}
if ($font_shadow) {
$grbit |= 0x20;
}
$data = pack(
'vvvvvCCCC',
// Fontsize (in twips)
$this->font->getSize() * 20,
$grbit,
// Colour
$icv,
// Font weight
self::mapBold($this->font->getBold()),
// Superscript/Subscript
$sss,
self::mapUnderline((string) $this->font->getUnderline()),
$bFamily,
$bCharSet,
$reserved
);
$data .= StringHelper::UTF8toBIFF8UnicodeShort((string) $this->font->getName());
$length = strlen($data);
$header = pack('vv', $record, $length);
return $header . $data;
}
/**
* Map to BIFF5-BIFF8 codes for bold.
*/
private static function mapBold(?bool $bold): int
{
if ($bold === true) {
return 0x2BC; // 700 = Bold font weight
}
return 0x190; // 400 = Normal font weight
}
/**
* Map of BIFF2-BIFF8 codes for underline styles.
*
* @var int[]
*/
private static array $mapUnderline = [
\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_NONE => 0x00,
\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE => 0x01,
\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE => 0x02,
\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING => 0x21,
\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLEACCOUNTING => 0x22,
];
/**
* Map underline.
*/
private static function mapUnderline(string $underline): int
{
if (isset(self::$mapUnderline[$underline])) {
return self::$mapUnderline[$underline];
}
return 0x00;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls/Escher.php | src/PhpSpreadsheet/Writer/Xls/Escher.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Shared\Escher as SharedEscher;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE;
use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE\Blip;
class Escher
{
/**
* The object we are writing.
*/
private Blip|BSE|BstoreContainer|DgContainer|DggContainer|Escher|SpContainer|SpgrContainer|SharedEscher $object;
/**
* The written binary data.
*/
private string $data;
/**
* Shape offsets. Positions in binary stream where a new shape record begins.
*
* @var int[]
*/
private array $spOffsets;
/**
* Shape types.
*
* @var mixed[]
*/
private array $spTypes;
/**
* Constructor.
*/
public function __construct(Blip|BSE|BstoreContainer|DgContainer|DggContainer|self|SpContainer|SpgrContainer|SharedEscher $object)
{
$this->object = $object;
}
/**
* Process the object to be written.
*/
public function close(): string
{
// initialize
$this->data = '';
switch ($this->object::class) {
case SharedEscher::class:
if ($dggContainer = $this->object->getDggContainer()) {
$writer = new self($dggContainer);
$this->data = $writer->close();
} elseif ($dgContainer = $this->object->getDgContainer()) {
$writer = new self($dgContainer);
$this->data = $writer->close();
$this->spOffsets = $writer->getSpOffsets();
$this->spTypes = $writer->getSpTypes();
}
break;
case DggContainer::class:
// this is a container record
// initialize
$innerData = '';
// write the dgg
$recVer = 0x0;
$recInstance = 0x0000;
$recType = 0xF006;
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
// dgg data
$dggData
= pack(
'VVVV',
$this->object->getSpIdMax(), // maximum shape identifier increased by one
$this->object->getCDgSaved() + 1, // number of file identifier clusters increased by one
$this->object->getCSpSaved(),
$this->object->getCDgSaved() // count total number of drawings saved
);
// add file identifier clusters (one per drawing)
$IDCLs = $this->object->getIDCLs();
foreach ($IDCLs as $dgId => $maxReducedSpId) {
/** @var int $maxReducedSpId */
$dggData .= pack('VV', $dgId, $maxReducedSpId + 1);
}
$header = pack('vvV', $recVerInstance, $recType, strlen($dggData));
$innerData .= $header . $dggData;
// write the bstoreContainer
if ($bstoreContainer = $this->object->getBstoreContainer()) {
$writer = new self($bstoreContainer);
$innerData .= $writer->close();
}
// write the record
$recVer = 0xF;
$recInstance = 0x0000;
$recType = 0xF000;
$length = strlen($innerData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header . $innerData;
break;
case BstoreContainer::class:
// this is a container record
// initialize
$innerData = '';
// treat the inner data
if ($BSECollection = $this->object->getBSECollection()) {
foreach ($BSECollection as $BSE) {
$writer = new self($BSE);
$innerData .= $writer->close();
}
}
// write the record
$recVer = 0xF;
$recInstance = count($this->object->getBSECollection());
$recType = 0xF001;
$length = strlen($innerData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header . $innerData;
break;
case BSE::class:
// this is a semi-container record
// initialize
$innerData = '';
// here we treat the inner data
if ($blip = $this->object->getBlip()) {
$writer = new self($blip);
$innerData .= $writer->close();
}
// initialize
$data = '';
$btWin32 = $this->object->getBlipType();
$btMacOS = $this->object->getBlipType();
$data .= pack('CC', $btWin32, $btMacOS);
$rgbUid = pack('VVVV', 0, 0, 0, 0); // todo
$data .= $rgbUid;
$tag = 0;
$size = strlen($innerData);
$cRef = 1;
$foDelay = 0; //todo
$unused1 = 0x0;
$cbName = 0x0;
$unused2 = 0x0;
$unused3 = 0x0;
$data .= pack('vVVVCCCC', $tag, $size, $cRef, $foDelay, $unused1, $cbName, $unused2, $unused3);
$data .= $innerData;
// write the record
$recVer = 0x2;
$recInstance = $this->object->getBlipType();
$recType = 0xF007;
$length = strlen($data);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header;
$this->data .= $data;
break;
case Blip::class:
// this is an atom record
// write the record
switch ($this->object->getParent()->getBlipType()) {
case BSE::BLIPTYPE_JPEG:
// initialize
$innerData = '';
$rgbUid1 = pack('VVVV', 0, 0, 0, 0); // todo
$innerData .= $rgbUid1;
$tag = 0xFF; // todo
$innerData .= pack('C', $tag);
$innerData .= $this->object->getData();
$recVer = 0x0;
$recInstance = 0x46A;
$recType = 0xF01D;
$length = strlen($innerData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header;
$this->data .= $innerData;
break;
case BSE::BLIPTYPE_PNG:
// initialize
$innerData = '';
$rgbUid1 = pack('VVVV', 0, 0, 0, 0); // todo
$innerData .= $rgbUid1;
$tag = 0xFF; // todo
$innerData .= pack('C', $tag);
$innerData .= $this->object->getData();
$recVer = 0x0;
$recInstance = 0x6E0;
$recType = 0xF01E;
$length = strlen($innerData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header;
$this->data .= $innerData;
break;
}
break;
case DgContainer::class:
// this is a container record
// initialize
$innerData = '';
// write the dg
$recVer = 0x0;
$recInstance = $this->object->getDgId();
$recType = 0xF008;
$length = 8;
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
// number of shapes in this drawing (including group shape)
$countShapes = count($this->object->getSpgrContainerOrThrow()->getChildren());
$innerData .= $header . pack('VV', $countShapes, $this->object->getLastSpId());
// write the spgrContainer
if ($spgrContainer = $this->object->getSpgrContainer()) {
$writer = new self($spgrContainer);
$innerData .= $writer->close();
// get the shape offsets relative to the spgrContainer record
$spOffsets = $writer->getSpOffsets();
$spTypes = $writer->getSpTypes();
// save the shape offsets relative to dgContainer
foreach ($spOffsets as &$spOffset) {
$spOffset += 24; // add length of dgContainer header data (8 bytes) plus dg data (16 bytes)
}
$this->spOffsets = $spOffsets;
$this->spTypes = $spTypes;
}
// write the record
$recVer = 0xF;
$recInstance = 0x0000;
$recType = 0xF002;
$length = strlen($innerData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header . $innerData;
break;
case SpgrContainer::class:
// this is a container record
// initialize
$innerData = '';
// initialize spape offsets
$totalSize = 8;
$spOffsets = [];
$spTypes = [];
// treat the inner data
foreach ($this->object->getChildren() as $spContainer) {
/** @var Blip|BSE|BstoreContainer|DgContainer|DggContainer|SharedEscher|SpContainer|SpgrContainer $spContainer */
$writer = new self($spContainer);
$spData = $writer->close();
$innerData .= $spData;
// save the shape offsets (where new shape records begin)
$totalSize += strlen($spData);
$spOffsets[] = $totalSize;
$spTypes = array_merge($spTypes, $writer->getSpTypes());
}
// write the record
$recVer = 0xF;
$recInstance = 0x0000;
$recType = 0xF003;
$length = strlen($innerData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header . $innerData;
$this->spOffsets = $spOffsets;
$this->spTypes = $spTypes;
break;
case SpContainer::class:
// initialize
$data = '';
// build the data
// write group shape record, if necessary?
if ($this->object->getSpgr()) {
$recVer = 0x1;
$recInstance = 0x0000;
$recType = 0xF009;
$length = 0x00000010;
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$data .= $header . pack('VVVV', 0, 0, 0, 0);
}
$this->spTypes[] = ($this->object->getSpType());
// write the shape record
$recVer = 0x2;
$recInstance = $this->object->getSpType(); // shape type
$recType = 0xF00A;
$length = 0x00000008;
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$data .= $header . pack('VV', $this->object->getSpId(), $this->object->getSpgr() ? 0x0005 : 0x0A00);
// the options
if ($this->object->getOPTCollection()) {
$optData = '';
$recVer = 0x3;
$recInstance = count($this->object->getOPTCollection());
$recType = 0xF00B;
foreach ($this->object->getOPTCollection() as $property => $value) {
$optData .= pack('vV', $property, $value);
}
$length = strlen($optData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$data .= $header . $optData;
}
// the client anchor
if ($this->object->getStartCoordinates()) {
$recVer = 0x0;
$recInstance = 0x0;
$recType = 0xF010;
// start coordinates
[$column, $row] = Coordinate::indexesFromString($this->object->getStartCoordinates());
$c1 = $column - 1;
$r1 = $row - 1;
// start offsetX
$startOffsetX = $this->object->getStartOffsetX();
// start offsetY
$startOffsetY = $this->object->getStartOffsetY();
// end coordinates
[$column, $row] = Coordinate::indexesFromString($this->object->getEndCoordinates());
$c2 = $column - 1;
$r2 = $row - 1;
// end offsetX
$endOffsetX = $this->object->getEndOffsetX();
// end offsetY
$endOffsetY = $this->object->getEndOffsetY();
$clientAnchorData = pack('vvvvvvvvv', $this->object->getSpFlag(), $c1, $startOffsetX, $r1, $startOffsetY, $c2, $endOffsetX, $r2, $endOffsetY);
$length = strlen($clientAnchorData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$data .= $header . $clientAnchorData;
}
// the client data, just empty for now
if (!$this->object->getSpgr()) {
$clientDataData = '';
$recVer = 0x0;
$recInstance = 0x0;
$recType = 0xF011;
$length = strlen($clientDataData);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$data .= $header . $clientDataData;
}
// write the record
$recVer = 0xF;
$recInstance = 0x0000;
$recType = 0xF004;
$length = strlen($data);
$recVerInstance = $recVer;
$recVerInstance |= $recInstance << 4;
$header = pack('vvV', $recVerInstance, $recType, $length);
$this->data = $header . $data;
break;
}
return $this->data;
}
/**
* Gets the shape offsets.
*
* @return int[]
*/
public function getSpOffsets(): array
{
return $this->spOffsets;
}
/**
* Gets the shape types.
*
* @return mixed[]
*/
public function getSpTypes(): array
{
return $this->spTypes;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls/Xf.php | src/PhpSpreadsheet/Writer/Xls/Xf.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Borders;
use PhpOffice\PhpSpreadsheet\Style\Protection;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellAlignment;
use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellBorder;
use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellFill;
// Original file header of PEAR::Spreadsheet_Excel_Writer_Format (used as the base for this class):
// -----------------------------------------------------------------------------------------
// /*
// * Module written/ported by Xavier Noguer <xnoguer@rezebra.com>
// *
// * The majority of this is _NOT_ my code. I simply ported it from the
// * PERL Spreadsheet::WriteExcel module.
// *
// * The author of the Spreadsheet::WriteExcel module is John McNamara
// * <jmcnamara@cpan.org>
// *
// * I _DO_ maintain this code, and John McNamara has nothing to do with the
// * porting of this code to PHP. Any questions directly related to this
// * class library should be directed to me.
// *
// * License Information:
// *
// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets
// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com
// *
// * This library is free software; you can redistribute it and/or
// * modify it under the terms of the GNU Lesser General Public
// * License as published by the Free Software Foundation; either
// * version 2.1 of the License, or (at your option) any later version.
// *
// * This library is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// * Lesser General Public License for more details.
// *
// * You should have received a copy of the GNU Lesser General Public
// * License along with this library; if not, write to the Free Software
// * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// */
class Xf
{
/**
* Style XF or a cell XF ?
*/
private bool $isStyleXf;
/**
* Index to the FONT record. Index 4 does not exist.
*/
private int $fontIndex;
/**
* An index (2 bytes) to a FORMAT record (number format).
*/
private int $numberFormatIndex;
/**
* 1 bit, apparently not used.
*/
private int $textJustLast;
/**
* The cell's foreground color.
*/
private int $foregroundColor;
/**
* The cell's background color.
*/
private int $backgroundColor;
/**
* Color of the bottom border of the cell.
*/
private int $bottomBorderColor;
/**
* Color of the top border of the cell.
*/
private int $topBorderColor;
/**
* Color of the left border of the cell.
*/
private int $leftBorderColor;
/**
* Color of the right border of the cell.
*/
private int $rightBorderColor;
//private $diag; // theoretically int, not yet implemented
private int $diagColor;
private Style $style;
/**
* Constructor.
*
* @param Style $style The XF format
*/
public function __construct(Style $style)
{
$this->isStyleXf = false;
$this->fontIndex = 0;
$this->numberFormatIndex = 0;
$this->textJustLast = 0;
$this->foregroundColor = 0x40;
$this->backgroundColor = 0x41;
//$this->diag = 0;
$this->bottomBorderColor = 0x40;
$this->topBorderColor = 0x40;
$this->leftBorderColor = 0x40;
$this->rightBorderColor = 0x40;
$this->diagColor = 0x40;
$this->style = $style;
}
/**
* Generate an Excel BIFF XF record (style or cell).
*
* @return string The XF record
*/
public function writeXf(): string
{
// Set the type of the XF record and some of the attributes.
if ($this->isStyleXf) {
$style = 0xFFF5;
} else {
$style = self::mapLocked($this->style->getProtection()->getLocked());
$style |= self::mapHidden($this->style->getProtection()->getHidden()) << 1;
}
// Flags to indicate if attributes have been set.
$atr_num = ($this->numberFormatIndex != 0) ? 1 : 0;
$atr_fnt = ($this->fontIndex != 0) ? 1 : 0;
$atr_alc = ((int) $this->style->getAlignment()->getWrapText()) ? 1 : 0;
$atr_bdr = (CellBorder::style($this->style->getBorders()->getBottom())
|| CellBorder::style($this->style->getBorders()->getTop())
|| CellBorder::style($this->style->getBorders()->getLeft())
|| CellBorder::style($this->style->getBorders()->getRight())) ? 1 : 0;
$atr_pat = ($this->foregroundColor != 0x40) ? 1 : 0;
$atr_pat = ($this->backgroundColor != 0x41) ? 1 : $atr_pat;
$atr_pat = CellFill::style($this->style->getFill()) ? 1 : $atr_pat;
$atr_prot = self::mapLocked($this->style->getProtection()->getLocked())
| self::mapHidden($this->style->getProtection()->getHidden());
// Zero the default border colour if the border has not been set.
if (CellBorder::style($this->style->getBorders()->getBottom()) == 0) {
$this->bottomBorderColor = 0;
}
if (CellBorder::style($this->style->getBorders()->getTop()) == 0) {
$this->topBorderColor = 0;
}
if (CellBorder::style($this->style->getBorders()->getRight()) == 0) {
$this->rightBorderColor = 0;
}
if (CellBorder::style($this->style->getBorders()->getLeft()) == 0) {
$this->leftBorderColor = 0;
}
if (CellBorder::style($this->style->getBorders()->getDiagonal()) == 0) {
$this->diagColor = 0;
}
$record = 0x00E0; // Record identifier
$length = 0x0014; // Number of bytes to follow
$ifnt = $this->fontIndex; // Index to FONT record
$ifmt = $this->numberFormatIndex; // Index to FORMAT record
// Alignment
$align = CellAlignment::horizontal($this->style->getAlignment());
$align |= CellAlignment::wrap($this->style->getAlignment()) << 3;
$align |= CellAlignment::vertical($this->style->getAlignment()) << 4;
$align |= $this->textJustLast << 7;
$used_attrib = $atr_num << 2;
$used_attrib |= $atr_fnt << 3;
$used_attrib |= $atr_alc << 4;
$used_attrib |= $atr_bdr << 5;
$used_attrib |= $atr_pat << 6;
$used_attrib |= $atr_prot << 7;
$icv = $this->foregroundColor; // fg and bg pattern colors
$icv |= $this->backgroundColor << 7;
$border1 = CellBorder::style($this->style->getBorders()->getLeft()); // Border line style and color
$border1 |= CellBorder::style($this->style->getBorders()->getRight()) << 4;
$border1 |= CellBorder::style($this->style->getBorders()->getTop()) << 8;
$border1 |= CellBorder::style($this->style->getBorders()->getBottom()) << 12;
$border1 |= $this->leftBorderColor << 16;
$border1 |= $this->rightBorderColor << 23;
$diagonalDirection = $this->style->getBorders()->getDiagonalDirection();
$diag_tl_to_rb = $diagonalDirection == Borders::DIAGONAL_BOTH
|| $diagonalDirection == Borders::DIAGONAL_DOWN;
$diag_tr_to_lb = $diagonalDirection == Borders::DIAGONAL_BOTH
|| $diagonalDirection == Borders::DIAGONAL_UP;
$border1 |= $diag_tl_to_rb << 30;
$border1 |= $diag_tr_to_lb << 31;
$border2 = $this->topBorderColor; // Border color
$border2 |= $this->bottomBorderColor << 7;
$border2 |= $this->diagColor << 14;
$border2 |= CellBorder::style($this->style->getBorders()->getDiagonal()) << 21;
$border2 |= CellFill::style($this->style->getFill()) << 26;
$header = pack('vv', $record, $length);
//BIFF8 options: indentation, shrinkToFit and text direction
$biff8_options = $this->style->getAlignment()->getIndent() & 15;
$biff8_options |= (int) $this->style->getAlignment()->getShrinkToFit() << 4;
$biff8_options |= $this->style->getAlignment()->getReadOrder() << 6;
$data = pack('vvvC', $ifnt, $ifmt, $style, $align);
$data .= pack('CCC', self::mapTextRotation((int) $this->style->getAlignment()->getTextRotation()), $biff8_options, $used_attrib);
$data .= pack('VVv', $border1, $border2, $icv);
return $header . $data;
}
/**
* Is this a style XF ?
*/
public function setIsStyleXf(bool $value): void
{
$this->isStyleXf = $value;
}
/**
* Sets the cell's bottom border color.
*
* @param int $colorIndex Color index
*/
public function setBottomColor(int $colorIndex): void
{
$this->bottomBorderColor = $colorIndex;
}
/**
* Sets the cell's top border color.
*
* @param int $colorIndex Color index
*/
public function setTopColor(int $colorIndex): void
{
$this->topBorderColor = $colorIndex;
}
/**
* Sets the cell's left border color.
*
* @param int $colorIndex Color index
*/
public function setLeftColor(int $colorIndex): void
{
$this->leftBorderColor = $colorIndex;
}
/**
* Sets the cell's right border color.
*
* @param int $colorIndex Color index
*/
public function setRightColor(int $colorIndex): void
{
$this->rightBorderColor = $colorIndex;
}
/**
* Sets the cell's diagonal border color.
*
* @param int $colorIndex Color index
*/
public function setDiagColor(int $colorIndex): void
{
$this->diagColor = $colorIndex;
}
/**
* Sets the cell's foreground color.
*
* @param int $colorIndex Color index
*/
public function setFgColor(int $colorIndex): void
{
$this->foregroundColor = $colorIndex;
}
/**
* Sets the cell's background color.
*
* @param int $colorIndex Color index
*/
public function setBgColor(int $colorIndex): void
{
$this->backgroundColor = $colorIndex;
}
/**
* Sets the index to the number format record
* It can be date, time, currency, etc...
*
* @param int $numberFormatIndex Index to format record
*/
public function setNumberFormatIndex(int $numberFormatIndex): void
{
$this->numberFormatIndex = $numberFormatIndex;
}
/**
* Set the font index.
*
* @param int $value Font index, note that value 4 does not exist
*/
public function setFontIndex(int $value): void
{
$this->fontIndex = $value;
}
/**
* Map to BIFF8 codes for text rotation angle.
*/
private static function mapTextRotation(int $textRotation): int
{
if ($textRotation >= 0) {
return $textRotation;
}
if ($textRotation == Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) {
return Alignment::TEXTROTATION_STACK_EXCEL;
}
return 90 - $textRotation;
}
private const LOCK_ARRAY = [
Protection::PROTECTION_INHERIT => 1,
Protection::PROTECTION_PROTECTED => 1,
Protection::PROTECTION_UNPROTECTED => 0,
];
/**
* Map locked values.
*/
private static function mapLocked(?string $locked): int
{
return $locked !== null && array_key_exists($locked, self::LOCK_ARRAY) ? self::LOCK_ARRAY[$locked] : 1;
}
private const HIDDEN_ARRAY = [
Protection::PROTECTION_INHERIT => 0,
Protection::PROTECTION_PROTECTED => 1,
Protection::PROTECTION_UNPROTECTED => 0,
];
/**
* Map hidden.
*/
private static function mapHidden(?string $hidden): int
{
return $hidden !== null && array_key_exists($hidden, self::HIDDEN_ARRAY) ? self::HIDDEN_ARRAY[$hidden] : 0;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Writer/Xls/ConditionalHelper.php | src/PhpSpreadsheet/Writer/Xls/ConditionalHelper.php | <?php
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard;
class ConditionalHelper
{
/**
* Formula parser.
*/
protected Parser $parser;
protected mixed $condition;
protected string $cellRange;
protected ?string $tokens = null;
protected int $size;
public function __construct(Parser $parser)
{
$this->parser = $parser;
}
public function processCondition(mixed $condition, string $cellRange): void
{
$this->condition = $condition;
$this->cellRange = $cellRange;
if (is_int($condition) && $condition >= 0 && $condition <= 65535) {
$this->size = 3;
$this->tokens = pack('Cv', 0x1E, $condition);
} else {
try {
$formula = Wizard\WizardAbstract::reverseAdjustCellRef(StringHelper::convertToString($condition), $cellRange);
$this->parser->parse($formula);
$this->tokens = $this->parser->toReversePolish();
$this->size = strlen($this->tokens ?? '');
} catch (PhpSpreadsheetException) {
// In the event of a parser error with a formula value, we set the expression to ptgInt + 0
$this->tokens = pack('Cv', 0x1E, 0);
$this->size = 3;
}
}
}
public function tokens(): ?string
{
return $this->tokens;
}
public function size(): int
{
return $this->size;
}
}
| 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.