Skip to content

Commit 9552172

Browse files
oleibmanPowerKiKi
authored andcommitted
Do not confuse defined names and cell refs
CALCULATION_REGEXP_CELLREF is not sufficiently robust. It treats some perfectly legal defined names, e.g. A1A, as cell refs. When the Xlsx Writer tries to save a worksheet which uses such a name in a formula in a cell, it throws an exception. The new DefinedNameConfusedForCellTest is a simple demonstration. The Regexp has been changed to ensure the name starts on a Word boundary, and to make sure it is not followed by a word character or period. This fixes the problem, and does not appear to cause any regression problems in the test suite. Closes #1263
1 parent 86fa542 commit 9552172

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/PhpSpreadsheet/Calculation/Calculation.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class Calculation
2525
// Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it)
2626
const CALCULATION_REGEXP_FUNCTION = '@?(?:_xlfn\.)?([A-Z][A-Z0-9\.]*)[\s]*\(';
2727
// Cell reference (cell or range of cells, with or without a sheet reference)
28-
const CALCULATION_REGEXP_CELLREF = '((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d{1,7})';
28+
const CALCULATION_REGEXP_CELLREF = '((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?\b([a-z]{1,3})\$?(\d{1,7})(?![\w.])';
2929
// Named Range of cells
3030
const CALCULATION_REGEXP_NAMEDRANGE = '((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?([_A-Z][_A-Z0-9\.]*)';
3131
// Error
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
3+
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
4+
5+
use PhpOffice\PhpSpreadsheet\Shared\File;
6+
use PHPUnit\Framework\TestCase;
7+
8+
class DefinedNameConfusedForCellTest extends TestCase
9+
{
10+
public function testDefinedName()
11+
{
12+
$obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
13+
$sheet0 = $obj->setActiveSheetIndex(0);
14+
$sheet0->setCellValue('A1', 2);
15+
$obj->addNamedRange(new \PhpOffice\PhpSpreadsheet\NamedRange('A1A', $sheet0, 'A1'));
16+
$sheet0->setCellValue('B1', '=2*A1A');
17+
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($obj, 'Xlsx');
18+
$filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test');
19+
$writer->save($filename);
20+
self::assertTrue(true);
21+
}
22+
}

0 commit comments

Comments
 (0)