diff --git a/src/PhpSpreadsheet/Worksheet/Worksheet.php b/src/PhpSpreadsheet/Worksheet/Worksheet.php index 6aa3f5d073..02305b7a7f 100644 --- a/src/PhpSpreadsheet/Worksheet/Worksheet.php +++ b/src/PhpSpreadsheet/Worksheet/Worksheet.php @@ -1197,7 +1197,8 @@ public function getCell($pCoordinate, $createIfNotExists = true) ) { $namedRange = $this->validateNamedRange($pCoordinate, true); if ($namedRange !== null) { - $cellCoordinate = str_replace('$', '', $namedRange->getValue()); + $cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!'); + $cellCoordinate = str_replace('$', '', $cellCoordinate); return $namedRange->getWorksheet()->getCell($cellCoordinate, $createIfNotExists); } @@ -1296,8 +1297,12 @@ public function cellExists($pCoordinate) (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/i', $pCoordinate, $matches)) ) { $namedRange = $this->validateNamedRange($pCoordinate, true); + if ($namedRange !== null) { + $cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!'); + $cellCoordinate = str_replace('$', '', $cellCoordinate); - return ($namedRange !== null) ? $namedRange->getWorksheet()->cellExists($pCoordinate) : false; + return $namedRange->getWorksheet()->cellExists($cellCoordinate); + } } // Uppercase coordinate @@ -2589,7 +2594,8 @@ public function namedRangeToArray(string $definedName, $nullValue = null, $calcu { $namedRange = $this->validateNamedRange($definedName); $workSheet = $namedRange->getWorksheet(); - $cellRange = str_replace('$', '', $namedRange->getValue()); + $cellRange = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!'); + $cellRange = str_replace('$', '', $cellRange); return $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef); } diff --git a/tests/PhpSpreadsheetTests/Worksheet/WorksheetNamedRangesTest.php b/tests/PhpSpreadsheetTests/Worksheet/WorksheetNamedRangesTest.php new file mode 100644 index 0000000000..c9beceea54 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/WorksheetNamedRangesTest.php @@ -0,0 +1,38 @@ +spreadsheet = $reader->load('tests/data/Worksheet/namedRangeTest.xlsx'); + } + + public function testCellExists() + { + $worksheet = $this->spreadsheet->getActiveSheet(); + $cellExists = $worksheet->cellExists('GREETING'); + self::assertTrue($cellExists); + } + + public function testGetCell() + { + $worksheet = $this->spreadsheet->getActiveSheet(); + $cell = $worksheet->getCell('GREETING'); + self::assertSame('Hello', $cell->getValue()); + } + + public function testNamedRangeToArray() + { + $worksheet = $this->spreadsheet->getActiveSheet(); + $rangeData = $worksheet->namedRangeToArray('Range1'); + self::assertSame([[1, 2, 3]], $rangeData); + } +}