Skip to content

Commit 3844186

Browse files
authored
Fix for Issue 1495 (#1500)
#1495 reports that ActiveSheet can change when calculation involves jumping around between sheets. Save index before calculation, restore after, add test.
1 parent 1a44ef9 commit 3844186

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/PhpSpreadsheet/Cell/Cell.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,9 +251,11 @@ public function getCalculatedValue($resetLog = true)
251251
{
252252
if ($this->dataType == DataType::TYPE_FORMULA) {
253253
try {
254+
$index = $this->getWorksheet()->getParent()->getActiveSheetIndex();
254255
$result = Calculation::getInstance(
255256
$this->getWorksheet()->getParent()
256257
)->calculateCellValue($this, $resetLog);
258+
$this->getWorksheet()->getParent()->setActiveSheetIndex($index);
257259
// We don't yet handle array returns
258260
if (is_array($result)) {
259261
while (is_array($result)) {

tests/PhpSpreadsheetTests/Cell/CellTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,23 @@ public function providerSetValueExplicitException()
4646
{
4747
return require 'tests/data/Cell/SetValueExplicitException.php';
4848
}
49+
50+
public function testNoChangeToActiveSheet(): void
51+
{
52+
$spreadsheet = new Spreadsheet();
53+
$sheet1 = $spreadsheet->getActiveSheet();
54+
$sheet1->setTitle('Sheet 1');
55+
$sheet3 = $spreadsheet->createSheet();
56+
$sheet3->setTitle('Sheet 3');
57+
$sheet1->setCellValue('C1', 123);
58+
$sheet1->setCellValue('D1', 124);
59+
$sheet3->setCellValue('A1', "='Sheet 1'!C1+'Sheet 1'!D1");
60+
$sheet1->setCellValue('A1', "='Sheet 3'!A1");
61+
$cell = 'A1';
62+
$spreadsheet->setActiveSheetIndex(0);
63+
self::assertEquals(0, $spreadsheet->getActiveSheetIndex());
64+
$value = $spreadsheet->getActiveSheet()->getCell($cell)->getCalculatedValue();
65+
self::assertEquals(0, $spreadsheet->getActiveSheetIndex());
66+
self::assertEquals(247, $value);
67+
}
4968
}

0 commit comments

Comments
 (0)