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/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/FindTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/FindTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\Attributes\DataProvider;
class FindTest extends AllSetupTeardown
{
#[DataProvider('providerFIND')]
public function testFIND(mixed $expectedResult, mixed $string1 = 'omitted', mixed $string2 = 'omitted', mixed $start = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($string1 === 'omitted') {
$sheet->getCell('B1')->setValue('=FIND()');
} elseif ($string2 === 'omitted') {
$this->setCell('A1', $string1);
$sheet->getCell('B1')->setValue('=FIND(A1)');
} elseif ($start === 'omitted') {
$this->setCell('A1', $string1);
$this->setCell('A2', $string2);
$sheet->getCell('B1')->setValue('=FIND(A1, A2)');
} else {
$this->setCell('A1', $string1);
$this->setCell('A2', $string2);
$this->setCell('A3', $start);
$sheet->getCell('B1')->setValue('=FIND(A1, A2, A3)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerFIND(): array
{
return require 'tests/data/Calculation/TextData/FIND.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerFindArray')]
public function testFindArray(array $expectedResult, string $argument1, string $argument2): void
{
$calculation = Calculation::getInstance();
$formula = "=FIND({$argument1}, {$argument2})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerFindArray(): array
{
return [
'row vector #1' => [[[3, 4, '#VALUE!']], '"l"', '{"Hello", "World", "PhpSpreadsheet"}'],
'column vector #1' => [[[3], [4], ['#VALUE!']], '"l"', '{"Hello"; "World"; "PhpSpreadsheet"}'],
'matrix #1' => [[[3, 4], ['#VALUE!', 5]], '"l"', '{"Hello", "World"; "PhpSpreadsheet", "Excel"}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ValueToTextTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ValueToTextTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\TextData\Format;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
class ValueToTextTest extends AllSetupTeardown
{
#[\PHPUnit\Framework\Attributes\DataProvider('providerVALUE')]
public function testVALUETOTEXT(mixed $expectedResult, mixed $value, int|string $format): void
{
$sheet = $this->getSheet();
$this->setCell('A1', $value);
$sheet->getCell('B1')->setValue("=VALUETOTEXT(A1, {$format})");
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertSame($expectedResult, $result);
}
public static function providerVALUE(): array
{
return require 'tests/data/Calculation/TextData/VALUETOTEXT.php';
}
// In Spreadsheet context, never see cell value as RichText.
// It will use calculatedValue, which is a string.
// Add an additional test for that condition.
public function testRichText(): void
{
$richText1 = new RichText();
$richText1->createTextRun('Hello');
$richText1->createText(' World');
self::assertSame('Hello World', Format::valueToText($richText1, 0));
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\Attributes\DataProvider;
class TTest extends AllSetupTeardown
{
/** @param mixed[] $expectedResult */
#[DataProvider('providerT')]
public function testT(mixed $expectedResult, mixed $value = 'no arguments'): void
{
$this->mightHaveException($expectedResult);
if ($value === 'no arguments') {
$this->setCell('H1', '=T()');
} else {
$this->setCell('A1', $value);
$this->setCell('H1', '=T(A1)');
}
$result = $this->getSheet()->getCell('H1')->getCalculatedValue();
self::assertSame($expectedResult, $result);
}
public static function providerT(): array
{
return require 'tests/data/Calculation/TextData/T.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerTArray')]
public function testTArray(array $expectedResult, string $argument): void
{
$calculation = Calculation::getInstance();
$formula = "=T({$argument})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerTArray(): array
{
return [
'row vector #1' => [[['PHP', '', 'PHP8']], '{"PHP", 99, "PHP8"}'],
'column vector #1' => [[[''], ['PHP'], ['']], '{12; "PHP"; 1.2}'],
'matrix #1' => [[['TRUE', 'FALSE'], ['', '']], '{"TRUE", "FALSE"; TRUE, FALSE}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ReplaceTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ReplaceTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\Attributes\DataProvider;
class ReplaceTest extends AllSetupTeardown
{
#[DataProvider('providerREPLACE')]
public function testREPLACE(mixed $expectedResult, mixed $oldText = 'omitted', mixed $start = 'omitted', mixed $count = 'omitted', mixed $newText = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($oldText === 'omitted') {
$sheet->getCell('B1')->setValue('=REPLACE()');
} elseif ($start === 'omitted') {
$this->setCell('A1', $oldText);
$sheet->getCell('B1')->setValue('=REPLACE(A1)');
} elseif ($count === 'omitted') {
$this->setCell('A1', $oldText);
$this->setCell('A2', $start);
$sheet->getCell('B1')->setValue('=REPLACE(A1, A2)');
} elseif ($newText === 'omitted') {
$this->setCell('A1', $oldText);
$this->setCell('A2', $start);
$this->setCell('A3', $count);
$sheet->getCell('B1')->setValue('=REPLACE(A1, A2, A3)');
} else {
$this->setCell('A1', $oldText);
$this->setCell('A2', $start);
$this->setCell('A3', $count);
$this->setCell('A4', $newText);
$sheet->getCell('B1')->setValue('=REPLACE(A1, A2, A3, A4)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerREPLACE(): array
{
return require 'tests/data/Calculation/TextData/REPLACE.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerReplaceArray')]
public function testReplaceArray(
array $expectedResult,
string $oldText,
string $start,
string $chars,
string $newText
): void {
$calculation = Calculation::getInstance();
$formula = "=REPLACE({$oldText}, {$start}, {$chars}, {$newText})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerReplaceArray(): array
{
return [
'row vector' => [[['Elephpant', 'ElePHPant']], '"Elephant"', '4', '2', '{"php", "PHP"}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextAfterTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextAfterTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PHPUnit\Framework\Attributes\DataProvider;
class TextAfterTest extends AllSetupTeardown
{
/** @param array{0: string, 1: mixed[]|string, 2?: string, 3?: string, 4?: string} $arguments */
#[DataProvider('providerTEXTAFTER')]
public function testTextAfter(string $expectedResult, array $arguments): void
{
$text = $arguments[0];
$delimiter = $arguments[1];
$args = (is_array($delimiter)) ? 'A1, {A2,A3}' : 'A1, A2';
$args .= (isset($arguments[2])) ? ", {$arguments[2]}" : ',';
$args .= (isset($arguments[3])) ? ", {$arguments[3]}" : ',';
$args .= (isset($arguments[4])) ? ", {$arguments[4]}" : ',';
$worksheet = $this->getSheet();
$worksheet->getCell('A1')->setValue($text);
$worksheet->getCell('A2')->setValue((is_array($delimiter)) ? $delimiter[0] : $delimiter);
if (is_array($delimiter)) {
$worksheet->getCell('A3')->setValue($delimiter[1]);
}
$worksheet->getCell('B1')->setValue("=TEXTAFTER({$args})");
$result = $worksheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerTEXTAFTER(): array
{
return require 'tests/data/Calculation/TextData/TEXTAFTER.php';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextJoinTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextJoinTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\Attributes\DataProvider;
class TextJoinTest extends AllSetupTeardown
{
/** @param mixed[] $args */
#[DataProvider('providerTEXTJOIN')]
public function testTEXTJOIN(mixed $expectedResult, array $args): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
$b1Formula = '=TEXTJOIN(';
$comma = '';
$row = 0;
foreach ($args as $arg) {
++$row;
$this->setCell("A$row", $arg);
$b1Formula .= $comma . "A$row";
$comma = ',';
}
$b1Formula .= ')';
$this->setCell('B1', $b1Formula);
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerTEXTJOIN(): array
{
return require 'tests/data/Calculation/TextData/TEXTJOIN.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerTextjoinArray')]
public function testTextjoinArray(array $expectedResult, string $delimiter, string $blanks, string $texts): void
{
$calculation = Calculation::getInstance();
$formula = "=TEXTJOIN({$delimiter}, {$blanks}, {$texts})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerTextjoinArray(): array
{
return [
'row vector #1' => [[['AB,CD,EF', 'AB;CD;EF']], '{",", ";"}', 'FALSE', '"AB", "CD", "EF"'],
'column vector #1' => [[['AB--CD--EF'], ['AB|CD|EF']], '{"--"; "|"}', 'FALSE', '"AB", "CD", "EF"'],
'matrix #1' => [[['AB,CD,EF', 'AB;CD;EF'], ['AB-CD-EF', 'AB|CD|EF']], '{",", ";"; "-", "|"}', 'FALSE', '"AB", "CD", "EF"'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/NumberValueTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/NumberValueTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\Attributes\DataProvider;
class NumberValueTest extends AllSetupTeardown
{
const NV_PRECISION = 1.0E-8;
#[DataProvider('providerNUMBERVALUE')]
public function testNUMBERVALUE(mixed $expectedResult, mixed $number = 'omitted', mixed $decimal = 'omitted', mixed $group = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($number === 'omitted') {
$sheet->getCell('B1')->setValue('=NUMBERVALUE()');
} elseif ($decimal === 'omitted') {
$this->setCell('A1', $number);
$sheet->getCell('B1')->setValue('=NUMBERVALUE(A1)');
} elseif ($group === 'omitted') {
$this->setCell('A1', $number);
$this->setCell('A2', $decimal);
$sheet->getCell('B1')->setValue('=NUMBERVALUE(A1, A2)');
} else {
$this->setCell('A1', $number);
$this->setCell('A2', $decimal);
$this->setCell('A3', $group);
$sheet->getCell('B1')->setValue('=NUMBERVALUE(A1, A2, A3)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEqualsWithDelta($expectedResult, $result, self::NV_PRECISION);
}
public static function providerNUMBERVALUE(): array
{
return require 'tests/data/Calculation/TextData/NUMBERVALUE.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerNumberValueArray')]
public function testNumberValueArray(array $expectedResult, string $argument1, string $argument2, string $argument3): void
{
$calculation = Calculation::getInstance();
$formula = "=NumberValue({$argument1}, {$argument2}, {$argument3})";
$result = $calculation->calculateFormula($formula);
self::assertEqualsWithDelta($expectedResult, $result, self::NV_PRECISION);
}
public static function providerNumberValueArray(): array
{
return [
'row vector #1' => [[[-123.321, 123.456, 12345.6789]], '{"-123,321", "123,456", "12 345,6789"}', '","', '" "'],
'column vector #1' => [[[-123.321], [123.456], [12345.6789]], '{"-123,321"; "123,456"; "12 345,6789"}', '","', '" "'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/RightTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/RightTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Settings;
use PHPUnit\Framework\Attributes\DataProvider;
class RightTest extends AllSetupTeardown
{
/**
* @param mixed $str string from which to extract
* @param mixed $cnt number of characters to extract
*/
#[DataProvider('providerRIGHT')]
public function testRIGHT(mixed $expectedResult, mixed $str = 'omitted', mixed $cnt = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($str === 'omitted') {
$sheet->getCell('B1')->setValue('=RIGHT()');
} elseif ($cnt === 'omitted') {
$this->setCell('A1', $str);
$sheet->getCell('B1')->setValue('=RIGHT(A1)');
} else {
$this->setCell('A1', $str);
$this->setCell('A2', $cnt);
$sheet->getCell('B1')->setValue('=RIGHT(A1, A2)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerRIGHT(): array
{
return require 'tests/data/Calculation/TextData/RIGHT.php';
}
#[DataProvider('providerLocaleRIGHT')]
public function testLowerWithLocaleBoolean(string $expectedResult, string $locale, mixed $value, mixed $characters): void
{
$newLocale = Settings::setLocale($locale);
if ($newLocale === false) {
self::markTestSkipped('Unable to set locale for locale-specific test');
}
$sheet = $this->getSheet();
$this->setCell('A1', $value);
$this->setCell('A2', $characters);
$sheet->getCell('B1')->setValue('=RIGHT(A1, A2)');
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerLocaleRIGHT(): array
{
return [
['RAI', 'fr_FR', true, 3],
['AAR', 'nl_NL', true, 3],
['OSI', 'fi', true, 3],
['ИНА', 'bg', true, 3],
['UX', 'fr_FR', false, 2],
['WAAR', 'nl_NL', false, 4],
['ÄTOSI', 'fi', false, 5],
['ЖЬ', 'bg', false, 2],
];
}
#[DataProvider('providerCalculationTypeRIGHTTrue')]
public function testCalculationTypeTrue(string $type, string $resultB1, string $resultB2): void
{
Functions::setCompatibilityMode($type);
$sheet = $this->getSheet();
$this->setCell('A1', true);
$this->setCell('A2', 'Hello');
$this->setCell('B1', '=RIGHT(A1, 1)');
$this->setCell('B2', '=RIGHT(A2, A1)');
self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue());
self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue());
}
public static function providerCalculationTypeRIGHTTrue(): array
{
return [
'Excel RIGHT(true, 1) AND RIGHT("hello", true)' => [
Functions::COMPATIBILITY_EXCEL,
'E',
'o',
],
'Gnumeric RIGHT(true, 1) AND RIGHT("hello", true)' => [
Functions::COMPATIBILITY_GNUMERIC,
'E',
'o',
],
'OpenOffice RIGHT(true, 1) AND RIGHT("hello", true)' => [
Functions::COMPATIBILITY_OPENOFFICE,
'1',
'#VALUE!',
],
];
}
#[DataProvider('providerCalculationTypeRIGHTFalse')]
public function testCalculationTypeFalse(string $type, string $resultB1, string $resultB2): void
{
Functions::setCompatibilityMode($type);
$sheet = $this->getSheet();
$this->setCell('A1', false);
$this->setCell('A2', 'Hello');
$this->setCell('B1', '=RIGHT(A1, 1)');
$this->setCell('B2', '=RIGHT(A2, A1)');
self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue());
self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue());
}
public static function providerCalculationTypeRIGHTFalse(): array
{
return [
'Excel RIGHT(false, 1) AND RIGHT("hello", false)' => [
Functions::COMPATIBILITY_EXCEL,
'E',
'',
],
'Gnumeric RIGHT(false, 1) AND RIGHT("hello", false)' => [
Functions::COMPATIBILITY_GNUMERIC,
'E',
'',
],
'OpenOffice RIGHT(false, 1) AND RIGHT("hello", false)' => [
Functions::COMPATIBILITY_OPENOFFICE,
'0',
'#VALUE!',
],
];
}
#[DataProvider('providerCalculationTypeRIGHTNull')]
public function testCalculationTypeNull(string $type, string $resultB1, string $resultB2): void
{
Functions::setCompatibilityMode($type);
$sheet = $this->getSheet();
$this->setCell('A2', 'Hello');
$this->setCell('B1', '=RIGHT(A1, 1)');
$this->setCell('B2', '=RIGHT(A2, A1)');
self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue());
self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue());
}
public static function providerCalculationTypeRIGHTNull(): array
{
return [
'Excel RIGHT(null, 1) AND RIGHT("hello", null)' => [
Functions::COMPATIBILITY_EXCEL,
'',
'',
],
'Gnumeric RIGHT(null, 1) AND RIGHT("hello", null)' => [
Functions::COMPATIBILITY_GNUMERIC,
'',
'o',
],
'OpenOffice RIGHT(null, 1) AND RIGHT("hello", null)' => [
Functions::COMPATIBILITY_OPENOFFICE,
'',
'',
],
];
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerRightArray')]
public function testRightArray(array $expectedResult, string $argument1, string $argument2): void
{
$calculation = Calculation::getInstance();
$formula = "=RIGHT({$argument1}, {$argument2})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerRightArray(): array
{
return [
'row vector #1' => [[['llo', 'rld', 'eet']], '{"Hello", "World", "PhpSpreadsheet"}', '3'],
'column vector #1' => [[['llo'], ['rld'], ['eet']], '{"Hello"; "World"; "PhpSpreadsheet"}', '3'],
'matrix #1' => [[['llo', 'rld'], ['eet', 'cel']], '{"Hello", "World"; "PhpSpreadsheet", "Excel"}', '3'],
'column vector #2' => [[['eet'], ['sheet']], '"PhpSpreadsheet"', '{3; 5}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/DollarTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/DollarTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\Attributes\DataProvider;
class DollarTest extends AllSetupTeardown
{
#[DataProvider('providerDOLLAR')]
public function testDOLLAR(mixed $expectedResult, mixed $amount = 'omitted', mixed $decimals = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($amount === 'omitted') {
$sheet->getCell('B1')->setValue('=DOLLAR()');
} elseif ($decimals === 'omitted') {
$this->setCell('A1', $amount);
$sheet->getCell('B1')->setValue('=DOLLAR(A1)');
} else {
$this->setCell('A1', $amount);
$this->setCell('A2', $decimals);
$sheet->getCell('B1')->setValue('=DOLLAR(A1, A2)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerDOLLAR(): array
{
return require 'tests/data/Calculation/TextData/DOLLAR.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerDollarArray')]
public function testDollarArray(array $expectedResult, string $argument1, string $argument2): void
{
$calculation = Calculation::getInstance();
$formula = "=DOLLAR({$argument1}, {$argument2})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerDollarArray(): array
{
return [
'row vector #1' => [[['-$123.32', '$123.46', '$12,345.68']], '{-123.321, 123.456, 12345.6789}', '2'],
'column vector #1' => [[['-$123.32'], ['$123.46'], ['$12,345.68']], '{-123.321; 123.456; 12345.6789}', '2'],
'matrix #1' => [[['-$123.46', '$12,345.68'], ['-$123.456', '$12,345.679']], '{-123.456, 12345.6789}', '{2; 3}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/UpperTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/UpperTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Settings;
use PHPUnit\Framework\Attributes\DataProvider;
class UpperTest extends AllSetupTeardown
{
#[DataProvider('providerUPPER')]
public function testUPPER(mixed $expectedResult, mixed $str = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($str === 'omitted') {
$sheet->getCell('B1')->setValue('=UPPER()');
} else {
$this->setCell('A1', $str);
$sheet->getCell('B1')->setValue('=UPPER(A1)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerUPPER(): array
{
return require 'tests/data/Calculation/TextData/UPPER.php';
}
#[DataProvider('providerLocaleLOWER')]
public function testLowerWithLocaleBoolean(string $expectedResult, string $locale, mixed $value): void
{
$newLocale = Settings::setLocale($locale);
if ($newLocale === false) {
self::markTestSkipped('Unable to set locale for locale-specific test');
}
$sheet = $this->getSheet();
$this->setCell('A1', $value);
$sheet->getCell('B1')->setValue('=UPPER(A1)');
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerLocaleLOWER(): array
{
return [
['VRAI', 'fr_FR', true],
['WAAR', 'nl_NL', true],
['TOSI', 'fi', true],
['ИСТИНА', 'bg', true],
['FAUX', 'fr_FR', false],
['ONWAAR', 'nl_NL', false],
['EPÄTOSI', 'fi', false],
['ЛОЖЬ', 'bg', false],
];
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerUpperArray')]
public function testUpperArray(array $expectedResult, string $array): void
{
$calculation = Calculation::getInstance();
$formula = "=UPPER({$array})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerUpperArray(): array
{
return [
'row vector' => [[["LET'S", 'ALL CHANGE', 'CASE']], '{"lEt\'S", "aLl chAngE", "cAsE"}'],
'column vector' => [[["LET'S"], ['ALL CHANGE'], ['CASE']], '{"lEt\'S"; "aLl chAngE"; "cAsE"}'],
'matrix' => [[['BUILD ALL', 'YOUR WORKBOOKS'], ['WITH', 'PHPSPREADSHEET']], '{"bUIld aLL", "yOUr WOrkBOOks"; "wiTH", "PhpSpreadsheet"}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextBeforeTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextBeforeTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PHPUnit\Framework\Attributes\DataProvider;
class TextBeforeTest extends AllSetupTeardown
{
/** @param array{0: string, 1: mixed[]|string, 2?: string, 3?: string, 4?: string} $arguments */
#[DataProvider('providerTEXTBEFORE')]
public function testTextBefore(string $expectedResult, array $arguments): void
{
$text = $arguments[0];
$delimiter = $arguments[1];
$args = (is_array($delimiter)) ? 'A1, {A2,A3}' : 'A1, A2';
$args .= (isset($arguments[2])) ? ", {$arguments[2]}" : ',';
$args .= (isset($arguments[3])) ? ", {$arguments[3]}" : ',';
$args .= (isset($arguments[4])) ? ", {$arguments[4]}" : ',';
$worksheet = $this->getSheet();
$worksheet->getCell('A1')->setValue($text);
$worksheet->getCell('A2')->setValue((is_array($delimiter)) ? $delimiter[0] : $delimiter);
if (is_array($delimiter)) {
$worksheet->getCell('A3')->setValue($delimiter[1]);
}
$worksheet->getCell('B1')->setValue("=TEXTBEFORE({$args})");
$result = $worksheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerTEXTBEFORE(): array
{
return require 'tests/data/Calculation/TextData/TEXTBEFORE.php';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/UnicharTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/UnicharTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\Attributes\DataProvider;
class UnicharTest extends AllSetupTeardown
{
#[DataProvider('providerCHAR')]
public function testCHAR(mixed $expectedResult, mixed $character = 'omitted'): void
{
// If expected is array, 1st is for CHAR, 2nd for UNICHAR,
// 3rd is for Mac CHAR if different from Windows.
if (is_array($expectedResult)) {
$expectedResult = $expectedResult[1];
}
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($character === 'omitted') {
$sheet->getCell('B1')->setValue('=UNICHAR()');
} else {
$this->setCell('A1', $character);
$sheet->getCell('B1')->setValue('=UNICHAR(A1)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerCHAR(): array
{
return require 'tests/data/Calculation/TextData/CHAR.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerCharArray')]
public function testCharArray(array $expectedResult, string $array): void
{
$calculation = Calculation::getInstance();
$formula = "=UNICHAR({$array})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerCharArray(): array
{
return [
'row vector' => [[['P', 'H', 'P']], '{80, 72, 80}'],
'column vector' => [[['P'], ['H'], ['P']], '{80; 72; 80}'],
'matrix' => [[['Y', 'o'], ['l', 'o']], '{89, 111; 108, 111}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/SubstituteTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/SubstituteTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\Attributes\DataProvider;
class SubstituteTest extends AllSetupTeardown
{
#[DataProvider('providerSUBSTITUTE')]
public function testSUBSTITUTE(mixed $expectedResult, mixed $text = 'omitted', mixed $oldText = 'omitted', mixed $newText = 'omitted', mixed $instance = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($text === 'omitted') {
$sheet->getCell('B1')->setValue('=SUBSTITUTE()');
} elseif ($oldText === 'omitted') {
$this->setCell('A1', $text);
$sheet->getCell('B1')->setValue('=SUBSTITUTE(A1)');
} elseif ($newText === 'omitted') {
$this->setCell('A1', $text);
$this->setCell('A2', $oldText);
$sheet->getCell('B1')->setValue('=SUBSTITUTE(A1, A2)');
} elseif ($instance === 'omitted') {
$this->setCell('A1', $text);
$this->setCell('A2', $oldText);
$this->setCell('A3', $newText);
$sheet->getCell('B1')->setValue('=SUBSTITUTE(A1, A2, A3)');
} else {
$this->setCell('A1', $text);
$this->setCell('A2', $oldText);
$this->setCell('A3', $newText);
$this->setCell('A4', $instance);
$sheet->getCell('B1')->setValue('=SUBSTITUTE(A1, A2, A3, A4)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerSUBSTITUTE(): array
{
return require 'tests/data/Calculation/TextData/SUBSTITUTE.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerSubstituteArray')]
public function testSubstituteArray(array $expectedResult, string $oldText, string $fromText, string $toText): void
{
$calculation = Calculation::getInstance();
$formula = "=SUBSTITUTE({$oldText}, {$fromText}, {$toText})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerSubstituteArray(): array
{
return [
'row vector' => [[['ElePHPant', 'EleFFant']], '"Elephant"', '"ph"', '{"PHP", "FF"}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ConcatenateTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ConcatenateTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
class ConcatenateTest extends AllSetupTeardown
{
#[DataProvider('providerCONCATENATE')]
public function testCONCATENATE(mixed $expectedResult, mixed ...$args): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
$finalArg = '';
$comma = '';
foreach ($args as $arg) {
$finalArg .= $comma;
$comma = ',';
if (is_bool($arg)) {
$finalArg .= $arg ? 'true' : 'false';
} elseif ($arg === 'A2') {
$finalArg .= 'A2';
$sheet->getCell('A2')->setValue('=2/0');
} elseif ($arg === 'A3') {
$finalArg .= 'A3';
$sheet->getCell('A3')->setValue(str_repeat('Ԁ', DataType::MAX_STRING_LENGTH - 5));
} else {
self::assertTrue($arg === null || is_scalar($arg));
$finalArg .= '"' . (string) $arg . '"';
}
}
$this->setCell('B1', "=CONCATENATE($finalArg)");
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerCONCATENATE(): array
{
return require 'tests/data/Calculation/TextData/CONCATENATE.php';
}
public function testConcatenateWithIndexMatch(): void
{
$spreadsheet = new Spreadsheet();
$sheet1 = $spreadsheet->getActiveSheet();
$sheet1->setTitle('Formula');
$sheet1->fromArray(
[
['Number', 'Formula'],
[52101293, '=CONCATENATE(INDEX(Lookup!B2, MATCH(A2, Lookup!A2, 0)))'],
]
);
$sheet2 = $spreadsheet->createSheet();
$sheet2->setTitle('Lookup');
$sheet2->fromArray(
[
['Lookup', 'Match'],
[52101293, 'PHP'],
]
);
self::assertSame('PHP', $sheet1->getCell('B2')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CharTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CharTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert as CC;
use PHPUnit\Framework\Attributes\DataProvider;
class CharTest extends AllSetupTeardown
{
protected function tearDown(): void
{
parent::tearDown();
CC::setWindowsCharacterSet();
}
#[DataProvider('providerCHAR')]
public function testCHAR(mixed $expectedResult, mixed $character = 'omitted'): void
{
// If expected is array, 1st is for CHAR, 2nd for UNICHAR,
// 3rd is for Mac CHAR if different from Windows.
if (is_array($expectedResult)) {
$expectedResult = $expectedResult[0];
}
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($character === 'omitted') {
$sheet->getCell('B1')->setValue('=CHAR()');
} else {
$this->setCell('A1', $character);
$sheet->getCell('B1')->setValue('=CHAR(A1)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
#[DataProvider('providerCHAR')]
public function testMacCHAR(mixed $expectedResult, mixed $character = 'omitted'): void
{
CC::setMacCharacterSet();
// If expected is array, 1st is for CHAR, 2nd for UNICHAR,
// 3rd is for Mac CHAR if different from Windows.
if (is_array($expectedResult)) {
$expectedResult = $expectedResult[2] ?? $expectedResult[0];
}
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($character === 'omitted') {
$sheet->getCell('B1')->setValue('=CHAR()');
} else {
$this->setCell('A1', $character);
$sheet->getCell('B1')->setValue('=CHAR(A1)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerCHAR(): array
{
return require 'tests/data/Calculation/TextData/CHAR.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerCharArray')]
public function testCharArray(array $expectedResult, string $array): void
{
$calculation = Calculation::getInstance();
$formula = "=CHAR({$array})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerCharArray(): array
{
return [
'row vector' => [[['P', 'H', 'P']], '{80, 72, 80}'],
'column vector' => [[['P'], ['H'], ['P']], '{80; 72; 80}'],
'matrix' => [[['Y', 'o'], ['l', 'o']], '{89, 111; 108, 111}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ConcatenateRangeTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ConcatenateRangeTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
class ConcatenateRangeTest extends AllSetupTeardown
{
public function testIssue4061(): void
{
$sheet = $this->getSheet();
$sheet->getCell('A1')->setValue('a');
$sheet->getCell('A2')->setValue('b');
$sheet->getCell('A3')->setValue('c');
$sheet->getCell('C1')->setValue('1');
$sheet->getCell('C2')->setValue('2');
$sheet->getCell('C3')->setValue('3');
$sheet->getCell('B1')->setValue('=CONCATENATE(A1:A3, "-", C1:C3)');
Calculation::getInstance($this->getSpreadsheet())
->setInstanceArrayReturnType(
Calculation::RETURN_ARRAY_AS_VALUE
);
self::assertSame('a-1', $sheet->getCell('B1')->getCalculatedValue());
$sheet->getCell('X1')->setValue('=A1:A3&"-"&C1:C3');
self::assertSame('a-1', $sheet->getCell('X1')->getCalculatedValue());
$sheet->getCell('D1')->setValue('=CONCAT(A1:A3, "-", C1:C3)');
self::assertSame('abc-123', $sheet->getCell('D1')->getCalculatedValue());
Calculation::getInstance($this->getSpreadsheet())
->setInstanceArrayReturnType(
Calculation::RETURN_ARRAY_AS_ARRAY
);
$sheet->getCell('E1')->setValue('=CONCATENATE(A1:A3, "-", C1:C3)');
self::assertSame([['a-1'], ['b-2'], ['c-3']], $sheet->getCell('E1')->getCalculatedValue());
$sheet->getCell('Y1')->setValue('=A1:A3&"-"&C1:C3');
self::assertSame([['a-1'], ['b-2'], ['c-3']], $sheet->getCell('Y1')->getCalculatedValue());
$sheet->getCell('F1')->setValue('=CONCAT(A1:A3, "-", C1:C3)');
self::assertSame('abc-123', $sheet->getCell('F1')->getCalculatedValue());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ConcatTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ConcatTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class ConcatTest extends AllSetupTeardown
{
#[\PHPUnit\Framework\Attributes\DataProvider('providerCONCAT')]
public function testCONCAT(mixed $expectedResult, mixed ...$args): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
$finalArg = '';
$row = 0;
foreach ($args as $arg) {
++$row;
$this->setCell("A$row", $arg);
$finalArg = "A1:A$row";
}
$this->setCell('B1', "=CONCAT($finalArg)");
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerCONCAT(): array
{
return require 'tests/data/Calculation/TextData/CONCAT.php';
}
public function testConcatWithIndexMatch(): void
{
$spreadsheet = new Spreadsheet();
$sheet1 = $spreadsheet->getActiveSheet();
$sheet1->setTitle('Formula');
$sheet1->fromArray(
[
['Number', 'Formula'],
[52101293, '=CONCAT(INDEX(Lookup!B2, MATCH(A2, Lookup!A2, 0)))'],
]
);
$sheet2 = $spreadsheet->createSheet();
$sheet2->setTitle('Lookup');
$sheet2->fromArray(
[
['Lookup', 'Match'],
[52101293, 'PHP'],
]
);
self::assertSame('PHP', $sheet1->getCell('B2')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/BahtTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/BahtTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class BahtTest extends TestCase
{
#[\PHPUnit\Framework\Attributes\DataProvider('providerBAHTTEXT')]
public function testBAHTTEXT(mixed $expectedResult, bool|string|float|int $number): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
if (is_bool($number)) {
$formulaValue = $number ? 'TRUE' : 'FALSE';
} elseif (is_string($number)) {
$formulaValue = '"' . $number . '"';
} else {
$formulaValue = (string) $number;
}
$sheet->getCell('A1')->setValue('=BAHTTEXT(' . $formulaValue . ')');
$result = $sheet->getCell('A1')->getCalculatedValue();
self::assertSame($expectedResult, $result);
$spreadsheet->disconnectWorksheets();
}
public static function providerBAHTTEXT(): array
{
return require 'tests/data/Calculation/TextData/BAHTTEXT.php';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LeftTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LeftTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Settings;
use PHPUnit\Framework\Attributes\DataProvider;
class LeftTest extends AllSetupTeardown
{
/**
* @param mixed $str string from which to extract
* @param mixed $cnt number of characters to extract
*/
#[DataProvider('providerLEFT')]
public function testLEFT(mixed $expectedResult, mixed $str = 'omitted', mixed $cnt = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($str === 'omitted') {
$sheet->getCell('B1')->setValue('=LEFT()');
} elseif ($cnt === 'omitted') {
$this->setCell('A1', $str);
$sheet->getCell('B1')->setValue('=LEFT(A1)');
} else {
$this->setCell('A1', $str);
$this->setCell('A2', $cnt);
$sheet->getCell('B1')->setValue('=LEFT(A1, A2)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerLEFT(): array
{
return require 'tests/data/Calculation/TextData/LEFT.php';
}
#[DataProvider('providerLocaleLEFT')]
public function testLowerWithLocaleBoolean(string $expectedResult, string $locale, mixed $value, mixed $characters): void
{
$newLocale = Settings::setLocale($locale);
if ($newLocale === false) {
self::markTestSkipped('Unable to set locale for locale-specific test');
}
$sheet = $this->getSheet();
$this->setCell('A1', $value);
$this->setCell('A2', $characters);
$sheet->getCell('B1')->setValue('=LEFT(A1, A2)');
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerLocaleLEFT(): array
{
return [
['VR', 'fr_FR', true, 2],
['WA', 'nl_NL', true, 2],
['TO', 'fi', true, 2],
['ИСТ', 'bg', true, 3],
['FA', 'fr_FR', false, 2],
['ON', 'nl_NL', false, 2],
['EPÄT', 'fi', false, 4],
['ЛОЖ', 'bg', false, 3],
];
}
#[DataProvider('providerCalculationTypeLEFTTrue')]
public function testCalculationTypeTrue(string $type, string $resultB1, string $resultB2): void
{
Functions::setCompatibilityMode($type);
$sheet = $this->getSheet();
$this->setCell('A1', true);
$this->setCell('A2', 'Hello');
$this->setCell('B1', '=LEFT(A1, 1)');
$this->setCell('B2', '=LEFT(A2, A1)');
self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue());
self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue());
}
public static function providerCalculationTypeLEFTTrue(): array
{
return [
'Excel LEFT(true, 1) AND LEFT("hello", true)' => [
Functions::COMPATIBILITY_EXCEL,
'T',
'H',
],
'Gnumeric LEFT(true, 1) AND LEFT("hello", true)' => [
Functions::COMPATIBILITY_GNUMERIC,
'T',
'H',
],
'OpenOffice LEFT(true, 1) AND LEFT("hello", true)' => [
Functions::COMPATIBILITY_OPENOFFICE,
'1',
'#VALUE!',
],
];
}
#[DataProvider('providerCalculationTypeLEFTFalse')]
public function testCalculationTypeFalse(string $type, string $resultB1, string $resultB2): void
{
Functions::setCompatibilityMode($type);
$sheet = $this->getSheet();
$this->setCell('A1', false);
$this->setCell('A2', 'Hello');
$this->setCell('B1', '=LEFT(A1, 1)');
$this->setCell('B2', '=LEFT(A2, A1)');
self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue());
self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue());
}
public static function providerCalculationTypeLEFTFalse(): array
{
return [
'Excel LEFT(false, 1) AND LEFT("hello", false)' => [
Functions::COMPATIBILITY_EXCEL,
'F',
'',
],
'Gnumeric LEFT(false, 1) AND LEFT("hello", false)' => [
Functions::COMPATIBILITY_GNUMERIC,
'F',
'',
],
'OpenOffice LEFT(false, 1) AND LEFT("hello", false)' => [
Functions::COMPATIBILITY_OPENOFFICE,
'0',
'#VALUE!',
],
];
}
#[DataProvider('providerCalculationTypeLEFTNull')]
public function testCalculationTypeNull(string $type, string $resultB1, string $resultB2): void
{
Functions::setCompatibilityMode($type);
$sheet = $this->getSheet();
$this->setCell('A2', 'Hello');
$this->setCell('B1', '=LEFT(A1, 1)');
$this->setCell('B2', '=LEFT(A2, A1)');
self::assertEquals($resultB1, $sheet->getCell('B1')->getCalculatedValue());
self::assertEquals($resultB2, $sheet->getCell('B2')->getCalculatedValue());
}
public static function providerCalculationTypeLEFTNull(): array
{
return [
'Excel LEFT(null, 1) AND LEFT("hello", null)' => [
Functions::COMPATIBILITY_EXCEL,
'',
'',
],
'Gnumeric LEFT(null, 1) AND LEFT("hello", null)' => [
Functions::COMPATIBILITY_GNUMERIC,
'',
'H',
],
'OpenOffice LEFT(null, 1) AND LEFT("hello", null)' => [
Functions::COMPATIBILITY_OPENOFFICE,
'',
'',
],
];
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerLeftArray')]
public function testLeftArray(array $expectedResult, string $argument1, string $argument2): void
{
$calculation = Calculation::getInstance();
$formula = "=LEFT({$argument1}, {$argument2})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerLeftArray(): array
{
return [
'row vector #1' => [[['Hel', 'Wor', 'Php']], '{"Hello", "World", "PhpSpreadsheet"}', '3'],
'column vector #1' => [[['Hel'], ['Wor'], ['Php']], '{"Hello"; "World"; "PhpSpreadsheet"}', '3'],
'matrix #1' => [[['Hel', 'Wor'], ['Php', 'Exc']], '{"Hello", "World"; "PhpSpreadsheet", "Excel"}', '3'],
'column vector #2' => [[['Php'], ['PhpSp']], '"PhpSpreadsheet"', '{3; 5}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ExactTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ExactTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\Attributes\DataProvider;
class ExactTest extends AllSetupTeardown
{
#[DataProvider('providerEXACT')]
public function testEXACT(mixed $expectedResult, mixed $string1 = 'omitted', mixed $string2 = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($string1 === 'omitted') {
$sheet->getCell('B1')->setValue('=EXACT()');
} elseif ($string2 === 'omitted') {
$this->setCell('A1', $string1);
$sheet->getCell('B1')->setValue('=EXACT(A1)');
} else {
$this->setCell('A1', $string1);
$this->setCell('A2', $string2);
$sheet->getCell('B1')->setValue('=EXACT(A1, A2)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerEXACT(): array
{
return require 'tests/data/Calculation/TextData/EXACT.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerExactArray')]
public function testExactArray(array $expectedResult, string $argument1, string $argument2): void
{
$calculation = Calculation::getInstance();
$formula = "=EXACT({$argument1}, {$argument2})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerExactArray(): array
{
return [
'row vector #1' => [[[true, false, false]], '{"PHP", "php", "PHP8"}', '"PHP"'],
'column vector #1' => [[[false], [true], [false]], '{"php"; "PHP"; "PHP8"}', '"PHP"'],
'matrix #1' => [[[false, true], [false, true]], '{"TRUE", "FALSE"; TRUE, FALSE}', '"FALSE"'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ConcatenateGnumericTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ConcatenateGnumericTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class ConcatenateGnumericTest extends AllSetupTeardown
{
/**
* Gnumeric, unlike Excel or LibreOffice, implements CONCATENATE like CONCAT.
*/
#[\PHPUnit\Framework\Attributes\DataProvider('providerCONCAT')]
public function testCONCATENATE(mixed $expectedResult, mixed ...$args): void
{
self::setGnumeric();
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
$finalArg = '';
$row = 0;
foreach ($args as $arg) {
++$row;
$this->setCell("A$row", $arg);
$finalArg = "A1:A$row";
}
$this->setCell('B1', "=CONCATENATE($finalArg)");
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerCONCAT(): array
{
return require 'tests/data/Calculation/TextData/CONCAT.php';
}
public function testConcatWithIndexMatch(): void
{
self::setGnumeric();
$spreadsheet = new Spreadsheet();
$sheet1 = $spreadsheet->getActiveSheet();
$sheet1->setTitle('Formula');
$sheet1->fromArray(
[
['Number', 'Formula'],
[52101293, '=CONCATENATE(INDEX(Lookup!B2, MATCH(A2, Lookup!A2, 0)))'],
]
);
$sheet2 = $spreadsheet->createSheet();
$sheet2->setTitle('Lookup');
$sheet2->fromArray(
[
['Lookup', 'Match'],
[52101293, 'PHP'],
]
);
self::assertSame('PHP', $sheet1->getCell('B2')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CodeTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CodeTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\TextData\CharacterConvert as CC;
use PHPUnit\Framework\Attributes\DataProvider;
class CodeTest extends AllSetupTeardown
{
protected function tearDown(): void
{
parent::tearDown();
CC::setWindowsCharacterSet();
}
#[DataProvider('providerCODE')]
public function testCODE(mixed $expectedResult, mixed $character = 'omitted'): void
{
// If expected is array, 1st is for CODE, 2nd for UNICODE,
// 3rd is for Mac CODE if different from Windows.
if (is_array($expectedResult)) {
$expectedResult = $expectedResult[0];
}
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($character === 'omitted') {
$sheet->getCell('B1')->setValue('=CODE()');
} else {
$this->setCell('A1', $character);
$sheet->getCell('B1')->setValue('=CODE(A1)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
#[DataProvider('providerCODE')]
public function testMacCODE(mixed $expectedResult, mixed $character = 'omitted'): void
{
CC::setMacCharacterSet();
// If expected is array, 1st is for CODE, 2nd for UNICODE,
// 3rd is for Mac CODE if different from Windows.
if (is_array($expectedResult)) {
$expectedResult = $expectedResult[2] ?? $expectedResult[0];
}
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($character === 'omitted') {
$sheet->getCell('B1')->setValue('=CODE()');
} else {
$this->setCell('A1', $character);
$sheet->getCell('B1')->setValue('=CODE(A1)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerCODE(): array
{
return require 'tests/data/Calculation/TextData/CODE.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerCodeArray')]
public function testCodeArray(array $expectedResult, string $array): void
{
$calculation = Calculation::getInstance();
$formula = "=CODE({$array})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerCodeArray(): array
{
return [
'row vector' => [[[80, 72, 80]], '{"P", "H", "P"}'],
'column vector' => [[[80], [72], [80]], '{"P"; "H"; "P"}'],
'matrix' => [[[89, 111], [108, 111]], '{"Y", "o"; "l", "o"}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\Attributes\DataProvider;
class TextTest extends AllSetupTeardown
{
#[DataProvider('providerTEXT')]
public function testTEXT(mixed $expectedResult, mixed $value = 'omitted', mixed $format = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($value === 'omitted') {
$sheet->getCell('B1')->setValue('=TEXT()');
} elseif ($format === 'omitted') {
$this->setCell('A1', $value);
$sheet->getCell('B1')->setValue('=TEXT(A1)');
} else {
$this->setCell('A1', $value);
$this->setCell('A2', $format);
$sheet->getCell('B1')->setValue('=TEXT(A1, A2)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerTEXT(): array
{
return require 'tests/data/Calculation/TextData/TEXT.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerTextArray')]
public function testTextArray(array $expectedResult, string $argument1, string $argument2): void
{
$calculation = Calculation::getInstance();
$formula = "=TEXT({$argument1}, {$argument2})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerTextArray(): array
{
return [
'row vector' => [[['123.75%', '1 19/80']], '1.2375', '{"0.00%", "0 ??/???"}'],
'matrix vector' => [
[
['$ -1,234.57', '(1,234.57)'],
['$ 9,876.54', '9,876.54'],
],
'{-1234.5678; 9876.5432}',
'{"$ #,##0.00", "#,##0.00;(#,##0.00)"}',
],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextSplitTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/TextSplitTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\Attributes\DataProvider;
class TextSplitTest extends AllSetupTeardown
{
/** @param mixed[] $argument */
private function setDelimiterArgument(array $argument, string $column): string
{
return '{' . $column . implode(',' . $column, range(1, count($argument))) . '}';
}
private function setDelimiterValues(Worksheet $worksheet, string $column, mixed $argument): void
{
if (is_array($argument)) {
foreach ($argument as $index => $value) {
++$index;
$worksheet->getCell("{$column}{$index}")->setValue($value);
}
} else {
$worksheet->getCell("{$column}1")->setValue($argument);
}
}
/**
* @param mixed[] $expectedResult
* @param array{0: string, 1: mixed[]|string, 2: mixed[]|string, 3?: string, 4?: string, 5?: string} $arguments
*/
#[DataProvider('providerTEXTSPLIT')]
public function testTextSplit(array $expectedResult, array $arguments): void
{
Calculation::getInstance($this->getSpreadsheet())->setInstanceArrayReturnType(Calculation::RETURN_ARRAY_AS_ARRAY);
$text = $arguments[0];
$columnDelimiter = $arguments[1];
$rowDelimiter = $arguments[2];
$args = 'A1';
$args .= (is_array($columnDelimiter)) ? ', ' . $this->setDelimiterArgument($columnDelimiter, 'B') : ', B1';
$args .= (is_array($rowDelimiter)) ? ', ' . $this->setDelimiterArgument($rowDelimiter, 'C') : ', C1';
$args .= (isset($arguments[3])) ? ", {$arguments[3]}" : ',';
$args .= (isset($arguments[4])) ? ", {$arguments[4]}" : ',';
$args .= (isset($arguments[5])) ? ", {$arguments[5]}" : ',';
$worksheet = $this->getSheet();
$worksheet->getCell('A1')->setValue($text);
$this->setDelimiterValues($worksheet, 'B', $columnDelimiter);
if (!empty($rowDelimiter)) {
$this->setDelimiterValues($worksheet, 'C', $rowDelimiter);
}
$worksheet->getCell('H1')->setValue("=TEXTSPLIT({$args})");
$result = Calculation::getInstance($this->getSpreadsheet())->calculateCellValue($worksheet->getCell('H1'));
self::assertSame($expectedResult, $result);
}
public static function providerTEXTSPLIT(): array
{
return require 'tests/data/Calculation/TextData/TEXTSPLIT.php';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LowerTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/LowerTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Settings;
use PHPUnit\Framework\Attributes\DataProvider;
class LowerTest extends AllSetupTeardown
{
#[DataProvider('providerLOWER')]
public function testLOWER(mixed $expectedResult, mixed $str = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($str === 'omitted') {
$sheet->getCell('B1')->setValue('=LOWER()');
} else {
$this->setCell('A1', $str);
$sheet->getCell('B1')->setValue('=LOWER(A1)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerLOWER(): array
{
return require 'tests/data/Calculation/TextData/LOWER.php';
}
#[DataProvider('providerLocaleLOWER')]
public function testLowerWithLocaleBoolean(string $expectedResult, string $locale, mixed $value): void
{
$newLocale = Settings::setLocale($locale);
if ($newLocale === false) {
self::markTestSkipped('Unable to set locale for locale-specific test');
}
$sheet = $this->getSheet();
$this->setCell('A1', $value);
$sheet->getCell('B1')->setValue('=LOWER(A1)');
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerLocaleLOWER(): array
{
return [
['vrai', 'fr_FR', true],
['waar', 'nl_NL', true],
['tosi', 'fi', true],
['истина', 'bg', true],
['faux', 'fr_FR', false],
['onwaar', 'nl_NL', false],
['epätosi', 'fi', false],
['ложь', 'bg', false],
];
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerLowerArray')]
public function testLowerArray(array $expectedResult, string $array): void
{
$calculation = Calculation::getInstance();
$formula = "=LOWER({$array})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerLowerArray(): array
{
return [
'row vector' => [[["let's", 'all change', 'case']], '{"lEt\'S", "aLl chAngE", "cAsE"}'],
'column vector' => [[["let's"], ['all change'], ['case']], '{"lEt\'S"; "aLl chAngE"; "cAsE"}'],
'matrix' => [[['build all', 'your workbooks'], ['with', 'phpspreadsheet']], '{"bUIld aLL", "yOUr WOrkBOOks"; "wiTH", "PhpSpreadsheet"}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/OpenOfficeTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/OpenOfficeTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
class OpenOfficeTest extends AllSetupTeardown
{
#[\PHPUnit\Framework\Attributes\DataProvider('providerOpenOffice')]
public function testOpenOffice(mixed $expectedResult, string $formula): void
{
$this->setOpenOffice();
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
$this->setCell('A1', $formula);
$result = $sheet->getCell('A1')->getCalculatedValue();
self::assertSame($expectedResult, $result);
}
public static function providerOpenOffice(): array
{
return require 'tests/data/Calculation/TextData/OpenOffice.php';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ProperTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ProperTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Settings;
use PHPUnit\Framework\Attributes\DataProvider;
class ProperTest extends AllSetupTeardown
{
#[DataProvider('providerPROPER')]
public function testPROPER(mixed $expectedResult, mixed $str = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($str === 'omitted') {
$sheet->getCell('B1')->setValue('=PROPER()');
} else {
$this->setCell('A1', $str);
$sheet->getCell('B1')->setValue('=PROPER(A1)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerPROPER(): array
{
return require 'tests/data/Calculation/TextData/PROPER.php';
}
#[DataProvider('providerLocaleLOWER')]
public function testLowerWithLocaleBoolean(string $expectedResult, string $locale, mixed $value): void
{
$newLocale = Settings::setLocale($locale);
if ($newLocale === false) {
self::markTestSkipped('Unable to set locale for locale-specific test');
}
$sheet = $this->getSheet();
$this->setCell('A1', $value);
$sheet->getCell('B1')->setValue('=PROPER(A1)');
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerLocaleLOWER(): array
{
return [
['Vrai', 'fr_FR', true],
['Waar', 'nl_NL', true],
['Tosi', 'fi', true],
['Истина', 'bg', true],
['Faux', 'fr_FR', false],
['Onwaar', 'nl_NL', false],
['Epätosi', 'fi', false],
['Ложь', 'bg', false],
];
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerProperArray')]
public function testProperArray(array $expectedResult, string $array): void
{
$calculation = Calculation::getInstance();
$formula = "=PROPER({$array})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerProperArray(): array
{
return [
'row vector' => [[["Let's", 'All Change', 'Case']], '{"lEt\'S", "aLl chAngE", "cAsE"}'],
'column vector' => [[["Let's"], ['All Change'], ['Case']], '{"lEt\'S"; "aLl chAngE"; "cAsE"}'],
'matrix' => [[['Build All', 'Your Workbooks'], ['With', 'Phpspreadsheet']], '{"bUIld aLL", "yOUr WOrkBOOks"; "wiTH", "PhpSpreadsheet"}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ValueTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/ValueTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PHPUnit\Framework\Attributes\DataProvider;
class ValueTest extends AllSetupTeardown
{
protected function tearDown(): void
{
parent::tearDown();
StringHelper::setCurrencyCode(null);
StringHelper::setDecimalSeparator(null);
StringHelper::setThousandsSeparator(null);
}
#[DataProvider('providerVALUE')]
public function testVALUE(mixed $expectedResult, mixed $value = 'omitted'): void
{
StringHelper::setDecimalSeparator('.');
StringHelper::setThousandsSeparator(' ');
StringHelper::setCurrencyCode('$');
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($value === 'omitted') {
$sheet->getCell('B1')->setValue('=VALUE()');
} else {
$this->setCell('A1', $value);
$sheet->getCell('B1')->setValue('=VALUE(A1)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEqualsWithDelta($expectedResult, $result, 1E-8);
}
public static function providerVALUE(): array
{
return require 'tests/data/Calculation/TextData/VALUE.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerValueArray')]
public function testValueArray(array $expectedResult, string $argument): void
{
$calculation = Calculation::getInstance();
$formula = "=VALUE({$argument})";
$result = $calculation->calculateFormula($formula);
self::assertEqualsWithDelta($expectedResult, $result, 1.0e-14);
}
public static function providerValueArray(): array
{
return [
'row vector' => [[[44604, -1234.567]], '{"12-Feb-2022", "$ -1,234.567"}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/SearchTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/SearchTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\Attributes\DataProvider;
class SearchTest extends AllSetupTeardown
{
#[DataProvider('providerSEARCH')]
public function testSEARCH(mixed $expectedResult, mixed $findText = 'omitted', mixed $withinText = 'omitted', mixed $start = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($findText === 'omitted') {
$sheet->getCell('B1')->setValue('=SEARCH()');
} elseif ($withinText === 'omitted') {
$this->setCell('A1', $findText);
$sheet->getCell('B1')->setValue('=SEARCH(A1)');
} elseif ($start === 'omitted') {
$this->setCell('A1', $findText);
$this->setCell('A2', $withinText);
$sheet->getCell('B1')->setValue('=SEARCH(A1, A2)');
} else {
$this->setCell('A1', $findText);
$this->setCell('A2', $withinText);
$this->setCell('A3', $start);
$sheet->getCell('B1')->setValue('=SEARCH(A1, A2, A3)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerSEARCH(): array
{
return require 'tests/data/Calculation/TextData/SEARCH.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerSearchArray')]
public function testSearchArray(array $expectedResult, string $argument1, string $argument2): void
{
$calculation = Calculation::getInstance();
$formula = "=SEARCH({$argument1}, {$argument2})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerSearchArray(): array
{
return [
'row vector #1' => [[[3, 4, '#VALUE!']], '"L"', '{"Hello", "World", "PhpSpreadsheet"}'],
'column vector #1' => [[[3], [4], ['#VALUE!']], '"L"', '{"Hello"; "World"; "PhpSpreadsheet"}'],
'matrix #1' => [[[3, 4], ['#VALUE!', 5]], '"L"', '{"Hello", "World"; "PhpSpreadsheet", "Excel"}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CleanTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CleanTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\Attributes\DataProvider;
class CleanTest extends AllSetupTeardown
{
#[DataProvider('providerCLEAN')]
public function testCLEAN(mixed $expectedResult, mixed $value = 'omitted'): void
{
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
if ($value === 'omitted') {
$sheet->getCell('B1')->setValue('=CLEAN()');
} else {
$this->setCell('A1', $value);
$sheet->getCell('B1')->setValue('=CLEAN(A1)');
}
$result = $sheet->getCell('B1')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerCLEAN(): array
{
return require 'tests/data/Calculation/TextData/CLEAN.php';
}
/** @param mixed[] $expectedResult */
#[DataProvider('providerCleanArray')]
public function testCleanArray(array $expectedResult, string $array): void
{
$calculation = Calculation::getInstance();
$formula = "=CLEAN({$array})";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerCleanArray(): array
{
return [
'row vector' => [[['PHP', 'MS Excel', 'Open/Libre Office']], '{"PHP", "MS Excel", "Open/Libre Office"}'],
'column vector' => [[['PHP'], ['MS Excel'], ['Open/Libre Office']], '{"PHP"; "MS Excel"; "Open/Libre Office"}'],
'matrix' => [[['PHP', 'MS Excel'], ['PhpSpreadsheet', 'Open/Libre Office']], '{"PHP", "MS Excel"; "PhpSpreadsheet", "Open/Libre Office"}'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CharNonPrintableTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/TextData/CharNonPrintableTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\TextData;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class CharNonPrintableTest extends AbstractFunctional
{
#[\PHPUnit\Framework\Attributes\DataProvider('providerType')]
public function testNotPrintable(string $type): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('B1')->setValue('=CHAR(2)');
$sheet->getCell('C1')->setValue('=CHAR(127)');
$hello = "hello\nthere";
$sheet->getCell('D2')->setValue($hello);
$sheet->getCell('D1')->setValue('=D2');
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $type);
$result = $reloadedSpreadsheet->getActiveSheet()->getCell('B1')->getCalculatedValue();
self::assertEquals("\x02", $result);
$result = $reloadedSpreadsheet->getActiveSheet()->getCell('C1')->getCalculatedValue();
self::assertEquals("\x7f", $result);
$result = $reloadedSpreadsheet->getActiveSheet()->getCell('D1')->getCalculatedValue();
self::assertEquals($hello, $result);
$spreadsheet->disconnectWorksheets();
$reloadedSpreadsheet->disconnectWorksheets();
}
public static function providerType(): array
{
return [
['Xlsx'],
['Xls'],
//['Ods'], // no support yet in Reader or Writer
// without csv suffix, Reader/Csv decides type via mime_get_type,
// and control character makes it guess application/octet-stream,
// so Reader/Csv decides it can't read it.
//['Csv'],
// DOMDocument.loadHTML() rejects '' even though legal html.
//['Html'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Engine/StructuredReferenceSlashTest.php | tests/PhpSpreadsheetTests/Calculation/Engine/StructuredReferenceSlashTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Engine;
use PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands\StructuredReference;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
use PHPUnit\Framework\TestCase;
class StructuredReferenceSlashTest extends TestCase
{
protected ?Spreadsheet $spreadSheet;
protected const COLUMN_FORMULA = '=[@Sales Amount]*[@[% Commission]]';
// Note that column headings may contain a non-breaking space, while the formula may not;
// these still need to match.
// As compared to StructuredReferenceTest, the last column
// "Commission/Amount" contains a slash. See PR #3513.
protected const TABLE_DATA = [
["Sales\u{a0}Person", 'Region', "Sales\u{a0}Amount", "%\u{a0}Commission", 'Commission/Amount'],
['Joe', 'North', 260, '10%', self::COLUMN_FORMULA],
['Robert', 'South', 660, '15%', self::COLUMN_FORMULA],
['Michelle', 'East', 940, '15%', self::COLUMN_FORMULA],
['Erich', 'West', 410, '12%', self::COLUMN_FORMULA],
['Dafna', 'North', 800, '15%', self::COLUMN_FORMULA],
['Rob', 'South', 900, '15%', self::COLUMN_FORMULA],
['Total'],
];
protected function getSpreadsheet(): Spreadsheet
{
$spreadsheet = $this->spreadSheet = new Spreadsheet();
$workSheet = $spreadsheet->getActiveSheet();
$workSheet->fromArray(self::TABLE_DATA, null, 'A1');
$table = new Table('A1:E8', 'DeptSales');
$table->setShowTotalsRow(true);
$table->getColumn('A')->setTotalsRowLabel('Total');
$workSheet->addTable($table);
return $spreadsheet;
}
protected function tearDown(): void
{
if ($this->spreadSheet !== null) {
$this->spreadSheet->disconnectWorksheets();
$this->spreadSheet = null;
}
parent::tearDown();
}
#[\PHPUnit\Framework\Attributes\DataProvider('structuredReferenceProviderColumnData')]
public function testStructuredReferenceColumns(string $expectedCellRange, string $structuredReference): void
{
$spreadsheet = $this->getSpreadsheet();
$structuredReferenceObject = new StructuredReference($structuredReference);
$cellRange = $structuredReferenceObject->parse($spreadsheet->getActiveSheet()->getCell('E5'));
self::assertSame($expectedCellRange, $cellRange);
}
#[\PHPUnit\Framework\Attributes\DataProvider('structuredReferenceProviderRowData')]
public function testStructuredReferenceRows(string $expectedCellRange, string $structuredReference): void
{
$spreadsheet = $this->getSpreadsheet();
$structuredReferenceObject = new StructuredReference($structuredReference);
$cellRange = $structuredReferenceObject->parse($spreadsheet->getActiveSheet()->getCell('E5'));
self::assertSame($expectedCellRange, $cellRange);
}
public static function structuredReferenceProviderColumnData(): array
{
return [
// Full table, with no column specified, means data only, not headers or totals
'Full table Unqualified' => ['A2:E7', '[]'],
'Full table Qualified' => ['A2:E7', 'DeptSales[]'],
// No item identifier, but with a column identifier, means data and header for the column, but no totals
'Column with no Item Identifier #1' => ['A2:A7', 'DeptSales[[Sales Person]]'],
'Column with no Item Identifier #2' => ['B2:B7', 'DeptSales[Region]'],
// Item identifier with no column specified
'Item Identifier only #1' => ['A1:E1', 'DeptSales[#Headers]'],
'Item Identifier only #2' => ['A1:E1', 'DeptSales[[#Headers]]'],
'Item Identifier only #3' => ['A8:E8', 'DeptSales[#Totals]'],
'Item Identifier only #4' => ['A2:E7', 'DeptSales[#Data]'],
// Item identifiers and column identifiers
'Full column' => ['C1:C8', 'DeptSales[[#All],[Sales Amount]]'],
'Column Header' => ['D1', 'DeptSales[[#Headers],[% Commission]]'],
'Column Total' => ['B8', 'DeptSales[[#Totals],[Region]]'],
'Column Range All' => ['C1:D8', 'DeptSales[[#All],[Sales Amount]:[% Commission]]'],
'Column Range Data' => ['D2:E7', 'DeptSales[[#Data],[% Commission]:[Commission/Amount]]'],
'Column Range Headers' => ['B1:E1', 'DeptSales[[#Headers],[Region]:[Commission/Amount]]'],
'Column Range Totals' => ['C8:E8', 'DeptSales[[#Totals],[Sales Amount]:[Commission/Amount]]'],
'Column Range Headers and Data' => ['D1:D7', 'DeptSales[[#Headers],[#Data],[% Commission]]'],
'Column Range No Item Identifier' => ['A2:B7', 'DeptSales[[Sales Person]:[Region]]'],
// ['C2:C7,E2:E7', 'DeptSales[Sales Amount],DeptSales[Commission Amount]'],
// ['B2:C7', 'DeptSales[[Sales Person]:[Sales Amount]] DeptSales[[Region]:[% Commission]]'],
];
}
public static function structuredReferenceProviderRowData(): array
{
return [
['E5', 'DeptSales[[#This Row], [Commission/Amount]]'],
['E5', 'DeptSales[@Commission/Amount]'],
['E5', 'DeptSales[@[Commission/Amount]]'],
['C5:D5', 'DeptSales[@[Sales Amount]:[% Commission]]'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Engine/StructuredReferenceTest.php | tests/PhpSpreadsheetTests/Calculation/Engine/StructuredReferenceTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Engine;
use PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands\StructuredReference;
use PhpOffice\PhpSpreadsheet\Calculation\Exception;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
use PHPUnit\Framework\TestCase;
class StructuredReferenceTest extends TestCase
{
protected Spreadsheet $spreadSheet;
protected const COLUMN_FORMULA = '=[@Sales Amount]*[@[% Commission]]';
// Note that column headings may contain a non-breaking space, while the formula may not;
// these still need to match.
protected const TABLE_DATA = [
["Sales\u{a0}Person", 'Region', "Sales\u{a0}Amount", "%\u{a0}Commission", "Commission\u{a0}Amount"],
['Joe', 'North', 260, '10%', self::COLUMN_FORMULA],
['Robert', 'South', 660, '15%', self::COLUMN_FORMULA],
['Michelle', 'East', 940, '15%', self::COLUMN_FORMULA],
['Erich', 'West', 410, '12%', self::COLUMN_FORMULA],
['Dafna', 'North', 800, '15%', self::COLUMN_FORMULA],
['Rob', 'South', 900, '15%', self::COLUMN_FORMULA],
['Total'],
];
protected function setUp(): void
{
parent::setUp();
$this->spreadSheet = new Spreadsheet();
$workSheet = $this->spreadSheet->getActiveSheet();
$workSheet->fromArray(self::TABLE_DATA, null, 'A1');
$table = new Table('A1:E8', 'DeptSales');
$table->setShowTotalsRow(true);
$table->getColumn('A')->setTotalsRowLabel('Total');
$workSheet->addTable($table);
}
protected function tearDown(): void
{
$this->spreadSheet->disconnectWorksheets();
parent::tearDown();
}
public function testStructuredReferenceInvalidTable(): void
{
$cell = $this->spreadSheet->getActiveSheet()->getCell('H5');
$this->expectException(Exception::class);
$this->expectExceptionMessage('Table SalesResults for Structured Reference cannot be located');
$structuredReferenceObject = new StructuredReference('SalesResults[@[% Commission]]');
$structuredReferenceObject->parse($cell);
}
public function testStructuredReferenceInvalidCellForTable(): void
{
$cell = $this->spreadSheet->getActiveSheet()->getCell('H99');
$this->expectException(Exception::class);
$this->expectExceptionMessage('Table for Structured Reference cannot be identified');
$structuredReferenceObject = new StructuredReference('[@[% Commission]]');
$structuredReferenceObject->parse($cell);
}
#[\PHPUnit\Framework\Attributes\DataProvider('structuredReferenceProviderColumnData')]
public function testStructuredReferenceColumns(string $expectedCellRange, string $structuredReference): void
{
$cell = $this->spreadSheet->getActiveSheet()->getCell('E5');
$structuredReferenceObject = new StructuredReference($structuredReference);
$cellRange = $structuredReferenceObject->parse($cell);
self::assertSame($expectedCellRange, $cellRange);
}
#[\PHPUnit\Framework\Attributes\DataProvider('structuredReferenceProviderRowData')]
public function testStructuredReferenceRows(string $expectedCellRange, string $structuredReference): void
{
$cell = $this->spreadSheet->getActiveSheet()->getCell('E5');
$structuredReferenceObject = new StructuredReference($structuredReference);
$cellRange = $structuredReferenceObject->parse($cell);
self::assertSame($expectedCellRange, $cellRange);
}
public function testInvalidStructuredReferenceRow(): void
{
$cell = $this->spreadSheet->getActiveSheet()->getCell('E5');
$this->expectException(Exception::class);
$this->expectExceptionCode(1);
$this->expectExceptionMessage('Invalid Structured Reference');
$this->expectExceptionCode(Exception::CALCULATION_ENGINE_PUSH_TO_STACK);
$structuredReferenceObject = new StructuredReference('DeptSales[@[Sales]:[%age Commission]]');
$structuredReferenceObject->parse($cell);
}
public function testStructuredReferenceHeadersHidden(): void
{
$cell = $this->spreadSheet->getActiveSheet()->getCell('K1');
$table = $this->spreadSheet->getActiveSheet()->getTableByName('DeptSales');
/** @var Table $table */
$structuredReferenceObject = new StructuredReference('DeptSales[[#Headers],[% Commission]]');
$cellRange = $structuredReferenceObject->parse($cell);
self::assertSame('D1', $cellRange);
$table->setShowHeaderRow(false);
$this->expectException(Exception::class);
$this->expectExceptionMessage('Table Headers are Hidden, and should not be Referenced');
$this->expectExceptionCode(Exception::CALCULATION_ENGINE_PUSH_TO_STACK);
$structuredReferenceObject = new StructuredReference('DeptSales[[#Headers],[% Commission]]');
$structuredReferenceObject->parse($cell);
}
public static function structuredReferenceProviderColumnData(): array
{
return [
// Full table, with no column specified, means data only, not headers or totals
'Full table Unqualified' => ['A2:E7', '[]'],
'Full table Qualified' => ['A2:E7', 'DeptSales[]'],
// No item identifier, but with a column identifier, means data and header for the column, but no totals
'Column with no Item Identifier #1' => ['A2:A7', 'DeptSales[[Sales Person]]'],
'Column with no Item Identifier #2' => ['B2:B7', 'DeptSales[Region]'],
// Item identifier with no column specified
'Item Identifier only #1' => ['A1:E1', 'DeptSales[#Headers]'],
'Item Identifier only #2' => ['A1:E1', 'DeptSales[[#Headers]]'],
'Item Identifier only #3' => ['A8:E8', 'DeptSales[#Totals]'],
'Item Identifier only #4' => ['A2:E7', 'DeptSales[#Data]'],
// Item identifiers and column identifiers
'Full column' => ['C1:C8', 'DeptSales[[#All],[Sales Amount]]'],
'Column Header' => ['D1', 'DeptSales[[#Headers],[% Commission]]'],
'Column Total' => ['B8', 'DeptSales[[#Totals],[Region]]'],
'Column Range All' => ['C1:D8', 'DeptSales[[#All],[Sales Amount]:[% Commission]]'],
'Column Range Data' => ['D2:E7', 'DeptSales[[#Data],[% Commission]:[Commission Amount]]'],
'Column Range Headers' => ['B1:E1', 'DeptSales[[#Headers],[Region]:[Commission Amount]]'],
'Column Range Totals' => ['C8:E8', 'DeptSales[[#Totals],[Sales Amount]:[Commission Amount]]'],
'Column Range Headers and Data' => ['D1:D7', 'DeptSales[[#Headers],[#Data],[% Commission]]'],
'Column Range No Item Identifier' => ['A2:B7', 'DeptSales[[Sales Person]:[Region]]'],
// ['C2:C7,E2:E7', 'DeptSales[Sales Amount],DeptSales[Commission Amount]'],
// ['B2:C7', 'DeptSales[[Sales Person]:[Sales Amount]] DeptSales[[Region]:[% Commission]]'],
];
}
public static function structuredReferenceProviderRowData(): array
{
return [
['E5', 'DeptSales[[#This Row], [Commission Amount]]'],
['E5', 'DeptSales[@Commission Amount]'],
['E5', 'DeptSales[@[Commission Amount]]'],
['C5:D5', 'DeptSales[@[Sales Amount]:[% Commission]]'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Engine/RangeTest.php | tests/PhpSpreadsheetTests/Calculation/Engine/RangeTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Engine;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class RangeTest extends TestCase
{
private ?Spreadsheet $spreadSheet = null;
protected function getSpreadsheet(): Spreadsheet
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()
->fromArray(array_chunk(range(1, 240), 6), null, 'A1', true);
return $spreadsheet;
}
protected function tearDown(): void
{
if ($this->spreadSheet !== null) {
$this->spreadSheet->disconnectWorksheets();
$this->spreadSheet = null;
}
}
#[DataProvider('providerRangeEvaluation')]
public function testRangeEvaluation(string $formula, int|string $expectedResult): void
{
$this->spreadSheet = $this->getSpreadsheet();
$workSheet = $this->spreadSheet->getActiveSheet();
$workSheet->setCellValue('H1', $formula);
$actualRresult = $workSheet->getCell('H1')->getCalculatedValue();
self::assertSame($expectedResult, $actualRresult);
}
public static function providerRangeEvaluation(): array
{
return [
'Sum with Simple Range' => ['=SUM(A1:C3)', 72],
'Count with Simple Range' => ['=COUNT(A1:C3)', 9],
'Sum with UNION #1' => ['=SUM(A1:B3,A1:C2)', 75],
'Count with UNION #1' => ['=COUNT(A1:B3,A1:C2)', 12],
'Sum with INTERSECTION #1' => ['=SUM(A1:B3 A1:C2)', 18],
'Count with INTERSECTION #1' => ['=COUNT(A1:B3 A1:C2)', 4],
'Sum with UNION #2' => ['=SUM(A1:A3,C1:C3)', 48],
'Count with UNION #2' => ['=COUNT(A1:A3,C1:C3)', 6],
'Sum with INTERSECTION #2 - No Intersect' => ['=SUM(A1:A3 C1:C3)', ExcelError::null()],
'Count with INTERSECTION #2 - No Intersect' => ['=COUNT(A1:A3 C1:C3)', 0],
'Sum with UNION #3' => ['=SUM(A1:B2,B2:C3)', 64],
'Count with UNION #3' => ['=COUNT(A1:B2,B2:C3)', 8],
'Sum with INTERSECTION #3 - Single Cell' => ['=SUM(A1:B2 B2:C3)', 8],
'Count with INTERSECTION #3 - Single Cell' => ['=COUNT(A1:B2 B2:C3)', 1],
'Sum with Triple UNION' => ['=SUM(A1:C1,A3:C3,B1:C3)', 99],
'Count with Triple UNION' => ['=COUNT(A1:C1,A3:C3,B1:C3)', 12],
'Sum with UNION and INTERSECTION' => ['=SUM(A1:C1,A3:C3 B1:C3)', 35],
'Count with UNION and INTERSECTION' => ['=COUNT(A1:C1,A3:C3 B1:C3)', 5],
'Sum with UNION with Worksheet Reference' => ['=SUM(Worksheet!A1:B3,Worksheet!A1:C2)', 75],
'Sum with UNION with full Worksheet Reference' => ['=SUM(Worksheet!A1:Worksheet!B3,Worksheet!A1:Worksheet!C2)', 75],
'Sum with Chained UNION #1' => ['=SUM(A3:B1:C2)', 72],
'Count with Chained UNION #1' => ['=COUNT(A3:B1:C2)', 9],
'Sum with Chained UNION #2' => ['=SUM(A5:C10:C20:F1)', 7260],
'Count with Chained UNION#2' => ['=COUNT(A5:C10:C20:F1)', 120],
];
}
public function test3dRangeParsing(): void
{
// This test shows that parsing throws exception.
// Next test shows that formula is still treated as a formula
// despite the parse failure.
$this->expectExceptionMessage('3D Range references are not yet supported');
$calculation = new Calculation();
$calculation->disableBranchPruning();
$calculation->parseFormula('=SUM(Worksheet!A1:Worksheet2!B3');
}
public function test3dRangeEvaluation(): void
{
$this->spreadSheet = $this->getSpreadsheet();
$workSheet = $this->spreadSheet->getActiveSheet();
$workSheet->setCellValue('E1', '=SUM(Worksheet!A1:Worksheet2!B3)');
$this->expectExceptionMessage('3D Range references are not yet supported');
$workSheet->getCell('E1')->getCalculatedValue();
}
/** @param string[] $ranges */
#[DataProvider('providerNamedRangeEvaluation')]
public function testNamedRangeEvaluation(array $ranges, string $formula, int $expectedResult): void
{
$this->spreadSheet = $this->getSpreadsheet();
$workSheet = $this->spreadSheet->getActiveSheet();
foreach ($ranges as $id => $range) {
$this->spreadSheet->addNamedRange(new NamedRange('GROUP' . ++$id, $workSheet, $range));
}
$workSheet->setCellValue('H1', $formula);
$sumRresult = $workSheet->getCell('H1')->getCalculatedValue();
self::assertSame($expectedResult, $sumRresult);
}
public static function providerNamedRangeEvaluation(): array
{
return [
[['$A$1:$B$3', '$A$1:$C$2'], '=SUM(GROUP1,GROUP2)', 75],
[['$A$1:$B$3', '$A$1:$C$2'], '=COUNT(GROUP1,GROUP2)', 12],
[['$A$1:$B$3', '$A$1:$C$2'], '=SUM(GROUP1 GROUP2)', 18],
[['$A$1:$B$3', '$A$1:$C$2'], '=COUNT(GROUP1 GROUP2)', 4],
[['$A$1:$B$2', '$B$2:$C$3'], '=SUM(GROUP1,GROUP2)', 64],
[['$A$1:$B$2', '$B$2:$C$3'], '=COUNT(GROUP1,GROUP2)', 8],
[['$A$1:$B$2', '$B$2:$C$3'], '=SUM(GROUP1 GROUP2)', 8],
[['$A$1:$B$2', '$B$2:$C$3'], '=COUNT(GROUP1 GROUP2)', 1],
[['$A$5', '$C$10:$C$20', '$F$1'], '=SUM(GROUP1:GROUP2:GROUP3)', 7260],
[['$A$5:$A$7', '$C$20', '$F$1'], '=SUM(GROUP1:GROUP2:GROUP3)', 7260],
[['$A$5:$A$7', '$C$10:$C$20', '$F$1'], '=SUM(GROUP1:GROUP2:GROUP3)', 7260],
[['Worksheet!$A$1:$B$2', 'Worksheet!$B$2:$C$3'], '=SUM(GROUP1,GROUP2)', 64],
[['Worksheet!$A$1:Worksheet!$B$2', 'Worksheet!$B$2:Worksheet!$C$3'], '=SUM(GROUP1,GROUP2)', 64],
];
}
/**
* @param string[] $names
* @param string[] $ranges
*/
#[DataProvider('providerUTF8NamedRangeEvaluation')]
public function testUTF8NamedRangeEvaluation(array $names, array $ranges, string $formula, int $expectedResult): void
{
$this->spreadSheet = $this->getSpreadsheet();
$workSheet = $this->spreadSheet->getActiveSheet();
foreach ($names as $index => $name) {
$range = $ranges[$index];
$this->spreadSheet->addNamedRange(new NamedRange($name, $workSheet, $range));
}
$workSheet->setCellValue('E1', $formula);
$sumRresult = $workSheet->getCell('E1')->getCalculatedValue();
self::assertSame($expectedResult, $sumRresult);
}
public static function providerUTF8NamedRangeEvaluation(): array
{
return [
[['Γειά', 'σου', 'Κόσμε'], ['$A$1', '$B$1:$B$2', '$C$1:$C$3'], '=SUM(Γειά,σου,Κόσμε)', 38],
[['Γειά', 'σου', 'Κόσμε'], ['$A$1', '$B$1:$B$2', '$C$1:$C$3'], '=COUNT(Γειά,σου,Κόσμε)', 6],
[['Здравствуй', 'мир'], ['$A$1:$A$3', '$C$1:$C$3'], '=SUM(Здравствуй,мир)', 48],
];
}
#[DataProvider('providerCompositeNamedRangeEvaluation')]
public function testCompositeNamedRangeEvaluation(string $composite, int $expectedSum, int $expectedCount): void
{
$this->spreadSheet = $this->getSpreadsheet();
$workSheet = $this->spreadSheet->getActiveSheet();
$this->spreadSheet->addNamedRange(new NamedRange('COMPOSITE', $workSheet, $composite));
$workSheet->setCellValue('E1', '=SUM(COMPOSITE)');
$workSheet->setCellValue('E2', '=COUNT(COMPOSITE)');
$actualSum = $workSheet->getCell('E1')->getCalculatedValue();
self::assertSame($expectedSum, $actualSum);
$actualCount = $workSheet->getCell('E2')->getCalculatedValue();
self::assertSame($expectedCount, $actualCount);
}
public static function providerCompositeNamedRangeEvaluation(): array
{
return [
'Union with overlap' => [
'$A$1:$C$1,$A$3:$C$3,$B$1:$C$3',
99,
12,
],
'Union and Intersection' => [
'$A$1:$C$1,$A$3:$C$3 $B$1:$C$3',
35,
5,
],
];
}
public function testIntersectCellFormula(): void
{
$this->spreadSheet = $this->getSpreadsheet();
$sheet = $this->spreadSheet->getActiveSheet();
$array = [
[null, 'Planets', 'Lives', 'Babies'],
['Batman', 5, 10, 4],
['Superman', 4, 56, 34],
['Spiderman', 23, 45, 67],
['Hulk', 12, 34, 58],
['Steve', 10, 34, 78],
];
$sheet->fromArray($array, null, 'A3', true);
$this->spreadSheet->addNamedRange(new NamedRange('Hulk', $sheet, '$B$7:$D$7'));
$this->spreadSheet->addNamedRange(new NamedRange('Planets', $sheet, '$B$4:$B$8'));
$this->spreadSheet->addNamedRange(new NamedRange('Intersect', $sheet, '$A$6:$D$6 $C$4:$C$8'));
$this->spreadSheet->addNamedRange(new NamedRange('SupHulk', $sheet, '$B$5:$D$5,$B$7:$D$7'));
$sheet->setCellValue('F1', '=Intersect');
$sheet->setCellValue('F2', '=SUM(SupHulk)');
$sheet->setCellValue('F3', '=Planets Hulk');
$sheet->setCellValue('F4', '=B4:D4 B4:C5');
$this->spreadSheet->returnArrayAsArray();
self::assertSame(45, $sheet->getCell('F1')->getCalculatedValue());
self::assertSame(198, $sheet->getCell('F2')->getCalculatedValue());
self::assertSame(12, $sheet->getCell('F3')->getCalculatedValue());
self::assertSame([[5, 10]], $sheet->getCell('F4')->getCalculatedValue());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Engine/FormattedNumberTest.php | tests/PhpSpreadsheetTests/Calculation/Engine/FormattedNumberTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Engine;
use PhpOffice\PhpSpreadsheet\Calculation\Engine\FormattedNumber;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class FormattedNumberTest extends TestCase
{
#[DataProvider('providerNumbers')]
public function testNumber(mixed $expected, string $value): void
{
FormattedNumber::convertToNumberIfFormatted($value);
self::assertSame($expected, $value);
}
public static function providerNumbers(): array
{
return [
[-12.5, '-12.5'],
[-125.0, '-1.25e2'],
[0.125, '12.5%'],
[1234.5, '1,234.5'],
[-1234.5, '- 1,234.5'],
[1234.5, '+ 1,234.5'],
];
}
#[DataProvider('providerFractions')]
public function testFraction(string $expected, string $value): void
{
$originalValue = $value;
$result = FormattedNumber::convertToNumberIfFraction($value);
if ($result === false) {
self::assertSame($expected, $originalValue);
self::assertSame($expected, $value);
} else {
self::assertSame($expected, (string) $value);
self::assertNotEquals($value, $originalValue);
}
}
public static function providerFractions(): array
{
return [
'non-fraction' => ['1', '1'],
'common fraction' => ['1.5', '1 1/2'],
'fraction between -1 and 0' => ['-0.5', '-1/2'],
'fraction between -1 and 0 with space' => ['-0.5', ' - 1/2'],
'fraction between 0 and 1' => ['0.75', '3/4 '],
'fraction between 0 and 1 with space' => ['0.75', ' 3/4'],
'improper fraction' => ['1.75', '7/4'],
];
}
#[DataProvider('providerPercentages')]
public function testPercentage(string $expected, string $value): void
{
$originalValue = $value;
$result = FormattedNumber::convertToNumberIfPercent($value);
if ($result === false) {
self::assertSame($expected, $originalValue);
self::assertSame($expected, $value);
} else {
self::assertSame($expected, (string) $value);
self::assertNotEquals($value, $originalValue);
}
}
public static function providerPercentages(): array
{
return [
'non-percentage' => ['10', '10'],
'single digit percentage' => ['0.02', '2%'],
'two digit percentage' => ['0.13', '13%'],
'negative single digit percentage' => ['-0.07', '-7%'],
'negative two digit percentage' => ['-0.75', '-75%'],
'large percentage' => ['98.45', '9845%'],
'small percentage' => ['0.0005', '0.05%'],
'percentage with decimals' => ['0.025', '2.5%'],
'trailing percent with space' => ['0.02', '2 %'],
'trailing percent with leading and trailing space' => ['0.02', ' 2 % '],
'leading percent with decimals' => ['0.025', ' % 2.5'],
'Percentage with thousands separator' => ['12.345', ' % 1,234.5'],
//These should all fail
'percent only' => ['%', '%'],
'nonsense percent' => ['2%2', '2%2'],
'negative leading percent' => ['-0.02', '-%2'],
//Percent position permutations
'permutation_1' => ['0.02', '2%'],
'permutation_2' => ['0.02', ' 2%'],
'permutation_3' => ['0.02', '2% '],
'permutation_4' => ['0.02', ' 2 % '],
'permutation_5' => ['0.0275', '2.75% '],
'permutation_6' => ['0.0275', ' 2.75% '],
'permutation_7' => ['0.0275', ' 2.75 % '],
'permutation_8' => [' 2 . 75 %', ' 2 . 75 %'],
'permutation_9' => [' 2.7 5 % ', ' 2.7 5 % '],
'permutation_10' => ['-0.02', '-2%'],
'permutation_11' => ['-0.02', ' -2% '],
'permutation_12' => ['-0.02', '- 2% '],
'permutation_13' => ['-0.02', '-2 % '],
'permutation_14' => ['-0.0275', '-2.75% '],
'permutation_15' => ['-0.0275', ' -2.75% '],
'permutation_16' => ['-0.0275', '-2.75 % '],
'permutation_17' => ['-0.0275', ' - 2.75 % '],
'permutation_18' => ['0.02', '2%'],
'permutation_19' => ['0.02', '% 2 '],
'permutation_20' => ['0.02', ' %2 '],
'permutation_21' => ['0.02', ' % 2 '],
'permutation_22' => ['0.0275', '%2.75 '],
'permutation_23' => ['0.0275', ' %2.75 '],
'permutation_24' => ['0.0275', ' % 2.75 '],
'permutation_25' => [' %2 . 75 ', ' %2 . 75 '],
'permutation_26' => [' %2.7 5 ', ' %2.7 5 '],
'permutation_27' => [' % 2 . 75 ', ' % 2 . 75 '],
'permutation_28' => [' % 2.7 5 ', ' % 2.7 5 '],
'permutation_29' => ['-0.0275', '-%2.75 '],
'permutation_30' => ['-0.0275', ' - %2.75 '],
'permutation_31' => ['-0.0275', '- % 2.75 '],
'permutation_32' => ['-0.0275', ' - % 2.75 '],
'permutation_33' => ['0.02', '2%'],
'permutation_34' => ['0.02', '2 %'],
'permutation_35' => ['0.02', ' 2%'],
'permutation_36' => ['0.02', ' 2 % '],
'permutation_37' => ['0.0275', '2.75%'],
'permutation_38' => ['0.0275', ' 2.75 % '],
'permutation_39' => ['2 . 75 % ', '2 . 75 % '],
'permutation_40' => ['-0.0275', '-2.75% '],
'permutation_41' => ['-0.0275', '- 2.75% '],
'permutation_42' => ['-0.0275', ' - 2.75% '],
'permutation_43' => ['-0.0275', ' -2.75 % '],
'permutation_44' => ['-2. 75 % ', '-2. 75 % '],
'permutation_45' => ['%', '%'],
'permutation_46' => ['0.02', '%2 '],
'permutation_47' => ['0.02', '% 2 '],
'permutation_48' => ['0.02', ' %2 '],
'permutation_49' => ['0.02', '% 2 '],
'permutation_50' => ['0.02', ' % 2 '],
'permutation_51' => ['0.02', ' 2 % '],
'permutation_52' => ['-0.02', '-2%'],
'permutation_53' => ['-0.02', '- %2'],
'permutation_54' => ['-0.02', ' -%2 '],
'permutation_55' => ['2%2', '2%2'],
'permutation_56' => [' 2% %', ' 2% %'],
'permutation_57' => [' % 2 -', ' % 2 -'],
'permutation_58' => ['-0.02', '%-2'],
'permutation_59' => ['-0.02', ' % - 2'],
'permutation_60' => ['-0.0275', '%-2.75 '],
'permutation_61' => ['-0.0275', ' % - 2.75 '],
'permutation_62' => ['-0.0275', ' % - 2.75 '],
'permutation_63' => ['-0.0275', ' % - 2.75 '],
'permutation_64' => ['0.0275', ' % + 2.75 '],
'permutation_65' => ['0.0275', ' % + 2.75 '],
'permutation_66' => ['0.0275', ' % + 2.75 '],
'permutation_67' => ['0.02', '+2%'],
'permutation_68' => ['0.02', ' +2% '],
'permutation_69' => ['0.02', '+ 2% '],
'permutation_70' => ['0.02', '+2 % '],
'permutation_71' => ['0.0275', '+2.75% '],
'permutation_72' => ['0.0275', ' +2.75% '],
'permutation_73' => ['0.0275', '+2.75 % '],
'permutation_74' => ['0.0275', ' + 2.75 % '],
'permutation_75' => ['-2.5E-6', '-2.5E-4%'],
'permutation_76' => ['200', '2E4%'],
'permutation_77' => ['-2.5E-8', '-%2.50E-06'],
'permutation_78' => [' - % 2.50 E -06 ', ' - % 2.50 E -06 '],
'permutation_79' => ['-2.5E-8', ' - % 2.50E-06 '],
'permutation_80' => ['-2.5E-8', ' - % 2.50E- 06 '],
'permutation_81' => [' - % 2.50E - 06 ', ' - % 2.50E - 06 '],
'permutation_82' => ['-2.5E-6', '-2.5e-4%'],
'permutation_83' => ['200', '2e4%'],
'permutation_84' => ['-2.5E-8', '-%2.50e-06'],
'permutation_85' => [' - % 2.50 e -06 ', ' - % 2.50 e -06 '],
'permutation_86' => ['-2.5E-8', ' - % 2.50e-06 '],
'permutation_87' => ['-2.5E-8', ' - % 2.50e- 06 '],
'permutation_88' => [' - % 2.50e - 06 ', ' - % 2.50e - 06 '],
];
}
#[DataProvider('providerCurrencies')]
public function testCurrencies(string $expected, string $value): void
{
$originalValue = $value;
$result = FormattedNumber::convertToNumberIfCurrency($value);
if ($result === false) {
self::assertSame($expected, $originalValue);
self::assertSame($expected, $value);
} else {
self::assertSame($expected, (string) $value);
self::assertNotEquals($value, $originalValue);
}
}
public static function providerCurrencies(): array
{
$currencyCode = StringHelper::getCurrencyCode();
return [
'basic_prefix_currency' => ['2.75', "{$currencyCode}2.75"],
'basic_postfix_currency' => ['2.75', "2.75{$currencyCode}"],
'basic_prefix_currency_with_spaces' => ['2.75', "{$currencyCode} 2.75"],
'basic_postfix_currency_with_spaces' => ['2.75', "2.75 {$currencyCode}"],
'negative_basic_prefix_currency' => ['-2.75', "-{$currencyCode}2.75"],
'negative_basic_postfix_currency' => ['-2.75', "-2.75{$currencyCode}"],
'negative_basic_prefix_currency_with_spaces' => ['-2.75', "-{$currencyCode} 2.75"],
'negative_basic_postfix_currency_with_spaces' => ['-2.75', "-2.75 {$currencyCode}"],
'positive_signed_prefix_currency_with_spaces' => ['2.75', "+{$currencyCode} 2.75"],
'positive_signed_prefix_currency_with_spaces-2' => ['2.75', "{$currencyCode} +2.75"],
'positive_signed_postfix_currency_with_spaces' => ['2.75', "+2.75 {$currencyCode}"],
'basic_prefix_scientific_currency' => ['2000000', "{$currencyCode}2E6"],
'basic_postfix_scientific_currency' => ['2000000', "2E6{$currencyCode}"],
'basic_prefix_scientific_currency_with_spaces' => ['2000000', "{$currencyCode} 2E6"],
'basic_postfix_scientific_currency_with_spaces' => ['2000000', "2E6 {$currencyCode}"],
'high_value_currency_with_thousands_separator' => ['2750000', "+{$currencyCode} 2,750,000"],
'explicit dollar' => ['2.75', '$2.75'],
'explicit euro' => ['2.75', '2.75€'],
'explicit pound sterling' => ['2.75', '£2.75'],
'explicit yen' => ['275', '¥275'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Engine/FormattedNumberSlashTest.php | tests/PhpSpreadsheetTests/Calculation/Engine/FormattedNumberSlashTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Engine;
use PhpOffice\PhpSpreadsheet\Calculation\Engine\FormattedNumber;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class FormattedNumberSlashTest extends TestCase
{
protected function tearDown(): void
{
StringHelper::setCurrencyCode(null);
StringHelper::setDecimalSeparator(null);
StringHelper::setThousandsSeparator(null);
}
#[DataProvider('providerNumbers')]
public function testNumber(mixed $expected, string $value, string $thousandsSeparator = ',', string $decimalSeparator = '.'): void
{
StringHelper::setThousandsSeparator($thousandsSeparator);
StringHelper::setDecimalSeparator($decimalSeparator);
$result = FormattedNumber::convertToNumberIfFormatted($value);
self::assertTrue($result);
self::assertSame($expected, $value);
}
public static function providerNumbers(): array
{
return [
'normal' => [1234.5, '1,234.5'],
'slash as thousands separator' => [-1234.5, '- 1/234.5', '/', '.'],
'slash as decimal separator' => [-1234.5, '- 1,234/5', ',', '/'],
];
}
#[DataProvider('providerPercentages')]
public function testPercentage(string $expected, string $value, string $thousandsSeparator = ',', string $decimalSeparator = '.'): void
{
$originalValue = $value;
StringHelper::setThousandsSeparator($thousandsSeparator);
StringHelper::setDecimalSeparator($decimalSeparator);
$result = FormattedNumber::convertToNumberIfPercent($value);
self::assertTrue($result);
self::assertSame($expected, (string) $value);
self::assertNotEquals($value, $originalValue);
}
public static function providerPercentages(): array
{
return [
'normal' => ['21.5034', '2,150.34%'],
'slash as thousands separator' => ['21.5034', '2/150.34%', '/', '.'],
'slash as decimal separator' => ['21.5034', '2,150/34%', ',', '/'],
];
}
#[DataProvider('providerCurrencies')]
public function testCurrencies(string $expected, string $value, string $thousandsSeparator = ',', string $decimalSeparator = '.', ?string $currencyCode = null): void
{
$originalValue = $value;
StringHelper::setThousandsSeparator($thousandsSeparator);
StringHelper::setDecimalSeparator($decimalSeparator);
if ($currencyCode !== null) {
StringHelper::setCurrencyCode($currencyCode);
}
$result = FormattedNumber::convertToNumberIfCurrency($value);
self::assertTrue($result);
self::assertSame($expected, (string) $value);
self::assertNotEquals($value, $originalValue);
}
public static function providerCurrencies(): array
{
return [
'switched delimiters' => ['2134.56', '$2.134,56', '.', ','],
'normal' => ['2134.56', '$2,134.56'],
'slash as thousands separator' => ['2134.56', '$2/134.56', '/', '.'],
'slash as decimal separator' => ['2134.56', '$2,134/56', ',', '/'],
'slash as currency code' => ['2134.56', '/2,134.56', ',', '.', '/'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Custom/ComplexAssert.php | tests/PhpSpreadsheetTests/Custom/ComplexAssert.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Custom;
use Complex\Complex;
use PHPUnit\Framework\TestCase;
class ComplexAssert extends TestCase
{
protected float $complexPrecision = 1E-12;
private function adjustDelta(float $expected, float $actual, float $delta): float
{
$adjustedDelta = $delta;
if (abs($actual) > 10 && abs($expected) > 10) {
$variance = floor(log10(abs($expected)));
$adjustedDelta *= 10 ** $variance;
}
return $adjustedDelta > 1.0 ? 1.0 : $adjustedDelta;
}
public function assertComplexEquals(mixed $expected, mixed $actual, ?float $delta = null): bool
{
if ($expected === INF) {
self::assertSame('INF', $actual);
return true;
}
if (is_string($expected) && $expected[0] === '#') {
self::assertSame(
$expected,
$actual,
'Mismatched Error'
);
return true;
}
if ($delta === null) {
$delta = $this->complexPrecision;
}
$expectedComplex = new Complex($expected);
$actualComplex = new Complex($actual);
$comparand1 = $expectedComplex->getReal();
$comparand2 = $actualComplex->getReal();
$adjustedDelta = $this->adjustDelta($comparand1, $comparand2, $delta);
self::assertEqualsWithDelta(
$comparand1,
$comparand2,
$adjustedDelta,
'Mismatched Real part'
);
$comparand1 = $expectedComplex->getImaginary();
$comparand2 = $actualComplex->getImaginary();
$adjustedDelta = $this->adjustDelta($comparand1, $comparand2, $delta);
self::assertEqualsWithDelta(
$comparand1,
$comparand2,
$adjustedDelta,
'Mismatched Imaginary part'
);
self::assertSame(
$expectedComplex->getSuffix(),
$actualComplex->getSuffix(),
'Mismatched Suffix'
);
return true;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Document/SecurityTest.php | tests/PhpSpreadsheetTests/Document/SecurityTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Document;
use PhpOffice\PhpSpreadsheet\Document\Security;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use PhpOffice\PhpSpreadsheet\Shared\PasswordHasher;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Protection;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
use PHPUnit\Framework\Attributes\DataProvider;
class SecurityTest extends AbstractFunctional
{
public function testSecurity(): void
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->getCell('A1')->setValue('Hello');
$security = $spreadsheet->getSecurity();
$security->setLockRevision(true);
$revisionsPassword = 'revpasswd';
$security->setRevisionsPassword($revisionsPassword);
$hashedRevisionsPassword = $security->getRevisionsPassword();
self::assertNotEquals($revisionsPassword, $hashedRevisionsPassword);
$security->setLockWindows(true);
$security->setLockStructure(true);
$workbookPassword = 'wbpasswd';
$security->setWorkbookPassword($workbookPassword);
$hashedWorkbookPassword = $security->getWorkbookPassword();
self::assertNotEquals($workbookPassword, $hashedWorkbookPassword);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xlsx');
$reloadedSecurity = $reloadedSpreadsheet->getSecurity();
self::assertTrue($reloadedSecurity->getLockRevision());
self::assertTrue($reloadedSecurity->getLockWindows());
self::assertTrue($reloadedSecurity->getLockStructure());
self::assertSame($hashedWorkbookPassword, $reloadedSecurity->getWorkbookPassword());
self::assertSame($hashedRevisionsPassword, $reloadedSecurity->getRevisionsPassword());
$reloadedSecurity->setRevisionsPassword($hashedWorkbookPassword, true);
self::assertSame($hashedWorkbookPassword, $reloadedSecurity->getRevisionsPassword());
$reloadedSecurity->setWorkbookPassword($hashedRevisionsPassword, true);
self::assertSame($hashedRevisionsPassword, $reloadedSecurity->getWorkbookPassword());
}
public function testHashRatherThanPassword(): void
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->getCell('A1')->setValue('Hello');
$security = $spreadsheet->getSecurity();
$password = '12345';
$algorithm = Protection::ALGORITHM_SHA_512;
$salt = 'KX7zweex4Ay6KVZu9JU6Gw==';
$spinCount = 100_000;
$hash = PasswordHasher::hashPassword($password, $algorithm, $salt, $spinCount);
$security->setLockStructure(true)
->setWorkbookAlgorithmName($algorithm)
->setWorkbookSaltValue($salt, false)
->setWorkbookSpinCount($spinCount)
->setWorkbookPassword($password);
self::assertSame('', $security->getWorkbookPassword());
self::assertSame($hash, $security->getWorkbookHashValue());
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xlsx');
$spreadsheet->disconnectWorksheets();
$reloadedSecurity = $reloadedSpreadsheet->getSecurity();
self::assertTrue($reloadedSecurity->getLockStructure());
self::assertSame('', $reloadedSecurity->getWorkbookPassword());
self::assertSame($hash, $reloadedSecurity->getWorkbookHashValue());
self::assertSame($algorithm, $reloadedSecurity->getWorkbookAlgorithmName());
self::assertSame($salt, $reloadedSecurity->getWorkbookSaltValue());
self::assertSame($spinCount, $reloadedSecurity->getWorkbookSpinCount());
$reloadedSpreadsheet->disconnectWorksheets();
}
public function testRevisionsHashRatherThanPassword(): void
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->getCell('A1')->setValue('Hello');
$security = $spreadsheet->getSecurity();
$password = '54321';
$algorithm = Protection::ALGORITHM_SHA_512;
$salt = 'ddXHG3GsaI5PnaiaVnFGkw==';
$spinCount = 100_000;
$hash = PasswordHasher::hashPassword($password, $algorithm, $salt, $spinCount);
$security->setLockRevision(true)
->setRevisionsAlgorithmName($algorithm)
->setRevisionsSaltValue($salt, false)
->setRevisionsSpinCount($spinCount)
->setRevisionsPassword($password);
self::assertSame('', $security->getRevisionsPassword());
self::assertSame($hash, $security->getRevisionsHashValue());
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xlsx');
$spreadsheet->disconnectWorksheets();
$reloadedSecurity = $reloadedSpreadsheet->getSecurity();
self::assertTrue($reloadedSecurity->getLockRevision());
self::assertSame('', $reloadedSecurity->getRevisionsPassword());
self::assertSame($hash, $reloadedSecurity->getRevisionsHashValue());
self::assertSame($algorithm, $reloadedSecurity->getRevisionsAlgorithmName());
self::assertSame($salt, $reloadedSecurity->getRevisionsSaltValue());
self::assertSame($spinCount, $reloadedSecurity->getRevisionsSpinCount());
$reloadedSpreadsheet->disconnectWorksheets();
}
public static function providerLocks(): array
{
return [
[false, false, false],
[false, false, true],
[false, true, false],
[false, true, true],
[true, false, false],
[true, false, true],
[true, true, false],
[true, true, true],
];
}
#[DataProvider('providerLocks')]
public function testLocks(bool $revision, bool $windows, bool $structure): void
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->getCell('A1')->setValue('Hello');
$security = $spreadsheet->getSecurity();
$security->setLockRevision($revision);
$security->setLockWindows($windows);
$security->setLockStructure($structure);
$enabled = $security->isSecurityEnabled();
self::assertSame($enabled, $revision || $windows || $structure);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xlsx');
$reloadedSecurity = $reloadedSpreadsheet->getSecurity();
self::assertSame($revision, $reloadedSecurity->getLockRevision());
self::assertSame($windows, $reloadedSecurity->getLockWindows());
self::assertSame($structure, $reloadedSecurity->getLockStructure());
}
public function testBadAlgorithm(): void
{
$security = new Security();
$password = '12345';
$algorithm = 'SHA-513';
$salt = 'KX7zweex4Ay6KVZu9JU6Gw==';
$spinCount = 100_000;
try {
$hash = PasswordHasher::hashPassword($password, $algorithm, $salt, $spinCount);
self::fail('hashPassword should have thrown exception');
} catch (SpreadsheetException $e) {
self::assertStringContainsString('Unsupported password algorithm', $e->getMessage());
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Document/EpochTest.php | tests/PhpSpreadsheetTests/Document/EpochTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Document;
use DateTime;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class EpochTest extends AbstractFunctional
{
public static function providerFormats(): array
{
return [
['Ods', '1921-03-17 11:30:00Z'],
['Ods', '2021-03-17 11:30:00Z'],
['Ods', '2041-03-17 11:30:00Z'],
['Xls', '1921-03-17 11:30:00Z'],
['Xls', '2021-03-17 11:30:00Z'],
['Xls', '2041-03-17 11:30:00Z'],
['Xlsx', '1921-03-17 11:30:00Z'],
['Xlsx', '2021-03-17 11:30:00Z'],
['Xlsx', '2041-03-17 11:30:00Z'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats')]
public function testSetCreated(string $format, string $timestamp): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('A1')->setValue(1);
$spreadsheet->getProperties()->setCreated($timestamp);
$timestamp2 = preg_replace('/1-/', '2-', $timestamp);
self::AssertNotEquals($timestamp, $timestamp2);
$spreadsheet->getProperties()->setModified($timestamp2);
$timestamp3 = preg_replace('/1-/', '3-', $timestamp);
self::AssertNotEquals($timestamp, $timestamp3);
self::AssertNotEquals($timestamp2, $timestamp3);
$spreadsheet->getProperties()->setCustomProperty('cprop', $timestamp3, 'd');
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$created = $reloadedSpreadsheet->getProperties()->getCreated();
$dt1 = DateTime::createFromFormat('U', "$created");
$modified = $reloadedSpreadsheet->getProperties()->getModified();
$dt2 = DateTime::createFromFormat('U', "$modified");
if ($dt1 === false || $dt2 === false) {
self::fail('Invalid timestamp for created or modified');
} else {
self::assertSame($timestamp, $dt1->format('Y-m-d H:i:s') . 'Z');
self::assertSame($timestamp2, $dt2->format('Y-m-d H:i:s') . 'Z');
}
if ($format === 'Xlsx' || $format === 'Ods') {
// No custom property support in Xls
$cprop = $reloadedSpreadsheet->getProperties()->getCustomPropertyValue('cprop');
if (!is_numeric($cprop)) {
self::fail('Cannot find custom property');
} else {
$dt3 = DateTime::createFromFormat('U', "$cprop");
if ($dt3 === false) {
self::fail('Invalid timestamp for custom property');
} else {
self::assertSame($timestamp3, $dt3->format('Y-m-d H:i:s') . 'Z');
}
}
}
}
public static function providerFormats2(): array
{
return [
['Ods'],
['Xls'],
['Xlsx'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats2')]
public function testConsistentTimeStamp(string $format): void
{
$pgmstart = (float) (new DateTime())->format('U');
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('A1')->setValue(1);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$pgmend = (float) (new DateTime())->format('U');
self::assertLessThanOrEqual($pgmend, $pgmstart);
$created = $reloadedSpreadsheet->getProperties()->getCreated();
$modified = $reloadedSpreadsheet->getProperties()->getModified();
self::assertLessThanOrEqual($pgmend, $created);
self::assertLessThanOrEqual($pgmend, $modified);
self::assertLessThanOrEqual($created, $pgmstart);
self::assertLessThanOrEqual($modified, $pgmstart);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Document/PropertiesTest.php | tests/PhpSpreadsheetTests/Document/PropertiesTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Document;
use DateTime;
use DateTimeZone;
use PhpOffice\PhpSpreadsheet\Document\Properties;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class PropertiesTest extends TestCase
{
private Properties $properties;
private float $startTime;
protected function setUp(): void
{
do {
// loop to avoid rare situation where timestamp changes
$this->startTime = (float) (new DateTime())->format('U');
$this->properties = new Properties();
$endTime = (float) (new DateTime())->format('U');
} while ($this->startTime !== $endTime);
}
public function testNewInstance(): void
{
self::assertSame('Unknown Creator', $this->properties->getCreator());
self::assertSame('Unknown Creator', $this->properties->getLastModifiedBy());
self::assertSame('Untitled Spreadsheet', $this->properties->getTitle());
self::assertSame('', $this->properties->getCompany());
self::assertEquals($this->startTime, $this->properties->getCreated());
self::assertEquals($this->startTime, $this->properties->getModified());
}
public function testSetCreator(): void
{
$creator = 'Mark Baker';
$this->properties->setCreator($creator);
self::assertSame($creator, $this->properties->getCreator());
}
#[DataProvider('providerCreationTime')]
public function testSetCreated(null|int $expectedCreationTime, null|int|string $created): void
{
if ($expectedCreationTime === null) {
do {
// loop to avoid rare situation where timestamp changes
$expectedCreationTime = (float) (new DateTime())->format('U');
$this->properties->setCreated($created);
$endTime = (float) (new DateTime())->format('U');
} while ($expectedCreationTime !== $endTime);
} else {
$this->properties->setCreated($created);
}
self::assertEquals($expectedCreationTime, $this->properties->getCreated());
}
public static function providerCreationTime(): array
{
return [
[null, null],
[1615980600, 1615980600],
[1615980600, '1615980600'],
[1615980600, '2021-03-17 11:30:00Z'],
];
}
public function testSetModifier(): void
{
$creator = 'Mark Baker';
$this->properties->setLastModifiedBy($creator);
self::assertSame($creator, $this->properties->getLastModifiedBy());
}
#[DataProvider('providerModifiedTime')]
public function testSetModified(mixed $expectedModifiedTime, null|int|string $modified): void
{
if ($expectedModifiedTime === null) {
do {
// loop to avoid rare situation where timestamp changes
$expectedModifiedTime = (float) (new DateTime())->format('U');
$this->properties->setModified($modified);
$endTime = (float) (new DateTime())->format('U');
} while ($expectedModifiedTime !== $endTime);
} else {
$this->properties->setModified($modified);
}
self::assertEquals($expectedModifiedTime, $this->properties->getModified());
}
public static function providerModifiedTime(): array
{
return [
[null, null],
[1615980600, 1615980600],
[1615980600, '1615980600'],
[1615980600, '2021-03-17 11:30:00Z'],
];
}
public function testSetTitle(): void
{
$title = 'My spreadsheet title test';
$this->properties->setTitle($title);
self::assertSame($title, $this->properties->getTitle());
}
public function testSetDescription(): void
{
$description = 'A test for spreadsheet description';
$this->properties->setDescription($description);
self::assertSame($description, $this->properties->getDescription());
}
public function testSetSubject(): void
{
$subject = 'Test spreadsheet';
$this->properties->setSubject($subject);
self::assertSame($subject, $this->properties->getSubject());
}
public function testSetKeywords(): void
{
$keywords = 'Test PHPSpreadsheet Spreadsheet Excel LibreOffice Gnumeric OpenSpreadsheetML OASIS';
$this->properties->setKeywords($keywords);
self::assertSame($keywords, $this->properties->getKeywords());
}
public function testSetCategory(): void
{
$category = 'Testing';
$this->properties->setCategory($category);
self::assertSame($category, $this->properties->getCategory());
}
public function testSetCompany(): void
{
$company = 'PHPOffice Suite';
$this->properties->setCompany($company);
self::assertSame($company, $this->properties->getCompany());
}
public function testSetManager(): void
{
$manager = 'Mark Baker';
$this->properties->setManager($manager);
self::assertSame($manager, $this->properties->getManager());
}
#[DataProvider('providerCustomProperties')]
public function testSetCustomProperties(mixed $expectedType, mixed $expectedValue, string $propertyName, null|bool|float|int|string $propertyValue, ?string $propertyType = null): void
{
if ($propertyType === null) {
$this->properties->setCustomProperty($propertyName, $propertyValue);
} else {
$this->properties->setCustomProperty($propertyName, $propertyValue, $propertyType);
}
self::assertTrue($this->properties->isCustomPropertySet($propertyName));
self::assertSame($expectedType, $this->properties->getCustomPropertyType($propertyName));
/** @var float|int|string */
$result = $this->properties->getCustomPropertyValue($propertyName);
if ($expectedType === Properties::PROPERTY_TYPE_DATE) {
$result = Date::formattedDateTimeFromTimestamp("$result", 'Y-m-d', new DateTimeZone('UTC'));
}
self::assertSame($expectedValue, $result);
}
public static function providerCustomProperties(): array
{
return [
[Properties::PROPERTY_TYPE_STRING, null, 'Editor', null],
[Properties::PROPERTY_TYPE_STRING, 'Mark Baker', 'Editor', 'Mark Baker'],
[Properties::PROPERTY_TYPE_FLOAT, 1.17, 'Version', 1.17],
[Properties::PROPERTY_TYPE_INTEGER, 2, 'Revision', 2],
[Properties::PROPERTY_TYPE_BOOLEAN, true, 'Tested', true],
[Properties::PROPERTY_TYPE_DATE, '2021-03-17', 'Test Date', '2021-03-17T00:00:00Z', Properties::PROPERTY_TYPE_DATE],
];
}
public function testGetUnknownCustomProperties(): void
{
$propertyName = 'I DONT EXIST';
self::assertFalse($this->properties->isCustomPropertySet($propertyName));
self::assertNull($this->properties->getCustomPropertyValue($propertyName));
self::assertNull($this->properties->getCustomPropertyType($propertyName));
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/ArrayFunctionsCellTest.php | tests/PhpSpreadsheetTests/Functional/ArrayFunctionsCellTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class ArrayFunctionsCellTest extends TestCase
{
public function testArrayAndNonArrayOutput(): void
{
$spreadsheet = new Spreadsheet();
Calculation::getInstance($spreadsheet)->setInstanceArrayReturnType(Calculation::RETURN_ARRAY_AS_ARRAY);
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray(
[
[1.0, 0.0, 1.0],
[0.0, 2.0, 0.0],
[0.0, 0.0, 1.0],
],
strictNullComparison: true
);
$sheet->setCellValue('E1', '=MINVERSE(A1:C3)');
$sheet->setCellValue('I1', '=E1#');
$sheet->setCellValue('M1', '=MMULT(E1#,I1#)');
$sheet->setCellValue('E6', '=SUM(E1)');
$sheet->setCellValue('E7', '=SUM(SINGLE(E1))');
$sheet->setCellValue('E8', '=SUM(E1#)');
$sheet->setCellValue('I6', '=E1+I1');
$sheet->setCellValue('J6', '=E1#+I1#');
$expectedE1 = [
[1.0, 0.0, -1.0],
[0.0, 0.5, 0.0],
[0.0, 0.0, 1.0],
];
self::assertSame($expectedE1, $sheet->getCell('E1')->getCalculatedValue(), 'MINVERSE function');
self::assertSame($expectedE1, $sheet->getCell('I1')->getCalculatedValue(), 'Assignment with spill operator');
$expectedM1 = [
[1.0, 0.0, -2.0],
[0.0, 0.25, 0.0],
[0.0, 0.0, 1.0],
];
self::assertSame($expectedM1, $sheet->getCell('M1')->getCalculatedValue(), 'MMULT with 2 spill operators');
self::assertSame(1.0, $sheet->getCell('E6')->getCalculatedValue(), 'SUM referring to anchor cell');
self::assertSame(1.0, $sheet->getCell('E7')->getCalculatedValue(), 'SUM referring to anchor cell wrapped in Single');
self::assertSame(1.5, $sheet->getCell('E8')->getCalculatedValue(), 'SUM referring to anchor cell with Spill Operator');
self::assertSame(2.0, $sheet->getCell('I6')->getCalculatedValue(), 'addition operator for 2 anchor cells');
$expectedJ6 = [
[2.0, 0.0, -2.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 2.0],
];
self::assertSame($expectedJ6, $sheet->getCell('J6')->getCalculatedValue(), 'addition operator for 2 anchor cells with Spill operators');
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/WorkbookViewAttributesTest.php | tests/PhpSpreadsheetTests/Functional/WorkbookViewAttributesTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class WorkbookViewAttributesTest extends AbstractFunctional
{
public static function providerFormats(): array
{
return [
['Xlsx'],
];
}
/**
* Test that workbook bookview attributes such as 'showSheetTabs',
* (the attribute controlling worksheet tabs visibility,)
* are preserved when xlsx documents are read and written.
*
* @see https://github.com/PHPOffice/PhpSpreadsheet/issues/523
*/
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats')]
public function testPreserveWorkbookViewAttributes(string $format): void
{
// Create a dummy workbook with two worksheets
$workbook = new Spreadsheet();
$worksheet1 = $workbook->getActiveSheet();
$worksheet1->setTitle('Tweedledee');
$worksheet1->setCellValue('A1', 1);
$worksheet2 = $workbook->createSheet();
$worksheet2->setTitle('Tweeldedum');
$worksheet2->setCellValue('A1', 2);
// Check that the bookview attributes return default values
self::assertTrue($workbook->getShowHorizontalScroll());
self::assertTrue($workbook->getShowVerticalScroll());
self::assertTrue($workbook->getShowSheetTabs());
self::assertTrue($workbook->getAutoFilterDateGrouping());
self::assertFalse($workbook->getMinimized());
self::assertSame(0, $workbook->getFirstSheetIndex());
self::assertSame(600, $workbook->getTabRatio());
self::assertSame(Spreadsheet::VISIBILITY_VISIBLE, $workbook->getVisibility());
// Set the bookview attributes to non-default values
$workbook->setShowHorizontalScroll(false);
$workbook->setShowVerticalScroll(false);
$workbook->setShowSheetTabs(false);
$workbook->setAutoFilterDateGrouping(false);
$workbook->setMinimized(true);
$workbook->setFirstSheetIndex(1);
$workbook->setTabRatio(700);
$workbook->setVisibility(Spreadsheet::VISIBILITY_HIDDEN);
// Check that bookview attributes were set properly
self::assertFalse($workbook->getShowHorizontalScroll());
self::assertFalse($workbook->getShowVerticalScroll());
self::assertFalse($workbook->getShowSheetTabs());
self::assertFalse($workbook->getAutoFilterDateGrouping());
self::assertTrue($workbook->getMinimized());
self::assertSame(1, $workbook->getFirstSheetIndex());
self::assertSame(700, $workbook->getTabRatio());
self::assertSame(Spreadsheet::VISIBILITY_HIDDEN, $workbook->getVisibility());
$workbook2 = $this->writeAndReload($workbook, $format);
// Check that the read spreadsheet has the right bookview attributes
self::assertFalse($workbook2->getShowHorizontalScroll());
self::assertFalse($workbook2->getShowVerticalScroll());
self::assertFalse($workbook2->getShowSheetTabs());
self::assertFalse($workbook2->getAutoFilterDateGrouping());
self::assertTrue($workbook2->getMinimized());
self::assertSame(1, $workbook2->getFirstSheetIndex());
self::assertSame(700, $workbook2->getTabRatio());
self::assertSame(Spreadsheet::VISIBILITY_HIDDEN, $workbook2->getVisibility());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/EnclosureTest.php | tests/PhpSpreadsheetTests/Functional/EnclosureTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class EnclosureTest extends AbstractFunctional
{
public static function providerFormats(): array
{
return [
['Html'],
['Xls'],
['Xlsx'],
['Ods'],
['Csv'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats')]
public function testEnclosure(string $format): void
{
$value = '<img alt="" src="http://example.com/image.jpg" />';
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->getCell('A1')->setValue($value);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$actual = $reloadedSpreadsheet->getActiveSheet()->getCell('A1')->getCalculatedValue();
self::assertSame($value, $actual, 'should be able to write and read strings with multiples quotes');
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/TypeAttributePreservationTest.php | tests/PhpSpreadsheetTests/Functional/TypeAttributePreservationTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Calculation\Information\Info;
use PhpOffice\PhpSpreadsheet\Reader\Ods as ReaderOds;
use PhpOffice\PhpSpreadsheet\Reader\Slk as ReaderSlk;
use PhpOffice\PhpSpreadsheet\Reader\Xls as ReaderXls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx as ReaderXlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xml as ReaderXml;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as WriterXlsx;
use PHPUnit\Framework\Attributes\DataProvider;
class TypeAttributePreservationTest extends AbstractFunctional
{
protected function setUp(): void
{
Info::$infoSupported = false;
}
protected function tearDown(): void
{
Info::$infoSupported = true;
}
public static function providerFormulae(): array
{
$formats = ['Xlsx'];
/** @var mixed[][] */
$data = require 'tests/data/Functional/TypeAttributePreservation/Formula.php';
$result = [];
foreach ($formats as $f) {
foreach ($data as $d) {
$result[] = [$f, $d];
}
}
return $result;
}
/**
* Ensure saved spreadsheets maintain the correct data type.
*
* @param mixed[] $values
*/
#[DataProvider('providerFormulae')]
public function testFormulae(string $format, array $values): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray($values);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$reloadedSheet = $reloadedSpreadsheet->getActiveSheet();
$expected = $sheet->getCell('A1')->getCalculatedValue();
if ($sheet->getCell('A1')->getDataType() === 'f') {
$actual = $reloadedSheet->getCell('A1')->getOldCalculatedValue();
} else {
$actual = $reloadedSheet->getCell('A1')->getValue();
}
self::assertSame($expected, $actual);
$spreadsheet->disconnectWorksheets();
$reloadedSpreadsheet->disconnectWorksheets();
}
public static function customizeWriter(WriterXlsx $writer): void
{
$writer->setPreCalculateFormulas(false);
}
/**
* Ensure saved spreadsheets maintain the correct data type.
*
* @param mixed[] $values
*/
#[DataProvider('providerFormulae')]
public function testFormulaeNoPrecalc(string $format, array $values): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray($values);
/** @var callable */
$writerCustomizer = [self::class, 'customizeWriter'];
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format, null, $writerCustomizer);
$reloadedSheet = $reloadedSpreadsheet->getActiveSheet();
$expected = $sheet->getCell('A1')->getCalculatedValue();
if ($sheet->getCell('A1')->getDataType() === 'f') {
$actual = $reloadedSheet->getCell('A1')->getOldCalculatedValue();
self::assertNull($actual);
} else {
$actual = $reloadedSheet->getCell('A1')->getValue();
self::assertSame($expected, $actual);
}
$spreadsheet->disconnectWorksheets();
$reloadedSpreadsheet->disconnectWorksheets();
}
public function testUnimplementedFunctionXlsx(): void
{
$file = 'tests/data/Reader/XLSX/issue.3658.xlsx';
$reader = new ReaderXlsx();
$spreadsheet = $reader->load($file);
$sheet = $spreadsheet->getActiveSheet();
$unimplemented = '=INFO("SYSTEM")';
self::assertSame(124, $sheet->getCell('A2')->getOldCalculatedValue());
self::assertSame('00123', $sheet->getCell('A3')->getOldCalculatedValue());
self::assertSame($unimplemented, $sheet->getCell('A4')->getValue());
self::assertSame('pcdos', $sheet->getCell('A4')->getCalculatedValue(), 'use oldCalculatedValue from read for unimplemented function');
$sheet->getCell('D10')->setValue($unimplemented);
self::assertNull($sheet->getCell('D10')->getCalculatedValue(), 'return null for unimplemented function when old value unassigned');
$spreadsheet->disconnectWorksheets();
}
public function testUnimplementedFunctionXls(): void
{
$file = 'tests/data/Reader/XLS/issue.3658.xls';
$reader = new ReaderXls();
$spreadsheet = $reader->load($file);
$sheet = $spreadsheet->getActiveSheet();
$unimplemented = '=INFO("SYSTEM")';
self::assertSame(124, $sheet->getCell('A2')->getOldCalculatedValue());
self::assertSame('00123', $sheet->getCell('A3')->getOldCalculatedValue());
self::assertSame($unimplemented, $sheet->getCell('A4')->getValue());
self::assertSame('pcdos', $sheet->getCell('A4')->getCalculatedValue(), 'use oldCalculatedValue from read for unimplemented function');
$sheet->getCell('D10')->setValue($unimplemented);
self::assertNull($sheet->getCell('D10')->getCalculatedValue(), 'return null for unimplemented function when old value unassigned');
$spreadsheet->disconnectWorksheets();
}
public function testUnimplementedFunctionXml(): void
{
$file = 'tests/data/Reader/Xml/issue.3658.xml';
$reader = new ReaderXml();
$spreadsheet = $reader->load($file);
$sheet = $spreadsheet->getActiveSheet();
$unimplemented = '=INFO("SYSTEM")';
self::assertSame(124, $sheet->getCell('A2')->getOldCalculatedValue());
self::assertSame('00123', $sheet->getCell('A3')->getOldCalculatedValue());
self::assertSame($unimplemented, $sheet->getCell('A4')->getValue());
self::assertSame('pcdos', $sheet->getCell('A4')->getCalculatedValue(), 'use oldCalculatedValue from read for unimplemented function');
$sheet->getCell('D10')->setValue($unimplemented);
self::assertNull($sheet->getCell('D10')->getCalculatedValue(), 'return null for unimplemented function when old value unassigned');
$spreadsheet->disconnectWorksheets();
}
public function testUnimplementedFunctionOds(): void
{
$file = 'tests/data/Reader/Ods/issue.3658.ods';
$reader = new ReaderOds();
$spreadsheet = $reader->load($file);
$sheet = $spreadsheet->getActiveSheet();
$unimplemented = '=INFO("SYSTEM")';
self::assertSame(124, $sheet->getCell('A2')->getOldCalculatedValue());
self::assertSame('00123', $sheet->getCell('A3')->getOldCalculatedValue());
self::assertSame($unimplemented, $sheet->getCell('A4')->getValue());
self::assertSame('WNT', $sheet->getCell('A4')->getCalculatedValue(), 'use oldCalculatedValue from read for unimplemented function');
$sheet->getCell('D10')->setValue($unimplemented);
self::assertNull($sheet->getCell('D10')->getCalculatedValue(), 'return null for unimplemented function when old value unassigned');
$spreadsheet->disconnectWorksheets();
}
public function testUnimplementedFunctionSlk(): void
{
$file = 'tests/data/Reader/Slk/issue.3658.slk';
$reader = new ReaderSlk();
$spreadsheet = $reader->load($file);
$sheet = $spreadsheet->getActiveSheet();
$unimplemented = '=INFO("SYSTEM")';
self::assertSame(124, $sheet->getCell('A2')->getOldCalculatedValue());
self::assertSame('00123', $sheet->getCell('A3')->getOldCalculatedValue());
self::assertSame($unimplemented, $sheet->getCell('A4')->getValue());
self::assertSame('pcdos', $sheet->getCell('A4')->getCalculatedValue(), 'use oldCalculatedValue from read for unimplemented function');
$sheet->getCell('D10')->setValue($unimplemented);
self::assertNull($sheet->getCell('D10')->getCalculatedValue(), 'return null for unimplemented function when old value unassigned');
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/ReadFilterTest.php | tests/PhpSpreadsheetTests/Functional/ReadFilterTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Reader\IReader;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
class ReadFilterTest extends AbstractFunctional
{
public static function providerCellsValues(): array
{
$cellValues = [
// one argument as a multidimensional array
[1, 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
[2, 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
[3, 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
[4, 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
[5, 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
[6, 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
[7, 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
[8, 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
[9, 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
[10, 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
];
return [
['Xlsx', $cellValues],
['Ods', $cellValues],
];
}
/**
* Test load Xlsx file with many empty cells with no filter used.
*
* @param mixed[] $arrayData
*/
#[DataProvider('providerCellsValues')]
public function testXlsxLoadWithoutReadFilter(string $format, array $arrayData): void
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->fromArray($arrayData, null, 'A1');
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$sheet = $reloadedSpreadsheet->getSheet(0);
// test highest column (very specific num of columns because of some 3rd party software)
self::assertSame('J', $sheet->getHighestColumn());
// test highest row (very specific num of rows because of some 3rd party software)
self::assertEquals(10, $sheet->getHighestRow());
// test top left coordinate
$sortedCoordinates = $sheet->getCellCollection()->getSortedCoordinates();
$coordinateTopLeft = reset($sortedCoordinates);
self::assertSame('A1', $coordinateTopLeft);
}
/**
* Test load Xlsx file with many empty cells (and big max row number) with readfilter.
*
* @param mixed[] $arrayData
*/
#[DataProvider('providerCellsValues')]
public function testXlsxLoadWithReadFilter(string $format, array $arrayData): void
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->fromArray($arrayData, null, 'A1');
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format, function (IReader $reader): void {
// apply filter
$reader->setReadFilter(new ReadFilterFilter());
});
$sheet = $reloadedSpreadsheet->getSheet(0);
// test highest column (very specific num of columns because of some 3rd party software)
self::assertSame('D', $sheet->getHighestColumn());
// test highest row (very specific num of rows because of some 3rd party software)
self::assertEquals(6, $sheet->getHighestRow());
// test top left coordinate
$sortedCoordinates = $sheet->getCellCollection()->getSortedCoordinates();
$coordinateTopLeft = reset($sortedCoordinates);
self::assertSame('B2', $coordinateTopLeft);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/ArrayFunctionsSpillTest.php | tests/PhpSpreadsheetTests/Functional/ArrayFunctionsSpillTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PHPUnit\Framework\TestCase;
class ArrayFunctionsSpillTest extends TestCase
{
public function testArrayOutput(): void
{
$spreadsheet = new Spreadsheet();
$calculation = Calculation::getInstance($spreadsheet);
$calculation->setInstanceArrayReturnType(Calculation::RETURN_ARRAY_AS_ARRAY);
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('B5', 'OCCUPIED');
$columnArray = [[1], [2], [2], [2], [3], [3], [3], [3], [4], [4], [4], [5]];
$sheet->fromArray($columnArray, 'A1');
$sheet->setCellValue('B1', '=UNIQUE(A1:A12)');
$expected = [['#SPILL!'], [null], [null], [null], ['OCCUPIED']];
self::assertSame($expected, $sheet->rangeToArray('B1:B5', calculateFormulas: true, formatData: false, reduceArrays: true), 'spill with B5 unchanged');
self::assertFalse($sheet->isCellInSpillRange('B1'));
self::assertFalse($sheet->isCellInSpillRange('B2'));
self::assertFalse($sheet->isCellInSpillRange('B3'));
self::assertFalse($sheet->isCellInSpillRange('B4'));
self::assertFalse($sheet->isCellInSpillRange('B5'));
self::assertFalse($sheet->isCellInSpillRange('Z9'));
$calculation->clearCalculationCache();
$columnArray = [[1], [2], [2], [2], [3], [3], [3], [3], [4], [4], [4], [4]];
$sheet->fromArray($columnArray, 'A1');
$sheet->setCellValue('B1', '=UNIQUE(A1:A12)');
$expected = [[1], [2], [3], [4], ['OCCUPIED']];
self::assertSame($expected, $sheet->rangeToArray('B1:B5', calculateFormulas: true, formatData: false, reduceArrays: true), 'fill B1:B4 with B5 unchanged');
self::assertFalse($sheet->isCellInSpillRange('B1'));
self::assertTrue($sheet->isCellInSpillRange('B2'));
self::assertTrue($sheet->isCellInSpillRange('B3'));
self::assertTrue($sheet->isCellInSpillRange('B4'));
self::assertFalse($sheet->isCellInSpillRange('B5'));
self::assertFalse($sheet->isCellInSpillRange('Z9'));
$calculation->clearCalculationCache();
$columnArray = [[1], [3], [3], [3], [3], [3], [3], [3], [3], [3], [3], [3]];
$sheet->fromArray($columnArray, 'A1');
$sheet->setCellValue('B1', '=UNIQUE(A1:A12)');
$expected = [[1], [3], [null], [null], ['OCCUPIED']];
self::assertSame($expected, $sheet->rangeToArray('B1:B5', calculateFormulas: true, formatData: false, reduceArrays: true), 'fill B1:B2(changed from prior) set B3:B4 to null B5 unchanged');
self::assertFalse($sheet->isCellInSpillRange('B1'));
self::assertTrue($sheet->isCellInSpillRange('B2'));
self::assertFalse($sheet->isCellInSpillRange('B3'));
self::assertFalse($sheet->isCellInSpillRange('B4'));
self::assertFalse($sheet->isCellInSpillRange('B5'));
self::assertFalse($sheet->isCellInSpillRange('Z9'));
$calculation->clearCalculationCache();
$columnArray = [[1], [2], [3], [3], [3], [3], [3], [3], [3], [3], [3], [3]];
$sheet->fromArray($columnArray, 'A1');
$sheet->setCellValue('B1', '=UNIQUE(A1:A12)');
$expected = [[1], [2], [3], [null], ['OCCUPIED']];
self::assertSame($expected, $sheet->rangeToArray('B1:B5', calculateFormulas: true, formatData: false, reduceArrays: true), 'fill B1:B3(B2 changed from prior) set B4 to null B5 unchanged');
$calculation->clearCalculationCache();
$columnArray = [[1], [2], [2], [2], [3], [3], [3], [3], [4], [4], [4], [5]];
$sheet->fromArray($columnArray, 'A1');
$sheet->setCellValue('B1', '=UNIQUE(A1:A12)');
$expected = [['#SPILL!'], [null], [null], [null], ['OCCUPIED']];
self::assertSame($expected, $sheet->rangeToArray('B1:B5', calculateFormulas: true, formatData: false, reduceArrays: true), 'spill clears B2:B4 with B5 unchanged');
$calculation->clearCalculationCache();
$sheet->setCellValue('Z1', '=SORT({7;5;1})');
$sheet->getCell('Z1')->getCalculatedValue(); // populates Z1-Z3
self::assertTrue($sheet->isCellInSpillRange('Z2'));
self::assertTrue($sheet->isCellInSpillRange('Z3'));
self::assertFalse($sheet->isCellInSpillRange('Z4'));
self::assertFalse($sheet->isCellInSpillRange('Z1'));
$spreadsheet->disconnectWorksheets();
}
public function testNonArrayOutput(): void
{
$spreadsheet = new Spreadsheet();
Calculation::getInstance($spreadsheet)
->setInstanceArrayReturnType(
Calculation::RETURN_ARRAY_AS_VALUE
);
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('B5', 'OCCUPIED');
$columnArray = [[1], [2], [2], [2], [3], [3], [3], [3], [4], [4], [4], [4]];
$sheet->fromArray($columnArray, 'A1');
$sheet->setCellValue('B1', '=UNIQUE(A1:A12)');
$expected = [[1], [null], [null], [null], ['OCCUPIED']];
self::assertSame($expected, $sheet->rangeToArray('B1:B5', calculateFormulas: true, formatData: false, reduceArrays: true), 'only fill B1');
self::assertFalse($sheet->isCellInSpillRange('B1'));
self::assertFalse($sheet->isCellInSpillRange('B2'));
self::assertFalse($sheet->isCellInSpillRange('B3'));
self::assertFalse($sheet->isCellInSpillRange('B4'));
self::assertFalse($sheet->isCellInSpillRange('B5'));
self::assertFalse($sheet->isCellInSpillRange('Z9'));
$spreadsheet->disconnectWorksheets();
}
public function testSpillOperator(): void
{
$spreadsheet = new Spreadsheet();
Calculation::getInstance($spreadsheet)->setInstanceArrayReturnType(Calculation::RETURN_ARRAY_AS_ARRAY);
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([
['Product', 'Quantity', 'Price', 'Cost'],
['Apple', 20, 0.75],
['Kiwi', 8, 0.80],
['Lemon', 12, 0.70],
['Mango', 5, 1.75],
['Pineapple', 2, 2.00],
['Total'],
]);
$sheet->getCell('D2')->setValue('=B2:B6*C2:C6');
$sheet->getCell('D7')->setValue('=SUM(D2#)');
$sheet->getStyle('A1:D1')->getFont()->setBold(true);
$sheet->getStyle('C2:D6')->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_USD);
self::assertEqualsWithDelta(
[
['Cost'],
[15.0],
[6.4],
[8.4],
[8.75],
[4.0],
[42.55],
],
$sheet->rangeToArray('D1:D7', calculateFormulas: true, formatData: false, reduceArrays: true),
1.0e-10
);
$sheet->getCell('G2')->setValue('=B2#');
self::assertSame('#REF!', $sheet->getCell('G2')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/ColumnWidthTest.php | tests/PhpSpreadsheetTests/Functional/ColumnWidthTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
class ColumnWidthTest extends AbstractFunctional
{
public static function providerFormats(): array
{
return [
['Xlsx'],
];
}
#[DataProvider('providerFormats')]
public function testReadColumnWidth(string $format): void
{
// create new sheet with column width
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$sheet->getColumnDimension('A')->setWidth(20);
$this->assertColumn($spreadsheet);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$this->assertColumn($reloadedSpreadsheet);
}
private function assertColumn(Spreadsheet $spreadsheet): void
{
$sheet = $spreadsheet->getActiveSheet();
$columnDimensions = $sheet->getColumnDimensions();
self::assertArrayHasKey('A', $columnDimensions);
$column = array_shift($columnDimensions);
self::assertEquals(20, $column->getWidth());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/SelectedCellsTest.php | tests/PhpSpreadsheetTests/Functional/SelectedCellsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class SelectedCellsTest extends AbstractFunctional
{
public static function providerFormats(): array
{
return [
['Xls'],
];
}
/**
* Test load file with correct selected cells.
*/
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats')]
public function testSelectedCells(string $format): void
{
$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0)
->setTitle('Test1')
->setCellValue('D1', 1)
->setCellValue('D2', 2)
->setCellValue('D3', 3)
->setCellValue('D4', 4)
->setCellValue('D5', '=SUM(D1:D4)')
->setSelectedCell('B2');
$spreadsheet->createSheet(1);
$spreadsheet->setActiveSheetIndex(1)
->setTitle('Test2')
->setCellValue('D1', 4)
->setCellValue('E1', 3)
->setCellValue('F1', 2)
->setCellValue('G1', 1)
->setCellValue('H1', '=SUM(D1:G4)')
->setSelectedCells('A1:B2');
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
// Original object.
self::assertSame('B2', $spreadsheet->setActiveSheetIndex(0)->getSelectedCells());
self::assertSame('A1:B2', $spreadsheet->setActiveSheetIndex(1)->getSelectedCells());
// Saved and reloaded file.
self::assertSame('B2', $reloadedSpreadsheet->setActiveSheetIndex(0)->getSelectedCells());
self::assertSame('A1:B2', $reloadedSpreadsheet->setActiveSheetIndex(1)->getSelectedCells());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/FreezePaneTest.php | tests/PhpSpreadsheetTests/Functional/FreezePaneTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Pane;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as XlsxWriter;
class FreezePaneTest extends AbstractFunctional
{
public static function providerFormats(): array
{
return [
['Xls'],
['Xlsx'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats')]
public function testFreezePane(string $format): void
{
$cellSplit = 'B4';
$topLeftCell = 'E7';
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->freezePane($cellSplit, $topLeftCell);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$spreadsheet->disconnectWorksheets();
// Read written file
$reloadedActive = $reloadedSpreadsheet->getActiveSheet();
$actualCellSplit = $reloadedActive->getFreezePane();
$actualTopLeftCell = $reloadedActive->getTopLeftCell();
self::assertSame($cellSplit, $actualCellSplit, 'should be able to set freeze pane');
self::assertSame($topLeftCell, $actualTopLeftCell, 'should be able to set the top left cell');
$reloadedSpreadsheet->disconnectWorksheets();
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats')]
public function testFreezePaneWithInvalidSelectedCells(string $format): void
{
$cellSplit = 'A7';
$topLeftCell = 'A24';
$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->freezePane('A7', 'A24');
$worksheet->setSelectedCells('F5');
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$spreadsheet->disconnectWorksheets();
// Read written file
$reloadedActive = $reloadedSpreadsheet->getActiveSheet();
$actualCellSplit = $reloadedActive->getFreezePane();
$actualTopLeftCell = $reloadedActive->getTopLeftCell();
self::assertSame($cellSplit, $actualCellSplit, 'should be able to set freeze pane');
self::assertSame($topLeftCell, $actualTopLeftCell, 'should be able to set the top left cell');
self::assertSame('F5', $reloadedActive->getSelectedCells());
$reloadedSpreadsheet->disconnectWorksheets();
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats')]
public function testFreezePaneUserSelectedCell(string $format): void
{
$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->setCellValue('A1', 'Header1');
$worksheet->setCellValue('B1', 'Header2');
$worksheet->setCellValue('C1', 'Header3');
$worksheet->setCellValue('A2', 'Data1');
$worksheet->setCellValue('B2', 'Data2');
$worksheet->setCellValue('C2', 'Data3');
$worksheet->setCellValue('A3', 'Data4');
$worksheet->setCellValue('B3', 'Data5');
$worksheet->setCellValue('C3', 'Data6');
$worksheet->freezePane('A2');
$worksheet->setSelectedCells('C3');
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$spreadsheet->disconnectWorksheets();
// Read written file
$reloadedActive = $reloadedSpreadsheet->getActiveSheet();
self::assertSame('C3', $reloadedActive->getSelectedCells());
self::assertSame('A2', $reloadedActive->getFreezePane());
if ($format === 'Xlsx') {
$writer = new XlsxWriter($reloadedSpreadsheet);
$writerSheet = new XlsxWriter\Worksheet($writer);
$data = $writerSheet->writeWorksheet($reloadedActive);
$expectedString = '<pane ySplit="1" activePane="bottomLeft" state="frozen" topLeftCell="A2"/><selection pane="bottomLeft" activeCell="C3" sqref="C3"/>';
self::assertStringContainsString($expectedString, $data);
$reloadedActive->freezePane('C1');
$reloadedActive->setSelectedCells('A2');
$writer = new XlsxWriter($reloadedSpreadsheet);
$writerSheet = new XlsxWriter\Worksheet($writer);
$data = $writerSheet->writeWorksheet($reloadedActive);
$expectedString = '<pane xSplit="2" activePane="topRight" state="frozen" topLeftCell="C1"/><selection pane="topRight" activeCell="A2" sqref="A2"/>';
self::assertStringContainsString($expectedString, $data);
}
$reloadedSpreadsheet->disconnectWorksheets();
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats')]
public function testNoFreezePaneUserSelectedCell(string $format): void
{
$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->setCellValue('A1', 'Header1');
$worksheet->setCellValue('B1', 'Header2');
$worksheet->setCellValue('C1', 'Header3');
$worksheet->setCellValue('A2', 'Data1');
$worksheet->setCellValue('B2', 'Data2');
$worksheet->setCellValue('C2', 'Data3');
$worksheet->setCellValue('A3', 'Data4');
$worksheet->setCellValue('B3', 'Data5');
$worksheet->setCellValue('C3', 'Data6');
//$worksheet->freezePane('A2');
$worksheet->setSelectedCells('C3');
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$spreadsheet->disconnectWorksheets();
// Read written file
$reloadedActive = $reloadedSpreadsheet->getActiveSheet();
$expected = 'C3';
self::assertSame($expected, $reloadedActive->getSelectedCells());
$reloadedSpreadsheet->disconnectWorksheets();
}
public function testFreezePaneWithSelectedCells(): void
{
$spreadsheet = new Spreadsheet();
$cellSplit = 'C4';
$sheet = $spreadsheet->getActiveSheet();
$sheet->freezePane($cellSplit);
$sheet->setSelectedCells('A2');
self::assertSame('topLeft', $sheet->getActivePane());
$sheet->setSelectedCells('D3');
self::assertSame('topRight', $sheet->getActivePane());
$sheet->setSelectedCells('B5');
self::assertSame('bottomLeft', $sheet->getActivePane());
$sheet->setSelectedCells('F7');
self::assertSame('bottomRight', $sheet->getActivePane());
$expected = [
'topLeft' => new Pane('topLeft', 'A2', 'A2'),
'topRight' => new Pane('topRight', 'D3', 'D3'),
'bottomLeft' => new Pane('bottomLeft', 'B5', 'B5'),
'bottomRight' => new Pane('bottomRight', 'F7', 'F7'),
];
self::assertEquals($expected, $sheet->getPanes());
self::assertSame('F7', $sheet->getSelectedCells());
$sheet = $spreadsheet->createSheet();
$cellSplit = 'A2';
$sheet->freezePane($cellSplit);
$sheet->setSelectedCells('B1');
self::assertSame('topLeft', $sheet->getActivePane());
$sheet->setSelectedCells('C7');
self::assertSame('bottomLeft', $sheet->getActivePane());
$expected = [
'topLeft' => new Pane('topLeft', 'B1', 'B1'),
'topRight' => null,
'bottomLeft' => new Pane('bottomLeft', 'C7', 'C7'),
'bottomRight' => null,
];
self::assertEquals($expected, $sheet->getPanes());
self::assertSame('C7', $sheet->getSelectedCells());
$sheet = $spreadsheet->createSheet();
$cellSplit = 'D1';
$sheet->freezePane($cellSplit);
$sheet->setSelectedCells('B1');
self::assertSame('topLeft', $sheet->getActivePane());
$sheet->setSelectedCells('G3');
self::assertSame('topRight', $sheet->getActivePane());
$expected = [
'topRight' => new Pane('topRight', 'G3', 'G3'),
'bottomRight' => null,
'topLeft' => new Pane('topLeft', 'B1', 'B1'),
'bottomLeft' => null,
];
self::assertEquals($expected, $sheet->getPanes());
self::assertSame('G3', $sheet->getSelectedCells());
$sheet = $spreadsheet->createSheet();
$sheet->setSelectedCells('D7');
self::assertEmpty($sheet->getActivePane());
$expected = [
'topRight' => null,
'bottomRight' => null,
'topLeft' => null,
'bottomLeft' => null,
];
self::assertEquals($expected, $sheet->getPanes());
self::assertSame('D7', $sheet->getSelectedCells());
$spreadsheet->disconnectWorksheets();
}
public function testFreezePaneViaPaneState(): void
{
$spreadsheet = new Spreadsheet();
$cellSplit = ['C4', 2, 3];
$sheet = $spreadsheet->getActiveSheet();
$sheet->setXSplit($cellSplit[1])
->setYSplit($cellSplit[2])
->setPaneState(Worksheet::PANE_SPLIT);
self::assertNull($sheet->getFreezePane());
$sheet = $spreadsheet->createSheet();
$sheet->setXSplit($cellSplit[1])
->setYSplit($cellSplit[2])
->setPaneState(Worksheet::PANE_FROZEN);
self::assertSame($cellSplit[0], $sheet->getFreezePane());
$sheet->setSelectedCells('A2');
self::assertSame('topLeft', $sheet->getActivePane());
$sheet->setSelectedCells('D3');
self::assertSame('topRight', $sheet->getActivePane());
$sheet->setSelectedCells('B5');
self::assertSame('bottomLeft', $sheet->getActivePane());
$sheet->setSelectedCells('F7');
self::assertSame('bottomRight', $sheet->getActivePane());
$expected = [
'topLeft' => new Pane('topLeft', 'A2', 'A2'),
'topRight' => new Pane('topRight', 'D3', 'D3'),
'bottomLeft' => new Pane('bottomLeft', 'B5', 'B5'),
'bottomRight' => new Pane('bottomRight', 'F7', 'F7'),
];
self::assertEquals($expected, $sheet->getPanes());
self::assertSame('F7', $sheet->getSelectedCells());
$cellSplit = ['B4', 1, 3];
$sheet->setXSplit($cellSplit[1]);
self::assertSame($cellSplit[0], $sheet->getFreezePane());
self::assertSame('F7', $sheet->getSelectedCells());
$expected = [
'topLeft' => null,
'topRight' => null,
'bottomLeft' => null,
'bottomRight' => new Pane('bottomRight', 'F7', 'F7'),
];
self::assertEquals($expected, $sheet->getPanes());
$cellSplit = ['B8', 1, 7];
$sheet->setYSplit($cellSplit[2]);
self::assertSame($cellSplit[0], $sheet->getFreezePane());
self::assertSame('F7', $sheet->getSelectedCells());
$expected = [
'topLeft' => null,
'bottomRight' => null,
'bottomLeft' => null,
'topRight' => new Pane('topRight', 'F7', 'F7'),
];
self::assertEquals($expected, $sheet->getPanes());
$spreadsheet->disconnectWorksheets();
}
public function testAutoWidthDoesNotCorruptActivePane(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray(
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
);
$sheet->freezePane('A2');
$sheet->setSelectedCell('B1');
$paneBefore = $sheet->getActivePane();
self::assertSame('topLeft', $paneBefore);
$sheet->getColumnDimension('A')->setAutoSize(true);
$sheet->getColumnDimension('B')->setAutoSize(true);
$sheet->getColumnDimension('C')->setAutoSize(true);
$sheet->getColumnDimension('D')->setAutoSize(true);
$sheet->calculateColumnWidths();
$paneAfter = $sheet->getActivePane();
self::assertSame('topLeft', $paneAfter);
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/ActiveSheetTest.php | tests/PhpSpreadsheetTests/Functional/ActiveSheetTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Protection;
class ActiveSheetTest extends AbstractFunctional
{
public static function providerFormats(): array
{
return [
['Xls'],
];
}
/**
* Test load file with correct active sheet.
*/
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats')]
public function testActiveSheet(string $format): void
{
$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0)
->setTitle('Test1')
->setCellValue('D1', 1)
->setCellValue('D2', 2)
->setCellValue('D3', 3)
->setCellValue('D4', 4)
->setCellValue('D5', '=SUM(D1:D4)')
->setSelectedCell('B2');
$spreadsheet->createSheet(1);
$spreadsheet->setActiveSheetIndex(1)
->setTitle('Test2')
->setCellValue('D1', 4)
->setCellValue('E1', 3)
->setCellValue('F1', 2)
->setCellValue('G1', 1)
->setCellValue('H1', '=SUM(D1:G4)')
->setSelectedCells('A1:B2');
$spreadsheet->createSheet(2);
$spreadsheet->setActiveSheetIndex(2)
->setCellValue('F1', 2)
->getCell('F1')
->getStyle()
->getProtection()
->setHidden(Protection::PROTECTION_PROTECTED);
$spreadsheet->setActiveSheetIndex(2)
->setTitle('Test3')
->setCellValue('A1', 4)
->setCellValue('B1', 3)
->setCellValue('C1', 2)
->setCellValue('D1', 1)
->setCellValue('E1', '=SUM(A1:D4)')
->setSelectedCells('A1:D1');
$spreadsheet->setActiveSheetIndex(1);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
// Original object.
self::assertSame(1, $spreadsheet->getActiveSheetIndex());
// Saved and reloaded file.
self::assertSame(1, $reloadedSpreadsheet->getActiveSheetIndex());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/DrawingImageHyperlinkTest.php | tests/PhpSpreadsheetTests/Functional/DrawingImageHyperlinkTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
class DrawingImageHyperlinkTest extends AbstractFunctional
{
public function testDrawingImageHyperlinkTest(): void
{
$gdImage = @imagecreatetruecolor(120, 20);
$textColor = ($gdImage === false) ? false : imagecolorallocate($gdImage, 255, 255, 255);
if ($gdImage === false || $textColor === false) {
self::fail('imagecreatetruecolor or imagecolorallocate failed');
} else {
$baseUrl = 'https://github.com/PHPOffice/PhpSpreadsheet';
$spreadsheet = new Spreadsheet();
$aSheet = $spreadsheet->getActiveSheet();
imagestring($gdImage, 1, 5, 5, 'Created with PhpSpreadsheet', $textColor);
$drawing = new MemoryDrawing();
$drawing->setName('In-Memory image 1');
$drawing->setDescription('In-Memory image 1');
$drawing->setCoordinates('A1');
$drawing->setImageResource($gdImage);
$drawing->setRenderingFunction(
MemoryDrawing::RENDERING_JPEG
);
$drawing->setMimeType(MemoryDrawing::MIMETYPE_DEFAULT);
$drawing->setHeight(36);
$hyperLink = new Hyperlink($baseUrl, 'test image');
$drawing->setHyperlink($hyperLink);
$drawing->setWorksheet($aSheet);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, 'Xlsx');
$spreadsheet->disconnectWorksheets();
foreach ($reloadedSpreadsheet->getActiveSheet()->getDrawingCollection() as $pDrawing) {
$getHyperlink = $pDrawing->getHyperlink();
if ($getHyperlink === null) {
self::fail('getHyperlink returned null');
} else {
self::assertEquals('https://github.com/PHPOffice/PhpSpreadsheet', $getHyperlink->getUrl(), 'functional test drawing hyperlink');
}
}
$reloadedSpreadsheet->disconnectWorksheets();
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/PrintAreaTest.php | tests/PhpSpreadsheetTests/Functional/PrintAreaTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Reader\BaseReader;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
class PrintAreaTest extends AbstractFunctional
{
public static function providerFormats(): array
{
return [
['Xls'],
['Xlsx'],
];
}
#[DataProvider('providerFormats')]
public function testPageSetup(string $format): void
{
// Create new workbook with 6 sheets and different print areas
$spreadsheet = new Spreadsheet();
$worksheet1 = $spreadsheet->getActiveSheet()->setTitle('Sheet 1');
$worksheet1->getPageSetup()->setPrintArea('A1:B1');
for ($i = 2; $i < 4; ++$i) {
$sheet = $spreadsheet->createSheet()->setTitle("Sheet $i");
$sheet->getPageSetup()->setPrintArea("A$i:B$i");
}
$worksheet4 = $spreadsheet->createSheet()->setTitle('Sheet 4');
$worksheet4->getPageSetup()->setPrintArea('A4:B4,D1:E4');
$worksheet5 = $spreadsheet->createSheet()->setTitle('Sheet 5');
$worksheet5->getPageSetup()->addPrintAreaByColumnAndRow(1, 1, 10, 10, 1);
$worksheet6 = $spreadsheet->createSheet()->setTitle('Sheet 6');
$worksheet6->getPageSetup()->addPrintAreaByColumnAndRow(1, 1, 10, 10, 1);
$worksheet6->getPageSetup()->addPrintAreaByColumnAndRow(12, 1, 12, 10, 1);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format, function (BaseReader $reader): void {
$reader->setLoadSheetsOnly(['Sheet 1', 'Sheet 3', 'Sheet 4', 'Sheet 5', 'Sheet 6']);
});
$spreadsheet->disconnectWorksheets();
$actual1 = self::getPrintArea($reloadedSpreadsheet, 'Sheet 1');
$actual3 = self::getPrintArea($reloadedSpreadsheet, 'Sheet 3');
$actual4 = self::getPrintArea($reloadedSpreadsheet, 'Sheet 4');
$actual5 = self::getPrintArea($reloadedSpreadsheet, 'Sheet 5');
$actual6 = self::getPrintArea($reloadedSpreadsheet, 'Sheet 6');
self::assertSame('A1:B1', $actual1, 'should be able to write and read normal page setup');
self::assertSame('A3:B3', $actual3, 'should be able to write and read page setup even when skipping sheets');
self::assertSame('A4:B4,D1:E4', $actual4, 'should be able to write and read page setup with multiple print areas');
self::assertSame('A1:J10', $actual5, 'add by column and row');
self::assertSame('A1:J10,L1:L10', $actual6, 'multiple add by column and row');
$reloadedSpreadsheet->disconnectWorksheets();
}
private static function getPrintArea(Spreadsheet $spreadsheet, string $name): string
{
$sheet = $spreadsheet->getSheetByNameOrThrow($name);
return $sheet->getPageSetup()->getPrintArea();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/ConditionalTextTest.php | tests/PhpSpreadsheetTests/Functional/ConditionalTextTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\Fill;
class ConditionalTextTest extends AbstractFunctional
{
const COLOR_GREEN = 'FF99FF66';
const COLOR_RED = 'FFFF5050';
const COLOR_BLUE = 'FF5050FF';
const COLOR_YELLOW = 'FFFFFF50';
public function testConditionalText(): void
{
$format = 'Xlsx';
$spreadsheet = new Spreadsheet();
$conditionalStyles = [];
// if text contains 'anywhere' - red background
$condition0 = new Conditional();
$condition0->setConditionType(Conditional::CONDITION_CONTAINSTEXT);
$condition0->setOperatorType(Conditional::CONDITION_CONTAINSTEXT);
$condition0->setText('anywhere');
$condition0->getStyle()->getFill()
->setFillType(Fill::FILL_SOLID)
->getEndColor()->setARGB(self::COLOR_RED);
array_push($conditionalStyles, $condition0);
// if text contains 'Left' on left - green background
$condition1 = new Conditional();
$condition1->setConditionType(Conditional::CONDITION_CONTAINSTEXT);
$condition1->setOperatorType(Conditional::OPERATOR_BEGINSWITH);
$condition1->setText('Left');
$condition1->getStyle()->getFill()
->setFillType(Fill::FILL_SOLID)
->getEndColor()->setARGB(self::COLOR_GREEN);
array_push($conditionalStyles, $condition1);
// if text contains 'right' on right - blue background
$condition2 = new Conditional();
$condition2->setConditionType(Conditional::CONDITION_CONTAINSTEXT);
$condition2->setOperatorType(Conditional::OPERATOR_ENDSWITH);
$condition2->setText('right');
$condition2->getStyle()->getFill()
->setFillType(Fill::FILL_SOLID)
->getEndColor()->setARGB(self::COLOR_BLUE);
array_push($conditionalStyles, $condition2);
// if text contains no spaces - yellow background
$condition3 = new Conditional();
$condition3->setConditionType(Conditional::CONDITION_CONTAINSTEXT);
$condition3->setOperatorType(Conditional::OPERATOR_NOTCONTAINS);
$condition3->setText(' ');
$condition3->getStyle()->getFill()
->setFillType(Fill::FILL_SOLID)
->getEndColor()->setARGB(self::COLOR_YELLOW);
array_push($conditionalStyles, $condition3);
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('B1', 'This should match anywhere, right?');
$sheet->setCellValue('B2', 'This should match nowhere, right?');
$sheet->setCellValue('B3', 'Left match');
$sheet->setCellValue('B4', 'Match on right');
$sheet->setCellValue('B5', 'nospaces');
$xpCoordinate = 'B1:B5';
$spreadsheet->getActiveSheet()->setConditionalStyles($xpCoordinate, $conditionalStyles);
$sheet->getColumnDimension('B')->setAutoSize(true);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
// see if we successfully written conditional text elements
$newConditionalStyles = $reloadedSpreadsheet->getActiveSheet()->getConditionalStyles($xpCoordinate);
$cnt = count($conditionalStyles);
for ($i = 0; $i < $cnt; ++$i) {
self::assertEquals(
$conditionalStyles[$i]->getConditionType(),
$newConditionalStyles[$i]->getConditionType(),
"Failure on condition type $i"
);
self::assertEquals(
$conditionalStyles[$i]->getOperatorType(),
$newConditionalStyles[$i]->getOperatorType(),
"Failure on operator type $i"
);
self::assertEquals(
$conditionalStyles[$i]->getText(),
$newConditionalStyles[$i]->getText(),
"Failure on text $i"
);
$filCond = $conditionalStyles[$i]->getStyle()->getFill();
$newCond = $newConditionalStyles[$i]->getStyle()->getFill();
self::assertEquals(
$filCond->getFillType(),
$newCond->getFillType(),
"Failure on fill type $i"
);
self::assertEquals(
$filCond->getEndColor()->getARGB(),
$newCond->getEndColor()->getARGB(),
"Failure on end color $i"
);
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/CommentsTest.php | tests/PhpSpreadsheetTests/Functional/CommentsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
class CommentsTest extends AbstractFunctional
{
public static function providerFormats(): array
{
return [
['Html'],
['Xlsx'],
['Ods'],
];
}
/**
* Test load file with comment in sheet to load proper
* count of comments in correct coords.
*/
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats')]
public function testComments(string $format): void
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->getCell('E10')->setValue('Comment');
$spreadsheet->getActiveSheet()
->getComment('E10')
->getText()
->createText('Comment to test');
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$sheet = $reloadedSpreadsheet->getSheet(0);
$commentsLoaded = $sheet->getComments();
self::assertCount(1, $commentsLoaded);
$commentCoordinate = key($commentsLoaded);
self::assertSame('E10', $commentCoordinate);
self::assertSame('Comment', $sheet->getCell('E10')->getValue());
$comment = $commentsLoaded[$commentCoordinate];
self::assertSame('Comment to test', (string) $comment);
$commentClone = clone $comment;
self::assertEquals($comment, $commentClone);
self::assertNotSame($comment, $commentClone);
if ($format === 'Xlsx') {
self::assertSame('bc7bcec8f676a333dae65c945cf8dace', $comment->getHashCode(), 'changed due to addition of theme to fillColor');
self::assertSame(Alignment::HORIZONTAL_GENERAL, $comment->getAlignment());
$comment->setAlignment(Alignment::HORIZONTAL_RIGHT);
self::assertSame(Alignment::HORIZONTAL_RIGHT, $comment->getAlignment());
}
$spreadsheet->disconnectWorksheets();
$reloadedSpreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/MergedCellsTest.php | tests/PhpSpreadsheetTests/Functional/MergedCellsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class MergedCellsTest extends AbstractFunctional
{
public static function providerFormats(): array
{
return [
['Html'],
['Xls'],
['Xlsx'],
['Ods'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats')]
public function testMergedCells(string $format): void
{
$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0);
$spreadsheet->getActiveSheet()->setCellValue('A1', '1');
$spreadsheet->getActiveSheet()->setCellValue('B1', '2');
$spreadsheet->getActiveSheet()->setCellValue('A2', '33');
$spreadsheet->getActiveSheet()->mergeCells('A2:B2');
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$actual = 0;
foreach ($reloadedSpreadsheet->getWorksheetIterator() as $worksheet) {
$actual += count($worksheet->getMergeCells());
}
self::assertSame(1, $actual, "Format $format failed, could not read 1 merged cell");
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/ReadFilterFilter.php | tests/PhpSpreadsheetTests/Functional/ReadFilterFilter.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
class ReadFilterFilter implements IReadFilter
{
/**
* @param string $column Column address (as a string value like "A", or "IV")
* @param int $row Row number
* @param string $worksheetName Optional worksheet name
*
* @see IReadFilter::readCell()
*/
public function readCell(string $column, int $row, string $worksheetName = ''): bool
{
// define filter range
$rowMin = 2;
$rowMax = 6;
$columnMin = 'B';
$columnMax = 'D';
$r = $row;
if ($r > $rowMax || $r < $rowMin) {
return false;
}
$col = sprintf('%04s', $column);
if (
$col > sprintf('%04s', $columnMax)
|| $col < sprintf('%04s', $columnMin)
) {
return false;
}
return true;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/AbstractFunctional.php | tests/PhpSpreadsheetTests/Functional/AbstractFunctional.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
/**
* Base class for functional test to write and reload file on disk across different formats.
*/
abstract class AbstractFunctional extends TestCase
{
/**
* Write spreadsheet to disk, reload and return it.
*/
protected function writeAndReload(Spreadsheet $spreadsheet, string $format, ?callable $readerCustomizer = null, ?callable $writerCustomizer = null): Spreadsheet
{
$filename = File::temporaryFilename();
try {
$writer = IOFactory::createWriter($spreadsheet, $format);
if ($writerCustomizer) {
$writerCustomizer($writer);
}
$writer->save($filename);
$reader = IOFactory::createReader($format);
if ($readerCustomizer) {
$readerCustomizer($reader);
}
$reloadedSpreadsheet = $reader->load($filename);
} finally {
@unlink($filename);
}
return $reloadedSpreadsheet;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/ReadBlankCellsTest.php | tests/PhpSpreadsheetTests/Functional/ReadBlankCellsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
class ReadBlankCellsTest extends AbstractFunctional
{
public static function providerSheetFormat(): array
{
return [
['Xlsx', false],
['Xls', true],
['Ods', true],
['Csv', false],
['Html', false],
];
}
/**
* Test load file with explicitly empty cells.
*/
public function testLoadReadEmptyCells(): void
{
$filename = 'tests/data/Reader/XLSX/blankcell.xlsx';
$reader = new Xlsx();
$reloadedSpreadsheet = $reader->load($filename);
self::assertTrue($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('B2'));
self::assertFalse($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('C2'));
self::assertTrue($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('C3'));
$reloadedSpreadsheet->disconnectWorksheets();
}
/**
* Test load file ignoring empty cells.
*/
public function testLoadDontReadEmptyCells(): void
{
$filename = 'tests/data/Reader/XLSX/blankcell.xlsx';
$reader = new Xlsx();
$reader->setReadEmptyCells(false);
$reloadedSpreadsheet = $reader->load($filename);
self::assertFalse($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('B2'));
self::assertFalse($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('C2'));
self::assertTrue($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('C3'));
$reloadedSpreadsheet->disconnectWorksheets();
}
/**
* Test load file ignoring empty cells.
*/
public function testLoadDontReadEmptyCellsFlag(): void
{
$filename = 'tests/data/Reader/XLSX/blankcell.xlsx';
$reader = new Xlsx();
$reloadedSpreadsheet = $reader->load($filename, Xlsx::IGNORE_EMPTY_CELLS);
self::assertFalse($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('B2'));
self::assertFalse($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('C2'));
self::assertTrue($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('C3'));
$reloadedSpreadsheet->disconnectWorksheets();
}
/**
* Test generate file with some empty cells.
*/
#[\PHPUnit\Framework\Attributes\DataProvider('providerSheetFormat')]
public function testLoadAndSaveReadEmpty(string $format, bool $expected): void
{
$filename = 'tests/data/Reader/XLSX/blankcell.xlsx';
$reader = new Xlsx();
//$reader->setReadEmptyCells(false);
$spreadsheet = $reader->load($filename);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$spreadsheet->disconnectWorksheets();
self::assertSame($expected, $reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('B2'));
if ($expected) {
self::assertContains($reloadedSpreadsheet->getActiveSheet()->getCell('B2')->getValue(), ['', null]);
}
self::assertFalse($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('C2'));
self::assertTrue($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('C3'));
$reloadedSpreadsheet->disconnectWorksheets();
}
/**
* Test generate file with some empty cells.
*/
#[\PHPUnit\Framework\Attributes\DataProvider('providerSheetFormat')]
public function testLoadAndSaveDontReadEmpty(string $format, mixed $expected): void
{
if (!is_bool($expected)) {
self::fail('unexpected unused arg');
}
$filename = 'tests/data/Reader/XLSX/blankcell.xlsx';
$reader = new Xlsx();
$reader->setReadEmptyCells(false);
$spreadsheet = $reader->load($filename);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
$spreadsheet->disconnectWorksheets();
self::assertFalse($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('B2'));
self::assertFalse($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('C2'));
self::assertTrue($reloadedSpreadsheet->getActiveSheet()->getCellCollection()->has('C3'));
$reloadedSpreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/StreamTest.php | tests/PhpSpreadsheetTests/Functional/StreamTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class StreamTest extends TestCase
{
public static function providerFormats(): array
{
$providerFormats = [
['Xls'],
['Xlsx'],
['Ods'],
['Csv'],
['Html'],
['Mpdf'],
['Dompdf'],
['Tcpdf'],
];
return $providerFormats;
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats')]
public function testAllWritersCanWriteToStream(string $format): void
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->setCellValue('A1', 'foo');
$writer = IOFactory::createWriter($spreadsheet, $format);
$stream = fopen('php://memory', 'wb+');
$stat = ($stream === false) ? false : fstat($stream);
if ($stream === false || $stat === false) {
self::fail('fopen or fstat failed');
} else {
self::assertSame(0, $stat['size']);
$writer->save($stream);
self::assertIsResource($stream, 'should not close the stream for further usage out of PhpSpreadsheet');
$stat = fstat($stream);
if ($stat === false) {
self::fail('fstat failed');
} else {
self::assertGreaterThan(0, $stat['size'], 'something should have been written to the stream');
}
self::assertGreaterThan(0, ftell($stream), 'should not be rewinded, because not all streams support it');
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Functional/ConditionalStopIfTrueTest.php | tests/PhpSpreadsheetTests/Functional/ConditionalStopIfTrueTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Functional;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class ConditionalStopIfTrueTest extends AbstractFunctional
{
const COLOR_GREEN = 'FF99FF66';
const COLOR_RED = 'FFFF5050';
public static function providerFormats(): array
{
return [
['Xlsx'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerFormats')]
public function testConditionalStopIfTrue(string $format): void
{
$pCoordinate = 'A1:A3';
// if blank cell -> no styling
$condition0 = new \PhpOffice\PhpSpreadsheet\Style\Conditional();
$condition0->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_EXPRESSION);
$condition0->addCondition('LEN(TRIM(A1))=0');
$condition0->setStopIfTrue(true); // ! stop here
// if value below 0.6 (matches also blank cells!) -> red background
$condition1 = new \PhpOffice\PhpSpreadsheet\Style\Conditional();
$condition1->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS);
$condition1->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_LESSTHAN);
$condition1->addCondition(0.6);
$condition1->getStyle()->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()->setARGB(self::COLOR_RED);
// if value above 0.6 -> green background
$condition2 = new \PhpOffice\PhpSpreadsheet\Style\Conditional();
$condition2->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS);
$condition2->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_GREATERTHAN);
$condition2->addCondition(0.6);
$condition2->getStyle()->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()->setARGB(self::COLOR_GREEN);
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->getCell('A1')->setValue(0.7);
$spreadsheet->getActiveSheet()->getCell('A2')->setValue('');
$spreadsheet->getActiveSheet()->getCell('A3')->setValue(0.4);
// put all three conditions in sheet
$conditionalStyles = [];
array_push($conditionalStyles, $condition0);
array_push($conditionalStyles, $condition1);
array_push($conditionalStyles, $condition2);
$spreadsheet->getActiveSheet()->setConditionalStyles($pCoordinate, $conditionalStyles);
$reloadedSpreadsheet = $this->writeAndReload($spreadsheet, $format);
// see if we successfully written "StopIfTrue"
$newConditionalStyles = $reloadedSpreadsheet->getActiveSheet()->getConditionalStyles($pCoordinate);
self::assertTrue($newConditionalStyles[0]->getStopIfTrue(), 'StopIfTrue should be set (=true) on first condition');
self::assertFalse($newConditionalStyles[1]->getStopIfTrue(), 'StopIfTrue should not be set (=false) on second condition');
self::assertFalse($newConditionalStyles[2]->getStopIfTrue(), 'StopIfTrue should not be set (=false) on third condition');
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Collection/SimpleCache3xxx.php | tests/PhpSpreadsheetTests/Collection/SimpleCache3xxx.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Collection;
use DateInterval;
use PhpOffice\PhpSpreadsheet\Collection\Memory\SimpleCache3;
class SimpleCache3xxx extends SimpleCache3
{
public static int $useCount = 0;
public function set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool
{
++self::$useCount;
if (self::$useCount >= 4) {
return false;
}
return parent::set($key, $value, $ttl);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Collection/CellsTest.php | tests/PhpSpreadsheetTests/Collection/CellsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Collection;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Collection\Cells;
use PhpOffice\PhpSpreadsheet\Collection\Memory;
use PhpOffice\PhpSpreadsheet\Settings;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\TestCase;
class CellsTest extends TestCase
{
public function testCollectionCell(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$collection = $sheet->getCellCollection();
// Assert empty state
self::assertEquals([], $collection->getCoordinates(), 'cell list should be empty');
self::assertEquals([], $collection->getSortedCoordinates(), 'sorted cell list should be empty');
$getB2 = $collection->get('B2');
self::assertNull($getB2, 'getting non-existing cell must return null');
self::assertFalse($collection->has('B2'), 'non-existing cell should be non-existent');
// Add one cell
$cell1 = $sheet->getCell('B2');
self::assertSame($cell1, $collection->add('B2', $cell1), 'adding a cell should return the cell');
// Assert cell presence
self::assertEquals(['B2'], $collection->getCoordinates(), 'cell list should contains the B2 cell');
self::assertEquals(['B2'], $collection->getSortedCoordinates(), 'sorted cell list contains the B2 cell');
self::assertSame($cell1, $collection->get('B2'), 'should get exact same object');
self::assertTrue($collection->has('B2'), 'B2 cell should exists');
// Add a second cell
$cell2 = $sheet->getCell('A1');
self::assertSame($cell2, $collection->add('A1', $cell2), 'adding a second cell should return the cell');
self::assertEquals(['B2', 'A1'], $collection->getCoordinates(), 'cell list should contains the second cell');
// Note that sorts orders the collection itself, so these cells will aread be ordered for the subsequent asserions
self::assertEquals(['A1', 'B2'], $collection->getSortedCoordinates(), 'sorted cell list contains the second cell');
// Add a third cell
$cell3 = $sheet->getCell('AA1');
self::assertSame($cell3, $collection->add('AA1', $cell3), 'adding a third cell should return the cell');
self::assertEquals(['A1', 'B2', 'AA1'], $collection->getCoordinates(), 'cell list should contains the third cell');
// Note that sorts orders the collection itself, so these cells will aread be ordered for the subsequent asserions
self::assertEquals(['A1', 'AA1', 'B2'], $collection->getSortedCoordinates(), 'sorted cell list contains the third cell');
// Add a fourth cell
$cell4 = $sheet->getCell('Z1');
self::assertSame($cell4, $collection->add('Z1', $cell4), 'adding a fourth cell should return the cell');
self::assertEquals(['A1', 'AA1', 'B2', 'Z1'], $collection->getCoordinates(), 'cell list should contains the fourth cell');
// Note that sorts orders the collection itself, so these cells will aread be ordered for the subsequent asserions
self::assertEquals(['A1', 'Z1', 'AA1', 'B2'], $collection->getSortedCoordinates(), 'sorted cell list contains the fourth cell');
// Assert collection copy
$sheet2 = $spreadsheet->createSheet();
$collection2 = $collection->cloneCellCollection($sheet2);
self::assertTrue($collection2->has('A1'));
$copiedCell2 = $collection2->get('A1');
self::assertNotNull($copiedCell2);
self::assertNotSame($cell2, $copiedCell2, 'copied cell should not be the same object any more');
self::assertSame($collection2, $copiedCell2->getParent(), 'copied cell should be owned by the copied collection');
self::assertSame('A1', $copiedCell2->getCoordinate(), 'copied cell should keep attributes');
// Assert deletion
$collection->delete('B2');
self::assertFalse($collection->has('B2'), 'cell should have been deleted');
self::assertEquals(['A1', 'Z1', 'AA1'], $collection->getCoordinates(), 'cell list should still contains the A1,Z1 and A11 cells');
// Assert update
$cell2 = $sheet->getCell('A1');
self::assertSame($sheet->getCellCollection(), $collection);
self::assertSame($cell2, $collection->update($cell2), 'should update existing cell');
$cell3 = $sheet->getCell('C3');
self::assertSame($cell3, $collection->update($cell3), 'should silently add non-existing C3 cell');
self::assertEquals(['A1', 'Z1', 'AA1', 'C3'], $collection->getCoordinates(), 'cell list should contains the C3 cell');
$spreadsheet->disconnectWorksheets();
}
public function testCacheLastCell(): void
{
$workbook = new Spreadsheet();
$cells = ['A1', 'A2'];
$sheet = $workbook->getActiveSheet();
$sheet->setCellValue('A1', 1);
$sheet->setCellValue('A2', 2);
self::assertEquals($cells, $sheet->getCoordinates(), 'list should include last added cell');
$workbook->disconnectWorksheets();
}
public function testCanGetCellAfterAnotherIsDeleted(): void
{
$workbook = new Spreadsheet();
$sheet = $workbook->getActiveSheet();
$collection = $sheet->getCellCollection();
$sheet->setCellValue('A1', 1);
$sheet->setCellValue('A2', 1);
$collection->delete('A1');
$sheet->setCellValue('A3', 1);
self::assertNotNull($collection->get('A2'), 'should be able to get back the cell even when another cell was deleted while this one was the current one');
$workbook->disconnectWorksheets();
}
public function testThrowsWhenCellCannotBeRetrievedFromCache(): void
{
$this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class);
$collection = $this->getMockBuilder(Cells::class)
->setConstructorArgs([
new Worksheet(),
Settings::useSimpleCacheVersion3() ? new Memory\SimpleCache3() : new Memory\SimpleCache1(),
])
->onlyMethods(['has'])
->getMock();
$collection->method('has')
->willReturn(true);
$collection->get('A2');
}
public function testThrowsWhenCellCannotBeStoredInCache(): void
{
$this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class);
$cache = $this->createMock(
Settings::useSimpleCacheVersion3() ? Memory\SimpleCache3::class : Memory\SimpleCache1::class
);
$cell = $this->createMock(Cell::class);
$cache->method('set')
->willReturn(false);
$collection = new Cells(new Worksheet(), $cache);
$collection->add('A1', $cell);
$collection->add('A2', $cell);
}
public function testGetHighestColumn(): void
{
$workbook = new Spreadsheet();
$sheet = $workbook->getActiveSheet();
$collection = $sheet->getCellCollection();
// check for empty sheet
self::assertEquals('A', $collection->getHighestColumn());
self::assertEquals('A', $collection->getHighestColumn(1));
// set a value and check again
$sheet->getCell('C4')->setValue(1);
self::assertEquals('C', $collection->getHighestColumn());
self::assertEquals('A', $collection->getHighestColumn(1));
self::assertEquals('C', $collection->getHighestColumn(4));
$workbook->disconnectWorksheets();
}
public function testGetHighestColumnBad(): void
{
$this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class);
$this->expectExceptionMessage('Row number must be a positive integer');
$workbook = new Spreadsheet();
$sheet = $workbook->getActiveSheet();
$collection = $sheet->getCellCollection();
// check for empty sheet
self::assertEquals('A', $collection->getHighestColumn());
$collection->getHighestColumn(0);
$workbook->disconnectWorksheets();
}
public function testRemoveRowBad(): void
{
$this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class);
$this->expectExceptionMessage('Row number must be a positive integer');
$workbook = new Spreadsheet();
$sheet = $workbook->getActiveSheet();
$collection = $sheet->getCellCollection();
$collection->removeRow(0);
$workbook->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Collection/Cells2Test.php | tests/PhpSpreadsheetTests/Collection/Cells2Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Collection;
use PhpOffice\PhpSpreadsheet\Collection\Cells;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\TestCase;
class Cells2Test extends TestCase
{
public function testThrowsWhenCellCannotBeStoredInClonedCache(): void
{
$this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class);
$this->expectExceptionMessage('Failed to copy cells in cache');
$cache = new SimpleCache3xxx();
$worksheet = new Worksheet();
$collection = new Cells($worksheet, $cache);
$collection->add('A1', $worksheet->getCell('A1'));
$collection->add('A2', $worksheet->getCell('A2'));
$collection->cloneCellCollection($worksheet);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/BaseNoLoad.php | tests/PhpSpreadsheetTests/Reader/BaseNoLoad.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader;
use PhpOffice\PhpSpreadsheet\Reader\BaseReader;
class BaseNoLoad extends BaseReader
{
public function canRead(string $filename): bool
{
return $filename !== '';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/CreateBlankSheetIfNoneReadTest.php | tests/PhpSpreadsheetTests/Reader/CreateBlankSheetIfNoneReadTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class CreateBlankSheetIfNoneReadTest extends TestCase
{
#[DataProvider('providerIdentify')]
public function testExceptionIfNoSheet(string $file, string $expectedName, string $expectedClass): void
{
$this->expectException(SpreadsheetException::class);
$this->expectExceptionMessage('out of bounds index: 0');
$actual = IOFactory::identify($file);
self::assertSame($expectedName, $actual);
$reader = IOFactory::createReaderForFile($file);
self::assertSame($expectedClass, $reader::class);
$sheetlist = ['Unknown sheetname'];
$reader->setLoadSheetsOnly($sheetlist);
$reader->load($file);
}
#[DataProvider('providerIdentify')]
public function testCreateSheetIfNoSheet(string $file, string $expectedName, string $expectedClass): void
{
$actual = IOFactory::identify($file);
self::assertSame($expectedName, $actual);
$reader = IOFactory::createReaderForFile($file);
self::assertSame($expectedClass, $reader::class);
$reader->setCreateBlankSheetIfNoneRead(true);
$sheetlist = ['Unknown sheetname'];
$reader->setLoadSheetsOnly($sheetlist);
$spreadsheet = $reader->load($file);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('Worksheet', $sheet->getTitle());
self::assertCount(1, $spreadsheet->getAllSheets());
$spreadsheet->disconnectWorksheets();
}
public static function providerIdentify(): array
{
return [
['samples/templates/26template.xlsx', 'Xlsx', Reader\Xlsx::class],
['samples/templates/GnumericTest.gnumeric', 'Gnumeric', Reader\Gnumeric::class],
['samples/templates/30template.xls', 'Xls', Reader\Xls::class],
['samples/templates/OOCalcTest.ods', 'Ods', Reader\Ods::class],
['samples/templates/excel2003.xml', 'Xml', Reader\Xml::class],
];
}
public function testUsingFlage(): void
{
$file = 'samples/templates/26template.xlsx';
$reader = IOFactory::createReaderForFile($file);
$sheetlist = ['Unknown sheetname'];
$reader->setLoadSheetsOnly($sheetlist);
$spreadsheet = $reader->load($file, Reader\BaseReader::CREATE_BLANK_SHEET_IF_NONE_READ);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('Worksheet', $sheet->getTitle());
self::assertCount(1, $spreadsheet->getAllSheets());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/BaseNoLoadTest.php | tests/PhpSpreadsheetTests/Reader/BaseNoLoadTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use PHPUnit\Framework\TestCase;
class BaseNoLoadTest extends TestCase
{
public function testBaseNoLoad(): void
{
$this->expectException(SpreadsheetException::class);
$this->expectExceptionMessage('Reader classes must implement their own loadSpreadsheetFromFile() method');
$reader = new BaseNoLoad();
$reader->load('unknown.file');
}
public function testBaseNoLoadInfo(): void
{
$this->expectException(SpreadsheetException::class);
$this->expectExceptionMessage('Reader classes must implement their own listWorksheetInfo() method');
$reader = new BaseNoLoad();
$reader->listWorksheetInfo('unknown.file');
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/Rc4Test.php | tests/PhpSpreadsheetTests/Reader/Xls/Rc4Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls\RC4;
use PHPUnit\Framework\TestCase;
class Rc4Test extends TestCase
{
public function testRc4(): void
{
// following result confirmed at:
// https://cryptii.com/pipes/rc4-encryption
$key = "\x63\x72\x79\x70\x74\x69\x69";
$string = 'The quick brown fox jumps over the lazy dog.';
$rc4 = new RC4($key);
$result = bin2hex($rc4->RC4($string));
$expectedResult = '2ac2fecdd8fbb84638e3a4820eb205cc8e29c28b9d5d6b2ef974f311964971c90e8b9ca16467ef2dc6fc3520';
self::assertSame($expectedResult, $result);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/PageSetupTest.php | tests/PhpSpreadsheetTests/Reader/Xls/PageSetupTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PHPUnit\Framework\TestCase;
class PageSetupTest extends TestCase
{
private const MARGIN_PRECISION = 0.00000001;
private const MARGIN_UNIT_CONVERSION = 2.54; // Inches to cm
public function testPageSetup(): void
{
$filename = 'tests/data/Reader/XLS/PageSetup.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$assertions = $this->pageSetupAssertions();
$sheetCount = 0;
foreach ($spreadsheet->getAllSheets() as $worksheet) {
++$sheetCount;
if (!array_key_exists($worksheet->getTitle(), $assertions)) {
self::fail('Unexpected worksheet ' . $worksheet->getTitle());
}
$sheetAssertions = $assertions[$worksheet->getTitle()];
foreach ($sheetAssertions as $test => $expectedResult) {
$testMethodName = 'get' . ucfirst($test);
$actualResult = $worksheet->getPageSetup()->$testMethodName();
self::assertSame(
$expectedResult,
$actualResult,
"Failed assertion for Worksheet '{$worksheet->getTitle()}' {$test}"
);
}
}
self::assertCount($sheetCount, $assertions);
$spreadsheet->disconnectWorksheets();
}
public function testPageMargins(): void
{
$filename = 'tests/data/Reader/XLS/PageSetup.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$assertions = $this->pageMarginAssertions();
$sheetCount = 0;
foreach ($spreadsheet->getAllSheets() as $worksheet) {
++$sheetCount;
if (!array_key_exists($worksheet->getTitle(), $assertions)) {
self::fail('Unexpected worksheet ' . $worksheet->getTitle());
}
$sheetAssertions = $assertions[$worksheet->getTitle()];
foreach ($sheetAssertions as $test => $expectedResult) {
$testMethodName = 'get' . ucfirst($test);
$actualResult = $worksheet->getPageMargins()->$testMethodName();
self::assertEqualsWithDelta(
$expectedResult,
$actualResult,
self::MARGIN_PRECISION,
"Failed assertion for Worksheet '{$worksheet->getTitle()}' {$test} margin"
);
}
}
self::assertCount($sheetCount, $assertions);
$spreadsheet->disconnectWorksheets();
}
/** @return array<array{orientation: string, scale: int, horizontalCentered: bool, verticalCentered: bool, pageOrder: string}> */
private function pageSetupAssertions(): array
{
return [
'Sheet1' => [
'orientation' => PageSetup::ORIENTATION_PORTRAIT,
'scale' => 75,
'horizontalCentered' => true,
'verticalCentered' => false,
'pageOrder' => PageSetup::PAGEORDER_DOWN_THEN_OVER,
],
'Sheet2' => [
'orientation' => PageSetup::ORIENTATION_LANDSCAPE,
'scale' => 100,
'horizontalCentered' => false,
'verticalCentered' => true,
'pageOrder' => PageSetup::PAGEORDER_OVER_THEN_DOWN,
],
'Sheet3' => [
'orientation' => PageSetup::ORIENTATION_PORTRAIT,
'scale' => 90,
'horizontalCentered' => true,
'verticalCentered' => true,
'pageOrder' => PageSetup::PAGEORDER_DOWN_THEN_OVER,
],
'Sheet4' => [
// Default Settings
'orientation' => PageSetup::ORIENTATION_DEFAULT,
'scale' => 100,
'horizontalCentered' => false,
'verticalCentered' => false,
'pageOrder' => PageSetup::PAGEORDER_DOWN_THEN_OVER,
],
];
}
/** @return array<array{top: float, header: float, left: float, right: float, bottom: float, footer: float}> */
private function pageMarginAssertions(): array
{
return [
'Sheet1' => [
// Here the values are in cm, so we convert to inches for comparison with internal uom
'top' => 2.4 / self::MARGIN_UNIT_CONVERSION,
'header' => 0.8 / self::MARGIN_UNIT_CONVERSION,
'left' => 1.3 / self::MARGIN_UNIT_CONVERSION,
'right' => 1.3 / self::MARGIN_UNIT_CONVERSION,
'bottom' => 1.9 / self::MARGIN_UNIT_CONVERSION,
'footer' => 0.8 / self::MARGIN_UNIT_CONVERSION,
],
'Sheet2' => [
// Here the values are in cm, so we convert to inches for comparison with internal uom
'top' => 1.9 / self::MARGIN_UNIT_CONVERSION,
'header' => 0.8 / self::MARGIN_UNIT_CONVERSION,
'left' => 1.8 / self::MARGIN_UNIT_CONVERSION,
'right' => 1.8 / self::MARGIN_UNIT_CONVERSION,
'bottom' => 1.9 / self::MARGIN_UNIT_CONVERSION,
'footer' => 0.8 / self::MARGIN_UNIT_CONVERSION,
],
'Sheet3' => [
// Here the values are in cm, so we convert to inches for comparison with internal uom
'top' => 2.4 / self::MARGIN_UNIT_CONVERSION,
'header' => 1.3 / self::MARGIN_UNIT_CONVERSION,
'left' => 1.8 / self::MARGIN_UNIT_CONVERSION,
'right' => 1.8 / self::MARGIN_UNIT_CONVERSION,
'bottom' => 2.4 / self::MARGIN_UNIT_CONVERSION,
'footer' => 1.3 / self::MARGIN_UNIT_CONVERSION,
],
'Sheet4' => [
// Default Settings (already in inches for comparison)
'top' => 0.75,
'header' => 0.3,
'left' => 0.7,
'right' => 0.7,
'bottom' => 0.75,
'footer' => 0.3,
],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/DateReaderTest.php | tests/PhpSpreadsheetTests/Reader/Xls/DateReaderTest.php | <?php
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PHPUnit\Framework\TestCase;
class DateReaderTest extends TestCase
{
protected function tearDown(): void
{
Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
}
public function testReadExcel1900Spreadsheet(): void
{
$filename = 'tests/data/Reader/XLS/1900_Calendar.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
self::assertSame(Date::CALENDAR_WINDOWS_1900, $spreadsheet->getExcelCalendar());
$worksheet = $spreadsheet->getActiveSheet();
self::assertSame(44562, $worksheet->getCell('A1')->getValue());
self::assertSame('2022-01-01', $worksheet->getCell('A1')->getFormattedValue());
self::assertSame(44926, $worksheet->getCell('A2')->getValue());
self::assertSame('2022-12-31', $worksheet->getCell('A2')->getFormattedValue());
$spreadsheet->disconnectWorksheets();
}
public function testReadExcel1904Spreadsheet(): void
{
$filename = 'tests/data/Reader/XLS/1904_Calendar.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
self::assertSame(Date::CALENDAR_MAC_1904, $spreadsheet->getExcelCalendar());
$worksheet = $spreadsheet->getActiveSheet();
self::assertSame(43100, $worksheet->getCell('A1')->getValue());
self::assertSame('2022-01-01', $worksheet->getCell('A1')->getFormattedValue());
self::assertSame(43464, $worksheet->getCell('A2')->getValue());
self::assertSame('2022-12-31', $worksheet->getCell('A2')->getFormattedValue());
$spreadsheet->disconnectWorksheets();
}
public function testNewDateInLoadedExcel1900Spreadsheet(): void
{
$filename = 'tests/data/Reader/XLS/1900_Calendar.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->getCell('A4')->setValue('=DATE(2023,1,1)');
self::assertEquals(44927, $worksheet->getCell('A4')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public function testNewDateInLoadedExcel1904Spreadsheet(): void
{
$filename = 'tests/data/Reader/XLS/1904_Calendar.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->getCell('A4')->setValue('=DATE(2023,1,1)');
self::assertEquals(43465, $worksheet->getCell('A4')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public function testSwitchCalendars(): void
{
$filename1904 = 'tests/data/Reader/XLS/1904_Calendar.xls';
$reader1904 = new Xls();
$spreadsheet1904 = $reader1904->load($filename1904);
$worksheet1904 = $spreadsheet1904->getActiveSheet();
$date1 = Date::convertIsoDate('2022-01-01');
self::assertSame(43100.0, $date1);
$filename1900 = 'tests/data/Reader/XLS/1900_Calendar.xls';
$reader1900 = new Xls();
$spreadsheet1900 = $reader1900->load($filename1900);
$worksheet1900 = $spreadsheet1900->getActiveSheet();
$date2 = Date::convertIsoDate('2022-01-01');
self::assertSame(44562.0, $date2);
self::assertSame(44562, $worksheet1900->getCell('A1')->getValue());
self::assertSame('2022-01-01', $worksheet1900->getCell('A1')->getFormattedValue());
self::assertSame(44926, $worksheet1900->getCell('A2')->getValue());
self::assertSame('2022-12-31', $worksheet1900->getCell('A2')->getFormattedValue());
self::assertSame(44561, $worksheet1900->getCell('B1')->getCalculatedValue());
self::assertSame('2021-12-31', $worksheet1900->getCell('B1')->getFormattedValue());
self::assertSame(44927, $worksheet1900->getCell('B2')->getCalculatedValue());
self::assertSame('2023-01-01', $worksheet1900->getCell('B2')->getFormattedValue());
self::assertSame(43100, $worksheet1904->getCell('A1')->getValue());
self::assertSame('2022-01-01', $worksheet1904->getCell('A1')->getFormattedValue());
self::assertSame(43464, $worksheet1904->getCell('A2')->getValue());
self::assertSame('2022-12-31', $worksheet1904->getCell('A2')->getFormattedValue());
self::assertSame(43099, $worksheet1904->getCell('B1')->getCalculatedValue());
self::assertSame('2021-12-31', $worksheet1904->getCell('B1')->getFormattedValue());
self::assertSame(43465, $worksheet1904->getCell('B2')->getCalculatedValue());
self::assertSame('2023-01-01', $worksheet1904->getCell('B2')->getFormattedValue());
// Check that accessing date values from one spreadsheet doesn't break accessing correct values from another
self::assertSame(44561, $worksheet1900->getCell('B1')->getCalculatedValue());
self::assertSame('2021-12-31', $worksheet1900->getCell('B1')->getFormattedValue());
self::assertSame(44927, $worksheet1900->getCell('B2')->getCalculatedValue());
self::assertSame('2023-01-01', $worksheet1900->getCell('B2')->getFormattedValue());
self::assertSame(44562, $worksheet1900->getCell('A1')->getValue());
self::assertSame('2022-01-01', $worksheet1900->getCell('A1')->getFormattedValue());
self::assertSame(44926, $worksheet1900->getCell('A2')->getValue());
self::assertSame('2022-12-31', $worksheet1900->getCell('A2')->getFormattedValue());
self::assertSame(43099, $worksheet1904->getCell('B1')->getCalculatedValue());
self::assertSame('2021-12-31', $worksheet1904->getCell('B1')->getFormattedValue());
self::assertSame(43465, $worksheet1904->getCell('B2')->getCalculatedValue());
self::assertSame('2023-01-01', $worksheet1904->getCell('B2')->getFormattedValue());
self::assertSame(43100, $worksheet1904->getCell('A1')->getValue());
self::assertSame('2022-01-01', $worksheet1904->getCell('A1')->getFormattedValue());
self::assertSame(43464, $worksheet1904->getCell('A2')->getValue());
self::assertSame('2022-12-31', $worksheet1904->getCell('A2')->getFormattedValue());
$spreadsheet1900->disconnectWorksheets();
$spreadsheet1904->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/DataValidationTest.php | tests/PhpSpreadsheetTests/Reader/Xls/DataValidationTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class DataValidationTest extends TestCase
{
/** @param mixed[] $expectedRule */
#[DataProvider('dataValidationProvider')]
public function testDataValidation(string $expectedRange, array $expectedRule): void
{
$filename = 'tests/data/Reader/XLS/DataValidation.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
$hasDataValidation = $sheet->dataValidationExists($expectedRange);
self::assertTrue($hasDataValidation);
$dataValidation = $sheet->getDataValidation($expectedRange);
self::assertSame($expectedRule['type'], $dataValidation->getType());
self::assertSame($expectedRule['operator'], $dataValidation->getOperator());
self::assertSame($expectedRule['formula'], $dataValidation->getFormula1());
$spreadsheet->disconnectWorksheets();
}
public static function dataValidationProvider(): array
{
return [
[
'B2',
[
'type' => DataValidation::TYPE_WHOLE,
'operator' => DataValidation::OPERATOR_GREATERTHANOREQUAL,
'formula' => '18',
],
],
[
'B3',
[
'type' => DataValidation::TYPE_LIST,
'operator' => DataValidation::OPERATOR_BETWEEN,
'formula' => '"Blocked,Pending,Approved"',
],
],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/LoadSheetsOnlyTest.php | tests/PhpSpreadsheetTests/Reader/Xls/LoadSheetsOnlyTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class LoadSheetsOnlyTest extends TestCase
{
private ?Spreadsheet $spreadsheet = null;
private static string $testbook = 'tests/data/Reader/XLS/HiddenSheet.xls';
protected function tearDown(): void
{
if ($this->spreadsheet !== null) {
$this->spreadsheet->disconnectWorksheets();
$this->spreadsheet = null;
}
}
public function testLoadSheet1Only(): void
{
$filename = self::$testbook;
$reader = new Xls();
//$reader->setLoadSheetsOnly(['Sheet1']);
$names = $reader->listWorksheetNames($filename);
$reader->setLoadSheetsOnly([$names[0]]);
$spreadsheet = $this->spreadsheet = $reader->load($filename);
self::assertSame(1, $spreadsheet->getSheetCount());
self::assertSame('Sheet1', $spreadsheet->getActiveSheet()->getTitle());
}
public function testLoadSheet2Only(): void
{
$filename = self::$testbook;
$reader = new Xls();
$reader->setLoadSheetsOnly(['Sheet2']);
$spreadsheet = $this->spreadsheet = $reader->load($filename);
self::assertSame(1, $spreadsheet->getSheetCount());
self::assertSame('Sheet2', $spreadsheet->getActiveSheet()->getTitle());
}
public function testLoadNoSheet(): void
{
$this->expectException(PhpSpreadsheetException::class);
$this->expectExceptionMessage('You tried to set a sheet active by the out of bounds index');
$filename = self::$testbook;
$reader = new Xls();
$reader->setLoadSheetsOnly(['Sheet3']);
$reader->load($filename);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/Pr607Test.php | tests/PhpSpreadsheetTests/Reader/Xls/Pr607Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Reader\Xls as XlsReader;
use PHPUnit\Framework\TestCase;
class Pr607Test extends TestCase
{
/**
* Test file with cell range expressed in unexpected manner.
*/
public static function testSumData(): void
{
$filename = 'tests/data/Reader/XLS/pr607.sum_data.xls';
$reader = new XlsReader();
$spreadsheet = $reader->load($filename);
$tests = [
'Test' => [
'A1' => 1,
'A2' => 2,
'A3' => 3,
'A4' => 4,
'A5' => 5,
'A6' => 6,
'A7' => 7,
'A8' => 8,
'A9' => 9,
'A10' => 10,
'B1' => 3,
'B2' => 4,
'B3' => 5,
'B4' => 6,
'B5' => 7,
'B6' => 8,
'B7' => 9,
'B8' => 10,
'B9' => 11,
'B10' => 12,
'C1' => 4,
'C2' => 6,
'C3' => 8,
'C4' => 10,
'C5' => 12,
'C6' => 14,
'C7' => 16,
'C8' => 18,
'C9' => 20,
'C10' => 22,
],
];
foreach ($tests as $sheetName => $testsForSheet) {
$sheet = $spreadsheet->getSheetByName($sheetName);
self::assertNotNull($sheet);
foreach ($testsForSheet as $cellCoordinate => $result) {
$calculatedValue = $sheet->getCell($cellCoordinate)->getCalculatedValue();
self::assertSame($result, $calculatedValue, "cell $cellCoordinate");
}
}
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/XlsSpecialCodePage.php | tests/PhpSpreadsheetTests/Reader/Xls/XlsSpecialCodePage.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Shared\CodePage;
class XlsSpecialCodePage extends \PhpOffice\PhpSpreadsheet\Reader\Xls
{
protected function readCodepage(): void
{
$length = self::getUInt2d($this->data, $this->pos + 2);
$recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
// move stream pointer to next record
$this->pos += 4 + $length;
// offset: 0; size: 2; code page identifier
$codepage = self::getUInt2d($recordData, 0);
if ($this->codepage === '') {
$this->codepage = CodePage::numberToName($codepage);
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/PageBreakTest.php | tests/PhpSpreadsheetTests/Reader/Xls/PageBreakTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class PageBreakTest extends AbstractFunctional
{
public function testPageBreak(): void
{
$filename = 'samples/templates/50_xlsverticalbreak.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
$pageSetup = $sheet->getPageSetup();
self::assertSame(PageSetup::PAGEORDER_DOWN_THEN_OVER, $pageSetup->getPageOrder());
$breaks = $sheet->getBreaks();
self::assertCount(2, $breaks);
self::assertSame(Worksheet::BREAK_ROW, $breaks['A5']);
self::assertSame(Worksheet::BREAK_COLUMN, $breaks['H1']);
$newSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls');
$spreadsheet->disconnectWorksheets();
$newSheet = $newSpreadsheet->getActiveSheet();
$newPageSetup = $newSheet->getPageSetup();
self::assertSame(PageSetup::PAGEORDER_DOWN_THEN_OVER, $newPageSetup->getPageOrder());
$newBreaks = $newSheet->getBreaks();
self::assertCount(2, $newBreaks);
self::assertSame(Worksheet::BREAK_ROW, $newBreaks['A5']);
self::assertSame(Worksheet::BREAK_COLUMN, $newBreaks['H1']);
$newSpreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/NumberFormatGeneralTest.php | tests/PhpSpreadsheetTests/Reader/Xls/NumberFormatGeneralTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class NumberFormatGeneralTest extends AbstractFunctional
{
public function testGeneral(): void
{
$filename = 'tests/data/Reader/XLS/issue2239.xls';
$contents = file_get_contents($filename) ?: '';
self::assertStringContainsString('GENERAL', $contents);
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getSheetByNameOrThrow('Blad1');
$array = $sheet->toArray();
self::assertSame('€ 2.95', $array[1][3]);
self::assertSame(2.95, $sheet->getCell('D2')->getValue());
self::assertSame(2.95, $sheet->getCell('D2')->getCalculatedValue());
self::assertSame('€ 2.95', $sheet->getCell('D2')->getFormattedValue());
self::assertSame('21', $array[1][4]);
self::assertSame(21, $sheet->getCell('E2')->getValue());
self::assertSame(21, $sheet->getCell('E2')->getCalculatedValue());
self::assertSame('21', $sheet->getCell('E2')->getFormattedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/HiddenMergeCellsTest.php | tests/PhpSpreadsheetTests/Reader/Xls/HiddenMergeCellsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PHPUnit\Framework\TestCase;
class HiddenMergeCellsTest extends TestCase
{
private const FILENAME = 'tests/data/Reader/XLS/HiddenMergeCellsTest.xls';
public function testHiddenMergeCells(): void
{
$reader = new Xls();
$spreadsheet = $reader->load(self::FILENAME);
$c2InMergeRange = $spreadsheet->getActiveSheet()->getCell('C2')->isInMergeRange();
self::assertTrue($c2InMergeRange);
$a2InMergeRange = $spreadsheet->getActiveSheet()->getCell('A2')->isInMergeRange();
self::assertTrue($a2InMergeRange);
$a2MergeRangeValue = $spreadsheet->getActiveSheet()->getCell('A2')->isMergeRangeValueCell();
self::assertTrue($a2MergeRangeValue);
$cellArray = $spreadsheet->getActiveSheet()->rangeToArray('A2:C2');
self::assertSame([['12', '4', '3']], $cellArray);
$cellArray = $spreadsheet->getActiveSheet()->rangeToArray('A2:C2', null, true, false);
self::assertSame([[12, 4, 3]], $cellArray);
$spreadsheet->disconnectWorksheets();
}
public function testUnmergeHiddenMergeCells(): void
{
$reader = new Xls();
$spreadsheet = $reader->load(self::FILENAME);
$spreadsheet->getActiveSheet()->unmergeCells('A2:C2');
$c2InMergeRange = $spreadsheet->getActiveSheet()->getCell('C2')->isInMergeRange();
self::assertFalse($c2InMergeRange);
$a2InMergeRange = $spreadsheet->getActiveSheet()->getCell('A2')->isInMergeRange();
self::assertFalse($a2InMergeRange);
$cellArray = $spreadsheet->getActiveSheet()->rangeToArray('A2:C2', null, false, false, false);
self::assertSame([[12, '=6-B1', '=A2/B2']], $cellArray);
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/RichTextSizeTest.php | tests/PhpSpreadsheetTests/Reader/Xls/RichTextSizeTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class RichTextSizeTest extends AbstractFunctional
{
public function testRichTextRunSize(): void
{
$filename = 'tests/data/Reader/XLS/RichTextFontSize.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getSheetByNameOrThrow('橱柜门板');
$text = $sheet->getCell('L15')->getValue();
self::assertInstanceOf(RichText::class, $text);
$elements = $text->getRichTextElements();
self::assertEquals(10, $elements[2]->getFont()?->getSize());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/Biff8CoverTest.php | tests/PhpSpreadsheetTests/Reader/Xls/Biff8CoverTest.php | <?php
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PHPUnit\Framework\TestCase;
class Biff8CoverTest extends TestCase
{
protected function tearDown(): void
{
Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
}
public function testBiff8Coverage(): void
{
$filename = 'tests/data/Reader/XLS/biff8cover.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('=SUM({1;2;3;4;5})', $sheet->getCell('A1')->getValue());
self::assertSame(15, $sheet->getCell('A1')->getCalculatedValue());
self::assertSame(
'=VLOOKUP("hello",'
. '{"what",1;"why",TRUE;"hello","there";"when",FALSE}'
. ',2,FALSE)',
$sheet->getCell('C1')->getValue()
);
self::assertSame('there', $sheet->getCell('C1')->getCalculatedValue());
self::assertSame(2, $sheet->getCell('A3')->getValue());
self::assertTrue(
$sheet->getStyle('A3')->getFont()->getSuperscript()
);
self::assertSame('n', $sheet->getCell('B3')->getValue());
self::assertTrue(
$sheet->getStyle('B3')->getFont()->getSubscript()
);
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/XlsBugPr3734Test.php | tests/PhpSpreadsheetTests/Reader/Xls/XlsBugPr3734Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PHPUnit\Framework\TestCase;
class XlsBugPr3734Test extends TestCase
{
/**
* Test XLS file including data with missing fonts?
*/
public function testXlsFileWithNoFontIndex(): void
{
$fileName = 'tests/data/Reader/XLS/bug-pr-3734.xls';
$spreadsheet = IOFactory::load($fileName);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('Calibri', $sheet->getStyle('A1')->getFont()->getName());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/Issue3202Test.php | tests/PhpSpreadsheetTests/Reader/Xls/Issue3202Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls as XlsReader;
use PHPUnit\Framework\TestCase;
class Issue3202Test extends TestCase
{
public function testSelectedCellWithConditionals(): void
{
// Unknown index notice when loading
$filename = 'tests/data/Reader/XLS/issue.3202.xls';
$reader = new XlsReader();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('A2', $sheet->getSelectedCells());
$collection = $sheet->getConditionalStylesCollection();
self::assertCount(1, $collection);
$conditionalArray = $collection['A1:A5'];
self::assertCount(3, $conditionalArray);
$conditions = $conditionalArray[0]->getConditions();
self::assertCount(1, $conditions);
self::assertSame('$A1=3', $conditions[0]);
self::assertTrue($conditionalArray[0]->getNoFormatSet());
self::assertTrue($conditionalArray[0]->getStopIfTrue());
$conditions = $conditionalArray[1]->getConditions();
self::assertCount(1, $conditions);
self::assertSame('$A1>5', $conditions[0]);
self::assertFalse($conditionalArray[1]->getNoFormatSet());
self::assertTrue($conditionalArray[1]->getStopIfTrue());
$conditions = $conditionalArray[2]->getConditions();
self::assertCount(1, $conditions);
self::assertSame('$A1>1', $conditions[0]);
self::assertFalse($conditionalArray[2]->getNoFormatSet());
self::assertTrue($conditionalArray[2]->getStopIfTrue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/SheetProtectionTest.php | tests/PhpSpreadsheetTests/Reader/Xls/SheetProtectionTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class SheetProtectionTest extends AbstractFunctional
{
public function testSheetProtection(): void
{
$originalSpreadsheet = new Spreadsheet();
$oldSheet = $originalSpreadsheet->getActiveSheet();
$oldProtection = $oldSheet->getProtection();
$oldProtection->setPassword('PhpSpreadsheet');
// setSheet should be true in order to enable protection!
$oldProtection->setSheet(true);
// The following are set to false, i.e. user is allowed to
// sort, insert rows, or format cells without unprotecting sheet.
$oldProtection->setSort(false);
$oldProtection->setInsertRows(false);
$oldProtection->setFormatCells(false);
$oldProtection->setFormatCells(false);
// Defaults below are true
$oldProtection->setSelectLockedCells(true);
$oldProtection->setSelectUnlockedCells(false);
$oldProtection->setScenarios(false);
$oldProtection->setObjects(true);
$spreadsheet = $this->writeAndReload($originalSpreadsheet, 'Xls');
$originalSpreadsheet->disconnectWorksheets();
$newSheet = $spreadsheet->getActiveSheet();
$protection = $newSheet->getProtection();
self::assertTrue($protection->verify('PhpSpreadsheet'));
self::assertTrue($protection->getSheet());
self::assertFalse($protection->getSort());
self::assertFalse($protection->getInsertRows());
self::assertFalse($protection->getFormatCells());
self::assertNotFalse($protection->getInsertColumns());
self::assertTrue($protection->getSelectLockedCells());
self::assertFalse($protection->getSelectUnlockedCells());
self::assertTrue($protection->getObjects());
self::assertFalse($protection->getScenarios());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/HiddenWorksheetTest.php | tests/PhpSpreadsheetTests/Reader/Xls/HiddenWorksheetTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\TestCase;
class HiddenWorksheetTest extends TestCase
{
public function testPageSetup(): void
{
$filename = 'tests/data/Reader/XLS/HiddenSheet.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$assertions = $this->worksheetAssertions();
$sheetCount = 0;
foreach ($spreadsheet->getAllSheets() as $worksheet) {
++$sheetCount;
if (!array_key_exists($worksheet->getTitle(), $assertions)) {
self::fail('Unexpected worksheet' . $worksheet->getTitle());
}
$sheetAssertions = $assertions[$worksheet->getTitle()];
foreach ($sheetAssertions as $test => $expectedResult) {
$actualResult = $worksheet->getSheetState();
self::assertSame(
$expectedResult,
$actualResult,
"Failed asserting sheet state {$expectedResult} for Worksheet '{$worksheet->getTitle()}' {$test}"
);
}
}
self::assertCount($sheetCount, $assertions);
$spreadsheet->disconnectWorksheets();
}
/** @return string[][] */
private function worksheetAssertions(): array
{
return [
'Sheet1' => [
'sheetState' => Worksheet::SHEETSTATE_VISIBLE,
],
'Sheet2' => [
'sheetState' => Worksheet::SHEETSTATE_HIDDEN,
],
];
}
public function testListWorksheetInfo(): void
{
$filename = 'tests/data/Reader/XLS/visibility.xls';
$reader = new Xls();
$expected = [
[
'worksheetName' => 'Sheet1',
'lastColumnLetter' => 'A',
'lastColumnIndex' => 0,
'totalRows' => 1,
'totalColumns' => 1,
'sheetState' => 'visible',
],
[
'worksheetName' => 'Sheet2',
'lastColumnLetter' => 'A',
'lastColumnIndex' => 0,
'totalRows' => 1,
'totalColumns' => 1,
'sheetState' => 'hidden',
],
[
'worksheetName' => 'Sheet3',
'lastColumnLetter' => 'A',
'lastColumnIndex' => 0,
'totalRows' => 1,
'totalColumns' => 1,
'sheetState' => 'visible',
],
[
'worksheetName' => 'Sheet4',
'lastColumnLetter' => 'A',
'lastColumnIndex' => 0,
'totalRows' => 2,
'totalColumns' => 1,
'sheetState' => 'veryHidden',
],
];
self::assertSame($expected, $reader->listWorksheetInfo($filename));
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/IsOddTest.php | tests/PhpSpreadsheetTests/Reader/Xls/IsOddTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PHPUnit\Framework\TestCase;
class IsOddTest extends TestCase
{
public function testIsOdd(): void
{
// Excel Xls treats ISODD and ISEVEN as 'Add-in functions'
// PhpSpreadsheet does not currently handle writing them.
// It should, however, read them correctly.
$filename = 'tests/data/Reader/XLS/isodd.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('=ISODD(5)', $sheet->getCell('A1')->getValue());
self::assertTrue($sheet->getCell('A1')->getCalculatedValue());
self::assertSame('=ISEVEN(5)', $sheet->getCell('B1')->getValue());
self::assertFalse($sheet->getCell('B1')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/Issue2463Test.php | tests/PhpSpreadsheetTests/Reader/Xls/Issue2463Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PHPUnit\Framework\TestCase;
class Issue2463Test extends TestCase
{
public function testNoUnknownIndexNotice(): void
{
// Unknown index notice when loading
$filename = 'tests/data/Reader/XLS/issue.2463.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('bol.com bestellingen', $sheet->getTitle());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/FormulasTest.php | tests/PhpSpreadsheetTests/Reader/Xls/FormulasTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls as WriterXls;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class FormulasTest extends AbstractFunctional
{
public function testFormulas(): void
{
// This file was created with Excel 365.
$filename = 'tests/data/Reader/XLS/formulas.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
$originalArray = $sheet->toArray(null, false, false, false);
$newSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls');
$spreadsheet->disconnectWorksheets();
$newWorksheet = $newSpreadsheet->getActiveSheet();
$newArray = $newWorksheet->toArray(null, false, false, false);
self::assertEquals($originalArray, $newArray);
$newSpreadsheet->disconnectWorksheets();
}
public function testDatabaseFormulas(): void
{
// This file was created with Excel 2003.
$filename = 'tests/data/Reader/XLS/formulas.database.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
$originalArray = $sheet->toArray(null, false, false, false);
$newSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls');
$spreadsheet->disconnectWorksheets();
$newWorksheet = $newSpreadsheet->getActiveSheet();
$newArray = $newWorksheet->toArray(null, false, false, false);
self::assertEquals($originalArray, $newArray);
$newSpreadsheet->disconnectWorksheets();
}
public function testOtherFormulas(): void
{
// This file was created with Excel 2003.
$filename = 'tests/data/Reader/XLS/formulas.other.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
$originalArray = $sheet->toArray(null, false, false, false);
$newSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls');
$spreadsheet->disconnectWorksheets();
$newWorksheet = $newSpreadsheet->getActiveSheet();
$newArray = $newWorksheet->toArray(null, false, false, false);
self::assertSame($originalArray, $newArray);
$newSpreadsheet->disconnectWorksheets();
}
public static function customizeWriter(WriterXls $writer): void
{
$writer->setPreCalculateFormulas(false);
}
public function testCaveatEmptor(): void
{
// This test confirms only that the 5 problematic functions
// in it are parsed correctly.
// When these are written to an Xls spreadsheet:
// Excel is buggy regarding their support; only BAHTTEXT
// will work as expected.
// LibreOffice handles them without problem.
// So does Gnumeric, except it doesn't implement BAHTTEXT.
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$originalArray = [
[1],
[2],
['=INDEX(TRANSPOSE(A1:A2),1,2)'],
['=BAHTTEXT(2)'],
['=CELL("ADDRESS",A3)'],
['=OFFSET(A3,-2,0)'],
['=GETPIVOTDATA("Sales",A3)'],
];
$sheet->fromArray($originalArray);
/** @var callable */
$writerCustomizer = [self::class, 'customizeWriter'];
$newSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls', null, $writerCustomizer);
$spreadsheet->disconnectWorksheets();
$newWorksheet = $newSpreadsheet->getActiveSheet();
$newArray = $newWorksheet->toArray(null, false, false, false);
self::assertSame($originalArray, $newArray);
$newSpreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/ConditionalFormattingBasicTest.php | tests/PhpSpreadsheetTests/Reader/Xls/ConditionalFormattingBasicTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class ConditionalFormattingBasicTest extends TestCase
{
/** @param mixed[][] $expectedRules */
#[DataProvider('conditionalFormattingProvider')]
public function testReadConditionalFormatting(string $expectedRange, array $expectedRules): void
{
$filename = 'tests/data/Reader/XLS/CF_Basic_Comparisons.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
$hasConditionalStyles = $sheet->conditionalStylesExists($expectedRange);
self::assertTrue($hasConditionalStyles);
$conditionalStyles = $sheet->getConditionalStyles($expectedRange);
foreach ($conditionalStyles as $index => $conditionalStyle) {
self::assertSame($expectedRules[$index]['type'], $conditionalStyle->getConditionType());
self::assertSame($expectedRules[$index]['operator'], $conditionalStyle->getOperatorType());
self::assertSame($expectedRules[$index]['conditions'], $conditionalStyle->getConditions());
}
$spreadsheet->disconnectWorksheets();
}
public static function conditionalFormattingProvider(): array
{
return [
[
'A2:E5',
[
[
'type' => Conditional::CONDITION_CELLIS,
'operator' => Conditional::OPERATOR_EQUAL,
'conditions' => [
0,
],
],
[
'type' => Conditional::CONDITION_CELLIS,
'operator' => Conditional::OPERATOR_GREATERTHAN,
'conditions' => [
0,
],
],
[
'type' => Conditional::CONDITION_CELLIS,
'operator' => Conditional::OPERATOR_LESSTHAN,
'conditions' => [
0,
],
],
],
],
[
'A10:E13',
[
[
'type' => Conditional::CONDITION_CELLIS,
'operator' => Conditional::OPERATOR_EQUAL,
'conditions' => [
'$H$9',
],
],
[
'type' => Conditional::CONDITION_CELLIS,
'operator' => Conditional::OPERATOR_GREATERTHAN,
'conditions' => [
'$H$9',
],
],
[
'type' => Conditional::CONDITION_CELLIS,
'operator' => Conditional::OPERATOR_LESSTHAN,
'conditions' => [
'$H$9',
],
],
],
],
[
'A18:A20',
[
[
'type' => Conditional::CONDITION_CELLIS,
'operator' => Conditional::OPERATOR_BETWEEN,
'conditions' => [
'$B1',
'$C1',
],
],
],
],
[
'A24:E27',
[
[
'type' => Conditional::CONDITION_CELLIS,
'operator' => Conditional::OPERATOR_BETWEEN,
'conditions' => [
'AVERAGE($A$24:$E$27)-STDEV($A$24:$E$27)',
'AVERAGE($A$24:$E$27)+STDEV($A$24:$E$27)',
],
],
[
'type' => Conditional::CONDITION_CELLIS,
'operator' => Conditional::OPERATOR_GREATERTHAN,
'conditions' => [
'AVERAGE($A$24:$E$27)+STDEV($A$24:$E$27)',
],
],
[
'type' => Conditional::CONDITION_CELLIS,
'operator' => Conditional::OPERATOR_LESSTHAN,
'conditions' => [
'AVERAGE($A$24:$E$27)-STDEV($A$24:$E$27)',
],
],
],
],
[
'A31:A33',
[
[
'type' => Conditional::CONDITION_CELLIS,
'operator' => Conditional::OPERATOR_EQUAL,
'conditions' => [
'"LOVE"',
],
],
[
'type' => Conditional::CONDITION_CELLIS,
'operator' => Conditional::OPERATOR_EQUAL,
'conditions' => [
'"PHP"',
],
],
],
],
];
}
public function testReadConditionalFormattingStyles(): void
{
$filename = 'tests/data/Reader/XLS/CF_Basic_Comparisons.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
$expectedRange = 'A2:E5';
$hasConditionalStyles = $sheet->conditionalStylesExists($expectedRange);
self::assertTrue($hasConditionalStyles);
$conditionalStyles = $sheet->getConditionalStyles($expectedRange);
self::assertCount(3, $conditionalStyles);
$style = $conditionalStyles[0]->getStyle();
$font = $style->getFont();
self::assertSame('FF0000FF', $font->getColor()->getArgb());
self::assertNull($font->getItalic());
self::assertNull($font->getStrikethrough());
// Fill not handled correctly - forget for now
$borders = $style->getBorders();
self::assertSame(Border::BORDER_OMIT, $borders->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_OMIT, $borders->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_OMIT, $borders->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_OMIT, $borders->getBottom()->getBorderStyle());
self::assertNull($style->getNumberFormat()->getFormatCode());
$style = $conditionalStyles[1]->getStyle();
$font = $style->getFont();
self::assertSame('FF800000', $font->getColor()->getArgb());
self::assertNull($font->getItalic());
self::assertNull($font->getStrikethrough());
// Fill not handled correctly - forget for now
$borders = $style->getBorders();
self::assertSame(Border::BORDER_OMIT, $borders->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_OMIT, $borders->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_OMIT, $borders->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_OMIT, $borders->getBottom()->getBorderStyle());
self::assertNull($style->getNumberFormat()->getFormatCode());
$style = $conditionalStyles[2]->getStyle();
$font = $style->getFont();
self::assertSame('FF00FF00', $font->getColor()->getArgb());
self::assertNull($font->getItalic());
self::assertNull($font->getStrikethrough());
// Fill not handled correctly - forget for now
$borders = $style->getBorders();
self::assertSame(Border::BORDER_OMIT, $borders->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_OMIT, $borders->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_OMIT, $borders->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_OMIT, $borders->getBottom()->getBorderStyle());
self::assertNull($style->getNumberFormat()->getFormatCode());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/Issue4356Test.php | tests/PhpSpreadsheetTests/Reader/Xls/Issue4356Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class Issue4356Test extends AbstractFunctional
{
public function testIssue4356(): void
{
// Reader couldn't handle sheet title with apostrophe for defined name.
// Issue was reported against Xlsx - see how Xls does.
$nameDefined = 'CELLNAME';
$originalSpreadsheet = new Spreadsheet();
$originalSheet = $originalSpreadsheet->getActiveSheet();
$originalSheet->setTitle("Goodn't sheet name");
$originalSpreadsheet->addNamedRange(
new NamedRange($nameDefined, $originalSheet, '$A$1')
);
$originalSheet->setCellValue('A1', 'This is a named cell.');
$originalSheet->getStyle($nameDefined)
->getFont()
->setItalic(true);
$spreadsheet = $this->writeAndReload($originalSpreadsheet, 'Xls');
$originalSpreadsheet->disconnectWorksheets();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('C1', "=$nameDefined");
self::assertSame('This is a named cell.', $sheet->getCell('C1')->getCalculatedValue());
$namedRange2 = $spreadsheet->getNamedRange($nameDefined);
self::assertNotNull($namedRange2);
$sheetx = $namedRange2->getWorksheet();
self::assertNotNull($sheetx);
$style = $sheetx->getStyle($nameDefined);
self::assertTrue($style->getFont()->getItalic());
$style->getFont()->setItalic(false);
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/NonExistentFileTest.php | tests/PhpSpreadsheetTests/Reader/Xls/NonExistentFileTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PHPUnit\Framework\TestCase;
class NonExistentFileTest extends TestCase
{
public function testNonExistentFile(): void
{
$temp = File::temporaryFileName();
file_put_contents($temp, '');
unlink($temp);
$reader = new Xls();
self::assertFalse($reader->canRead($temp));
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/ColorMapTest.php | tests/PhpSpreadsheetTests/Reader/Xls/ColorMapTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls\Color\BIFF5;
use PhpOffice\PhpSpreadsheet\Reader\Xls\Color\BIFF8;
use PhpOffice\PhpSpreadsheet\Reader\Xls\Color\BuiltIn;
use PHPUnit\Framework\TestCase;
class ColorMapTest extends TestCase
{
#[\PHPUnit\Framework\Attributes\DataProvider('colorMapProvider')]
public function testColorMap(int $index, string $expectedBiff5, string $expectedBiff8, string $expectedBuiltin): void
{
self::assertSame($expectedBiff5, BIFF5::lookup($index)['rgb']);
self::assertSame($expectedBiff8, BIFF8::lookup($index)['rgb']);
self::assertSame($expectedBuiltin, BuiltIn::lookup($index)['rgb']);
}
public static function colorMapProvider(): array
{
return [
'default builtin' => [0x00, '000000', '000000', '000000'],
'non-default builtin' => [0x02, '000000', '000000', 'FF0000'],
'system window text color' => [0x40, '000000', '000000', '000000'],
'system window background color' => [0x41, '000000', '000000', 'FFFFFF'],
'same biff5/8' => [0x09, 'FFFFFF', 'FFFFFF', '000000'],
'different biff5/8' => [0x29, '69FFFF', 'CCFFFF', '000000'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/Md5Test.php | tests/PhpSpreadsheetTests/Reader/Xls/Md5Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls\MD5;
use PHPUnit\Framework\TestCase;
class Md5Test extends TestCase
{
public function testMd5(): void
{
$md5 = new MD5();
$md5->add('123456789a123456789b123456789c123456789d123456789e123456789f1234');
$context = $md5->getContext();
self::assertSame('0761293f016b925b0bca11b34f1ed613', bin2hex($context));
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/DefinedNameTest.php | tests/PhpSpreadsheetTests/Reader/Xls/DefinedNameTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PHPUnit\Framework\TestCase;
class DefinedNameTest extends TestCase
{
public function testAbsoluteNamedRanges(): void
{
// Named Ranges were being converted from absolute to relative
$filename = 'tests/data/Reader/XLS/DefinedNameTest.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame($sheet->getCell('A7')->getCalculatedValue(), $sheet->getCell('B7')->getCalculatedValue());
self::assertSame($sheet->getCell('A8')->getCalculatedValue(), $sheet->getCell('B8')->getCalculatedValue());
self::assertSame($sheet->getCell('A9')->getCalculatedValue(), $sheet->getCell('B9')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/XlsTest.php | tests/PhpSpreadsheetTests/Reader/Xls/XlsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class XlsTest extends AbstractFunctional
{
/**
* Test load Xls file.
*/
public function testLoadXlsSample(): void
{
$filename = 'tests/data/Reader/XLS/sample.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
self::assertEquals('Title', $spreadsheet->getSheet(0)->getCell('A1')->getValue());
$spreadsheet->disconnectWorksheets();
}
/**
* Test load Xls file with invalid xfIndex.
*/
public function testLoadXlsBug1505(): void
{
$filename = 'tests/data/Reader/XLS/bug1505.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
$col = $sheet->getHighestColumn();
$row = $sheet->getHighestRow();
$newspreadsheet = $this->writeAndReload($spreadsheet, 'Xlsx');
$newsheet = $newspreadsheet->getActiveSheet();
$newcol = $newsheet->getHighestColumn();
$newrow = $newsheet->getHighestRow();
self::assertEquals($spreadsheet->getSheetCount(), $newspreadsheet->getSheetCount());
self::assertEquals($sheet->getTitle(), $newsheet->getTitle());
self::assertEquals($sheet->getColumnDimensions(), $newsheet->getColumnDimensions());
self::assertEquals($col, $newcol);
self::assertEquals($row, $newrow);
self::assertEquals($sheet->getCell('A1')->getFormattedValue(), $newsheet->getCell('A1')->getFormattedValue());
self::assertEquals($sheet->getCell("$col$row")->getFormattedValue(), $newsheet->getCell("$col$row")->getFormattedValue());
$spreadsheet->disconnectWorksheets();
$newspreadsheet->disconnectWorksheets();
}
/**
* Test load Xls file with invalid length in SST map.
*/
public function testLoadXlsBug1592(): void
{
$filename = 'tests/data/Reader/XLS/bug1592.xls';
$reader = new Xls();
// When no fix applied, spreadsheet is not loaded
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
$col = $sheet->getHighestColumn();
$row = $sheet->getHighestRow();
$newspreadsheet = $this->writeAndReload($spreadsheet, 'Xlsx');
$newsheet = $newspreadsheet->getActiveSheet();
$newcol = $newsheet->getHighestColumn();
$newrow = $newsheet->getHighestRow();
self::assertEquals($spreadsheet->getSheetCount(), $newspreadsheet->getSheetCount());
self::assertEquals($sheet->getTitle(), $newsheet->getTitle());
self::assertEquals($sheet->getColumnDimensions(), $newsheet->getColumnDimensions());
self::assertEquals($col, $newcol);
self::assertEquals($row, $newrow);
$rowIterator = $sheet->getRowIterator();
foreach ($rowIterator as $row) {
foreach ($row->getCellIterator() as $cellx) {
/** @var Cell */
$cell = $cellx;
$valOld = $cell->getFormattedValue();
$valNew = $newsheet->getCell($cell->getCoordinate())->getFormattedValue();
self::assertEquals($valOld, $valNew);
}
}
$spreadsheet->disconnectWorksheets();
$newspreadsheet->disconnectWorksheets();
}
public function testLoadXlsBug1114(): void
{
$filename = 'tests/data/Reader/XLS/bug1114.xls';
$spreadsheet = IOFactory::load($filename);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame(1148140800.0, $sheet->getCell('B2')->getValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/ConditionalItalicTest.php | tests/PhpSpreadsheetTests/Reader/Xls/ConditionalItalicTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class ConditionalItalicTest extends AbstractFunctional
{
public function testFormulas(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('A1')->setValue(1);
$sheet->getCell('A2')->setValue(9);
$sheet->getCell('A3')->setValue(5);
$sheet->getCell('A4')->setValue(2);
$sheet->getCell('A5')->setValue(8);
$condition1 = new Conditional();
$condition1->setConditionType(Conditional::CONDITION_CELLIS);
$condition1->setOperatorType(Conditional::OPERATOR_LESSTHAN);
$condition1->addCondition(5);
$condition1->getStyle()->getFont()->setItalic(true);
$condition2 = new Conditional();
$condition2->setConditionType(Conditional::CONDITION_CELLIS);
$condition2->setOperatorType(Conditional::OPERATOR_GREATERTHAN);
$condition2->addCondition(5);
$condition2->getStyle()->getFont()->setStrikeThrough(true)->setBold(true);
$conditionalStyles = [$condition1, $condition2];
$sheet->getStyle('A1:A5')->setConditionalStyles($conditionalStyles);
$newSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls');
$spreadsheet->disconnectWorksheets();
$sheet = $newSpreadsheet->getActiveSheet();
$conditionals = $sheet->getConditionalStylesCollection();
self::assertCount(1, $conditionals);
$cond1 = $conditionals['A1:A5'];
self::assertCount(2, $cond1);
$font = $cond1[0]->getStyle()->getFont();
self::assertTrue($font->getItalic());
self::assertNull($font->getBold());
self::assertNull($font->getStrikethrough());
$font = $cond1[1]->getStyle()->getFont();
self::assertNull($font->getItalic());
self::assertTrue($font->getBold());
self::assertTrue($font->getStrikethrough());
$newSpreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/ColourTest.php | tests/PhpSpreadsheetTests/Reader/Xls/ColourTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class ColourTest extends AbstractFunctional
{
private \PhpOffice\PhpSpreadsheet\Spreadsheet $spreadsheet;
protected function setup(): void
{
$filename = 'tests/data/Reader/XLS/Colours.xls';
$reader = new Xls();
$this->spreadsheet = $reader->load($filename);
}
public function testColours(): void
{
$colours = [];
$worksheet = $this->spreadsheet->getActiveSheet();
for ($row = 1; $row <= 7; ++$row) {
for ($column = 'A'; $column !== 'J'; StringHelper::stringIncrement($column)) {
$cellAddress = "{$column}{$row}";
$colours[$cellAddress] = $worksheet->getStyle($cellAddress)->getFill()->getStartColor()->getRGB();
}
}
$newSpreadsheet = $this->writeAndReload($this->spreadsheet, 'Xls');
$newWorksheet = $newSpreadsheet->getActiveSheet();
foreach ($colours as $cellAddress => $expectedColourValue) {
$actualColourValue = $newWorksheet->getStyle($cellAddress)->getFill()->getStartColor()->getRGB();
self::assertSame($expectedColourValue, $actualColourValue);
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/InfoNamesTest.php | tests/PhpSpreadsheetTests/Reader/Xls/InfoNamesTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Shared\CodePage;
use PHPUnit\Framework\TestCase;
class InfoNamesTest extends TestCase
{
public function testWorksheetNamesBiff5(): void
{
$filename = 'samples/templates/30templatebiff5.xls';
$reader = new Xls();
$names = $reader->listWorksheetNames($filename);
$expected = ['Invoice', 'Terms and conditions'];
self::assertSame($expected, $names);
}
public function testWorksheetInfoBiff5(): void
{
$filename = 'samples/templates/30templatebiff5.xls';
$reader = new Xls();
$info = $reader->listWorksheetInfo($filename);
$expected = [
[
'worksheetName' => 'Invoice',
'lastColumnLetter' => 'E',
'lastColumnIndex' => 4,
'totalRows' => 19,
'totalColumns' => 5,
'sheetState' => 'visible',
],
[
'worksheetName' => 'Terms and conditions',
'lastColumnLetter' => 'B',
'lastColumnIndex' => 1,
'totalRows' => 3,
'totalColumns' => 2,
'sheetState' => 'visible',
],
];
self::assertSame($expected, $info);
self::assertSame(Xls::XLS_BIFF7, $reader->getVersion());
self::assertSame('CP1252', $reader->getCodepage());
}
public function testWorksheetNamesBiff8(): void
{
$filename = 'samples/templates/31docproperties.xls';
$reader = new Xls();
$names = $reader->listWorksheetNames($filename);
$expected = ['Worksheet'];
self::assertSame($expected, $names);
}
public function testWorksheetInfoBiff8(): void
{
$filename = 'samples/templates/31docproperties.xls';
$reader = new Xls();
$info = $reader->listWorksheetInfo($filename);
$expected = [
[
'worksheetName' => 'Worksheet',
'lastColumnLetter' => 'B',
'lastColumnIndex' => 1,
'totalRows' => 1,
'totalColumns' => 2,
'sheetState' => 'visible',
],
];
self::assertSame($expected, $info);
self::assertSame(Xls::XLS_BIFF8, $reader->getVersion());
self::assertSame('UTF-16LE', $reader->getCodepage());
}
/**
* Test load Xls file with MACCENTRALEUROPE encoding, which is implemented
* as MAC-CENTRALEUROPE on some systems. Issue #549.
*/
private const MAC_CE = ['MACCENTRALEUROPE', 'MAC-CENTRALEUROPE'];
private const MAC_FILE5 = 'tests/data/Reader/XLS/maccentraleurope.biff5.xls';
private const MAC_FILE8 = 'tests/data/Reader/XLS/maccentraleurope.xls';
public function testWorksheetNamesBiff5Mac(): void
{
$codePages = CodePage::getEncodings();
self::assertSame(self::MAC_CE, $codePages[10029]);
$reader = new Xls();
$names = $reader->listWorksheetNames(self::MAC_FILE5);
$expected = ['Ärkusz1'];
self::assertSame($expected, $names);
}
public function testWorksheetInfoBiff5Mac(): void
{
$codePages = CodePage::getEncodings();
// prior test has replaced array with single string
self::assertContains($codePages[10029], self::MAC_CE);
$reader = new Xls();
$info = $reader->listWorksheetInfo(self::MAC_FILE5);
$expected = [
[
'worksheetName' => 'Ärkusz1',
'lastColumnLetter' => 'P',
'lastColumnIndex' => 15,
'totalRows' => 3,
'totalColumns' => 16,
'sheetState' => 'visible',
],
];
self::assertSame($expected, $info);
self::assertSame(Xls::XLS_BIFF7, $reader->getVersion());
self::assertContains($reader->getCodepage(), self::MAC_CE);
}
public function testWorksheetNamesBiff5Special(): void
{
// Sadly, no unit test was added for PR #1484,
// so we have to invent a fake one now.
$reader = new XlsSpecialCodePage();
$reader->setCodePage('CP855'); // use Cyrillic rather than MACCENTRAL
$names = $reader->listWorksheetNames(self::MAC_FILE5);
$expected = ['ђrkusz1']; // first character interpreted as Cyrillic
self::assertSame($expected, $names);
}
public function testBadCodePage(): void
{
$this->expectException(PhpSpreadsheetException::class);
$this->expectExceptionMessage('Unknown codepage');
$reader = new Xls();
$reader->setCodePage('XXXCP855');
}
public function testLoadMacCentralEuropeBiff5(): void
{
$reader = new Xls();
$spreadsheet = $reader->load(self::MAC_FILE5);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('Ärkusz1', $sheet->getTitle());
self::assertSame('Ładowność', $sheet->getCell('I1')->getValue());
self::assertSame(Xls::XLS_BIFF7, $reader->getVersion());
self::assertContains($reader->getCodepage(), self::MAC_CE);
$spreadsheet->disconnectWorksheets();
}
public function testLoadMacCentralEuropeBiff8(): void
{
// Document is UTF-16LE as a whole,
// but some strings are stored as MACCENTRALEUROPE
$reader = new Xls();
$spreadsheet = $reader->load(self::MAC_FILE8);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('Arkusz1', $sheet->getTitle());
self::assertSame('Ładowność', $sheet->getCell('I1')->getValue());
self::assertSame(Xls::XLS_BIFF8, $reader->getVersion());
self::assertSame('UTF-16LE', $reader->getCodepage());
$properties = $spreadsheet->getProperties();
// the following is stored as MACCENTRALEUROPE, not UTF-16LE
self::assertSame('Użytkownik Microsoft Office', $properties->getLastModifiedBy());
$spreadsheet->disconnectWorksheets();
}
public function testDimensions(): void
{
$filename = 'tests/data/Reader/XLS/pr.4687.excel.xls';
$reader = new Xls();
$info = $reader->listWorksheetInfo($filename);
$expected = [
[
'worksheetName' => 'Sheet1',
'lastColumnLetter' => 'D',
'lastColumnIndex' => 3,
'totalRows' => 2,
'totalColumns' => 4,
'sheetState' => 'visible',
],
[
'worksheetName' => 'Sheet2',
'lastColumnLetter' => 'B',
'lastColumnIndex' => 1,
'totalRows' => 4,
'totalColumns' => 2,
'sheetState' => 'visible',
],
];
self::assertSame($expected, $info);
$info = $reader->listWorksheetDimensions($filename);
$expected = [
[
'worksheetName' => 'Sheet1',
'dimensionsMinR' => 0,
'dimensionsMaxR' => 2,
'dimensionsMinC' => 0,
'dimensionsMaxC' => 4,
'lastColumnLetter' => 'D',
],
[
'worksheetName' => 'Sheet2',
'dimensionsMinR' => 0,
'dimensionsMaxR' => 4,
'dimensionsMinC' => 0,
'dimensionsMaxC' => 2,
'lastColumnLetter' => 'B',
],
];
self::assertSame($expected, $info);
}
public function testChartSheetIgnored(): void
{
$filename = 'tests/data/Reader/XLS/chartsheet.xls';
$reader = new Xls();
$info = $reader->listWorksheetInfo($filename);
$expected = [
[
'worksheetName' => 'Data',
'lastColumnLetter' => 'M',
'lastColumnIndex' => 12,
'totalRows' => 7,
'totalColumns' => 13,
'sheetState' => 'visible',
],
];
self::assertSame($expected, $info);
$info = $reader->listWorksheetDimensions($filename);
$expected = [
[
'worksheetName' => 'Data',
'dimensionsMinR' => 0,
'dimensionsMaxR' => 7,
'dimensionsMinC' => 0,
'dimensionsMaxC' => 13,
'lastColumnLetter' => 'M',
],
];
self::assertSame($expected, $info);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/ErrorCodeMapTest.php | tests/PhpSpreadsheetTests/Reader/Xls/ErrorCodeMapTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls\ErrorCode;
use PHPUnit\Framework\TestCase;
class ErrorCodeMapTest extends TestCase
{
#[\PHPUnit\Framework\Attributes\DataProvider('errorCodeMapProvider')]
public function testErrorCode(bool|string $expected, int $index): void
{
self::assertSame($expected, ErrorCode::lookup($index));
}
public static function errorCodeMapProvider(): array
{
return [
[false, 0x01],
['#NULL!', 0x00],
['#DIV/0!', 0x07],
['#VALUE!', 0x0F],
['#REF!', 0x17],
['#NAME?', 0x1D],
['#NUM!', 0x24],
['#N/A', 0x2A],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/ConditionalFormattingExpressionTest.php | tests/PhpSpreadsheetTests/Reader/Xls/ConditionalFormattingExpressionTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class ConditionalFormattingExpressionTest extends TestCase
{
/** @param mixed[][] $expectedRule */
#[DataProvider('conditionalFormattingProvider')]
public function testReadConditionalFormatting(string $expectedRange, array $expectedRule): void
{
$filename = 'tests/data/Reader/XLS/CF_Expression_Comparisons.xls';
$reader = new Xls();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
$hasConditionalStyles = $sheet->conditionalStylesExists($expectedRange);
self::assertTrue($hasConditionalStyles);
$conditionalStyles = $sheet->getConditionalStyles($expectedRange);
foreach ($conditionalStyles as $index => $conditionalStyle) {
self::assertSame($expectedRule[$index]['type'], $conditionalStyle->getConditionType());
self::assertSame($expectedRule[$index]['operator'], $conditionalStyle->getOperatorType());
self::assertSame($expectedRule[$index]['conditions'], $conditionalStyle->getConditions());
}
$spreadsheet->disconnectWorksheets();
}
public static function conditionalFormattingProvider(): array
{
return [
[
'A3:D8',
[
[
'type' => Conditional::CONDITION_EXPRESSION,
'operator' => Conditional::OPERATOR_NONE,
'conditions' => [
'$C1="USA"',
],
],
],
],
[
'A13:D18',
[
[
'type' => Conditional::CONDITION_EXPRESSION,
'operator' => Conditional::OPERATOR_NONE,
'conditions' => [
'AND($C1="USA",$D1="Q4")',
],
],
],
],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/PasswordTest.php | tests/PhpSpreadsheetTests/Reader/Xls/PasswordTest.php | <?php
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
use PhpOffice\PhpSpreadsheet\Reader\Xls as XlsReader;
use PHPUnit\Framework\TestCase;
class PasswordTest extends TestCase
{
public function testDefaultPassword(): void
{
$filename = 'tests/data/Reader/XLS/pwtest.xls';
$reader = new XlsReader();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('x', $sheet->getCell('A1')->getValue());
$spreadsheet->disconnectWorksheets();
}
public function testWrongPassword(): void
{
$this->expectException(ReaderException::class);
$this->expectExceptionMessage('Decryption password incorrect');
$filename = 'tests/data/Reader/XLS/pwtest2.xls';
$reader = new XlsReader();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('test2', $sheet->getCell('A1')->getValue());
$spreadsheet->disconnectWorksheets();
}
public function testCorrectPassword(): void
{
$filename = 'tests/data/Reader/XLS/pwtest2.xls';
$reader = new XlsReader();
$reader->setEncryptionPassword('pwtest2');
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('test2', $sheet->getCell('A1')->getValue());
$spreadsheet->disconnectWorksheets();
}
public function testUnsupportedEncryption(): void
{
$this->expectException(ReaderException::class);
$this->expectExceptionMessage('Unsupported encryption algorithm');
$filename = 'tests/data/Reader/XLS/pwtest3.xls';
$reader = new XlsReader();
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('test2', $sheet->getCell('A1')->getValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xls/ConditionalBorderTest.php | tests/PhpSpreadsheetTests/Reader/Xls/ConditionalBorderTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class ConditionalBorderTest extends AbstractFunctional
{
public function testFormulas(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('A1')->setValue(1);
$sheet->getCell('A2')->setValue(9);
$sheet->getCell('A3')->setValue(5);
$sheet->getCell('A4')->setValue(2);
$sheet->getCell('A5')->setValue(8);
$condition1 = new Conditional();
$condition1->setConditionType(Conditional::CONDITION_CELLIS);
$condition1->setOperatorType(Conditional::OPERATOR_LESSTHAN);
$condition1->addCondition(5);
$condition1->getStyle()->getBorders()->getRight()
->setBorderStyle(Border::BORDER_THICK)
->getColor()
->setArgb('FFFF0000');
$condition1->getStyle()->getBorders()->getBottom()
->setBorderStyle(Border::BORDER_DASHED)
->getColor()
->setArgb('FFF08000');
$condition2 = new Conditional();
$condition2->setConditionType(Conditional::CONDITION_CELLIS);
$condition2->setOperatorType(Conditional::OPERATOR_GREATERTHAN);
$condition2->addCondition(5);
$condition2->getStyle()->getBorders()->getRight()
->setBorderStyle(Border::BORDER_THICK)
->getColor()
->setArgb('FF0000FF');
$condition2->getStyle()->getBorders()->getBottom()
->setBorderStyle(Border::BORDER_DASHED)
->getColor()
->setArgb('FF0080FF');
$conditionalStyles = [$condition1, $condition2];
$sheet->getStyle('A1:A5')->setConditionalStyles($conditionalStyles);
$sheet->getCell('C6')->setValue(1);
$sheet->getCell('C7')->setValue(9);
$sheet->getCell('C8')->setValue(5);
$sheet->getCell('C9')->setValue(2);
$sheet->getCell('C10')->setValue(8);
$condition1 = new Conditional();
$condition1->setConditionType(Conditional::CONDITION_CELLIS);
$condition1->setOperatorType(Conditional::OPERATOR_LESSTHAN);
$condition1->addCondition(5);
$condition1->getStyle()->getBorders()->getLeft()
->setBorderStyle(Border::BORDER_THICK)
->getColor()
->setArgb('FFFF0000');
$condition1->getStyle()->getBorders()->getTop()
->setBorderStyle(Border::BORDER_DASHED)
->getColor()
->setArgb('FFF08000');
$condition2 = new Conditional();
$condition2->setConditionType(Conditional::CONDITION_CELLIS);
$condition2->setOperatorType(Conditional::OPERATOR_GREATERTHAN);
$condition2->addCondition(5);
$condition2->getStyle()->getBorders()->getLeft()
->setBorderStyle(Border::BORDER_THICK)
->getColor()
->setArgb('FF0000FF');
$condition2->getStyle()->getBorders()->getTop()
->setBorderStyle(Border::BORDER_DASHED)
->getColor()
->setArgb('FF0080FF');
$conditionalStyles = [$condition1, $condition2];
$sheet->getStyle('C6:C10')->setConditionalStyles($conditionalStyles);
$newSpreadsheet = $this->writeAndReload($spreadsheet, 'Xls');
$spreadsheet->disconnectWorksheets();
$sheet = $newSpreadsheet->getActiveSheet();
$conditionals = $sheet->getConditionalStylesCollection();
self::assertCount(2, $conditionals);
$cond1 = $conditionals['A1:A5'];
self::assertCount(2, $cond1);
$borders = $cond1[0]->getStyle()->getBorders();
self::assertSame(Border::BORDER_OMIT, $borders->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_THICK, $borders->getRight()->getBorderStyle());
self::assertSame('FFFF0000', $borders->getRight()->getColor()->getARGB());
self::assertSame(Border::BORDER_OMIT, $borders->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_DASHED, $borders->getBottom()->getBorderStyle());
self::assertSame('FFF08000', $borders->getBottom()->getColor()->getARGB());
$borders = $cond1[1]->getStyle()->getBorders();
self::assertSame(Border::BORDER_OMIT, $borders->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_THICK, $borders->getRight()->getBorderStyle());
self::assertSame('FF0000FF', $borders->getRight()->getColor()->getARGB());
self::assertSame(Border::BORDER_OMIT, $borders->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_DASHED, $borders->getBottom()->getBorderStyle());
self::assertSame('FF0080FF', $borders->getBottom()->getColor()->getARGB());
$cond1 = $conditionals['C6:C10'];
self::assertCount(2, $cond1);
$borders = $cond1[0]->getStyle()->getBorders();
self::assertSame(Border::BORDER_THICK, $borders->getLeft()->getBorderStyle());
self::assertSame('FFFF0000', $borders->getLeft()->getColor()->getARGB());
self::assertSame(Border::BORDER_OMIT, $borders->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_DASHED, $borders->getTop()->getBorderStyle());
self::assertSame('FFF08000', $borders->getTop()->getColor()->getARGB());
self::assertSame(Border::BORDER_OMIT, $borders->getBottom()->getBorderStyle());
$borders = $cond1[1]->getStyle()->getBorders();
self::assertSame(Border::BORDER_THICK, $borders->getLeft()->getBorderStyle());
self::assertSame('FF0000FF', $borders->getLeft()->getColor()->getARGB());
self::assertSame(Border::BORDER_OMIT, $borders->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_DASHED, $borders->getTop()->getBorderStyle());
self::assertSame('FF0080FF', $borders->getTop()->getColor()->getARGB());
self::assertSame(Border::BORDER_OMIT, $borders->getBottom()->getBorderStyle());
$newSpreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Reader/Xml/DataValidationsTest.php | tests/PhpSpreadsheetTests/Reader/Xml/DataValidationsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Reader\Xml;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use PhpOffice\PhpSpreadsheet\Reader\Xml;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheetTests\Functional\AbstractFunctional;
class DataValidationsTest extends AbstractFunctional
{
private string $filename = 'tests/data/Reader/Xml/datavalidations.xml';
private string $filename2 = 'tests/data/Reader/Xml/datavalidations.wholerow.xml';
public function testValidation(): void
{
$reader = new Xml();
$spreadsheet = $reader->load($this->filename);
$sheet = $spreadsheet->getActiveSheet();
$assertions = $this->validationAssertions();
$validation = $sheet->getCell('A1')->getDataValidation();
self::assertSame('A:A', $validation->getSqref());
$validation = $sheet->getCell('B3')->getDataValidation();
self::assertSame('B2:B1048576', $validation->getSqref());
foreach ($assertions as $title => $assertion) {
$sheet->getCell($assertion[1])->setValue($assertion[2]);
self::assertSame($assertion[0], $sheet->getCell($assertion[1])->hasValidValue(), $title);
}
$sheet->getCell('F1')->getDataValidation()->setType(DataValidation::TYPE_NONE);
$sheet->getCell('F1')->setValue(1);
self::assertTrue($sheet->getCell('F1')->hasValidValue(), 'validation type is NONE');
$spreadsheet->disconnectWorksheets();
}
public function testValidationWholeRow(): void
{
$reader = new Xml();
$spreadsheet = $reader->load($this->filename2);
$sheet = $spreadsheet->getActiveSheet();
$collection = $sheet->getDataValidationCollection();
self::assertSame(['A1', '1:1'], array_keys($collection));
$dv = $collection['A1'];
self::assertSame('"Item A,Item B,Item D"', $dv->getFormula1());
self::assertSame('warn', $dv->getErrorStyle());
self::assertFalse($dv->getShowDropDown());
self::assertFalse($dv->getShowErrorMessage());
$dv = $collection['1:1'];
self::assertSame('"Item A,Item B,Item C"', $dv->getFormula1());
self::assertSame('stop', $dv->getErrorStyle());
self::assertTrue($dv->getShowDropDown());
self::assertTrue($dv->getShowErrorMessage());
$spreadsheet->disconnectWorksheets();
}
public function testValidationXlsx(): void
{
$reader = new Xml();
$oldspreadsheet = $reader->load($this->filename);
$spreadsheet = $this->writeAndReload($oldspreadsheet, 'Xlsx');
$oldspreadsheet->disconnectWorksheets();
$sheet = $spreadsheet->getActiveSheet();
$assertions = $this->validationAssertions();
$validation = $sheet->getCell('A1')->getDataValidation();
self::assertSame('A:A', $validation->getSqref());
$validation = $sheet->getCell('B3')->getDataValidation();
self::assertSame('B2:B1048576', $validation->getSqref());
foreach ($assertions as $title => $assertion) {
$sheet->getCell($assertion[1])->setValue($assertion[2]);
self::assertSame($assertion[0], $sheet->getCell($assertion[1])->hasValidValue(), $title);
}
$spreadsheet->disconnectWorksheets();
}
public function testValidationXls(): void
{
$reader = new Xml();
$oldspreadsheet = $reader->load($this->filename);
$spreadsheet = $this->writeAndReload($oldspreadsheet, 'Xls');
$oldspreadsheet->disconnectWorksheets();
$sheet = $spreadsheet->getActiveSheet();
$assertions = $this->validationAssertions();
$validation = $sheet->getCell('A1')->getDataValidation();
self::assertSame('A:A', $validation->getSqref(), 'limited number of rows in Xls');
$validation = $sheet->getCell('B3')->getDataValidation();
self::assertSame('B2:B1048576', $validation->getSqref());
foreach ($assertions as $title => $assertion) {
$sheet->getCell($assertion[1])->setValue($assertion[2]);
self::assertSame($assertion[0], $sheet->getCell($assertion[1])->hasValidValue(), $title);
}
$spreadsheet->disconnectWorksheets();
}
/** @return array<string, array{bool, string, mixed}> */
private function validationAssertions(): array
{
return [
// Numeric tests
'Integer between 2 and 5: x' => [false, 'F1', 'x'],
'Integer between 2 and 5: 3.1' => [false, 'F1', 3.1],
'Integer between 2 and 5: 3' => [true, 'F1', 3],
'Integer between 2 and 5: 1' => [false, 'F1', 1],
'Integer between 2 and 5: 7' => [false, 'F1', 7],
'Float between 2 and 5: x' => [false, 'G1', 'x'],
'Float between 2 and 5: 3.1' => [true, 'G1', 3.1],
'Float between 2 and 5: 3' => [true, 'G1', 3],
'Float between 2 and 5: 1' => [false, 'G1', 1],
'Float between 2 and 5: 7' => [false, 'G1', 7],
'Integer not between -5 and 5: 3' => [false, 'F2', 3],
'Integer not between -5 and 5: -1' => [false, 'F2', -1],
'Integer not between -5 and 5: 7' => [true, 'F2', 7],
'Any integer except 7: -1' => [true, 'F3', -1],
'Any integer except 7: 7' => [false, 'F3', 7],
'Only -3: -1' => [false, 'F4', -1],
'Only -3: -3' => [true, 'F4', -3],
'Integer less than 8: 8' => [false, 'F5', 8],
'Integer less than 8: 7' => [true, 'F5', 7],
'Integer less than 8: 9' => [false, 'F5', 9],
'Integer less than or equal 12: 12' => [true, 'F6', 12],
'Integer less than or equal 12: 7' => [true, 'F6', 7],
'Integer less than or equal 12: 13' => [false, 'F6', 13],
'Integer greater than or equal -6: -6' => [true, 'F7', -6],
'Integer greater than or equal -6: -7' => [false, 'F7', -7],
'Integer greater than or equal -6: -5' => [true, 'F7', -5],
'Integer greater than 5: 5' => [false, 'F8', 5],
'Integer greater than 5: 6' => [true, 'F8', 6],
'Integer greater than 5: 3' => [false, 'F8', 3],
// Text tests
'a,b,c,d,e: a' => [true, 'C4', 'a'],
'a,b,c,d,e: c' => [true, 'C4', 'c'],
'a,b,c,d,e: e' => [true, 'C4', 'e'],
'a,b,c,d,e: x' => [false, 'C4', 'x'],
'a,b,c,d,e: aa' => [false, 'C4', 'aa'],
'less than 8 characters: abcdefg' => [true, 'C3', 'abcdefg'],
'less than 8 characters: abcdefgh' => [false, 'C3', 'abcdefgh'],
'texts in e1 to e5: ccc' => [true, 'D2', 'ccc'],
'texts in e1 to e5: ffffff' => [false, 'D2', 'ffffff'],
'date from 20230101: 20221231' => [false, 'C1', Date::convertIsoDate('20221231')],
'date from 20230101: 20230101' => [true, 'C1', Date::convertIsoDate('20230101')],
'date from 20230101: 20240507' => [true, 'C1', Date::convertIsoDate('20240507')],
'date from 20230101: 20240507 10:00:00' => [true, 'C1', Date::convertIsoDate('20240507 10:00:00')],
'time from 12:00-14:00: 2023-01-01 13:00:00' => [false, 'C2', Date::convertIsoDate('2023-01-01 13:00:00')],
'time from 8:00-14:00: 13:00' => [true, 'C2', Date::convertIsoDate('13:00')],
'time from 8:00-14:00: 07:00:00' => [false, 'C2', Date::convertIsoDate('07:00:00')],
'time from 8:00-14:00: 15:00:00' => [false, 'C2', Date::convertIsoDate('15:00:00')],
'time from 8:00-14:00: 1:13 am' => [false, 'C2', Date::convertIsoDate('1:13 am')],
'time from 8:00-14:00: 1:13 pm' => [true, 'C2', Date::convertIsoDate('1:13 pm')],
'time from 8:00-14:00: 9:13' => [true, 'C2', Date::convertIsoDate('9:13')],
'time from 8:00-14:00: 9:13 am' => [true, 'C2', Date::convertIsoDate('9:13 am')],
'time from 8:00-14:00: 9:13 pm' => [false, 'C2', Date::convertIsoDate('9:13 pm')],
];
}
}
| 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.