From 38441863971872e5d291d80223697c28bd5a95eb Mon Sep 17 00:00:00 2001 From: oleibman Date: Fri, 19 Jun 2020 11:57:20 -0700 Subject: [PATCH] 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. --- src/PhpSpreadsheet/Cell/Cell.php | 2 ++ tests/PhpSpreadsheetTests/Cell/CellTest.php | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/PhpSpreadsheet/Cell/Cell.php b/src/PhpSpreadsheet/Cell/Cell.php index 0bca2fc0..74ed9268 100644 --- a/src/PhpSpreadsheet/Cell/Cell.php +++ b/src/PhpSpreadsheet/Cell/Cell.php @@ -251,9 +251,11 @@ class Cell { if ($this->dataType == DataType::TYPE_FORMULA) { try { + $index = $this->getWorksheet()->getParent()->getActiveSheetIndex(); $result = Calculation::getInstance( $this->getWorksheet()->getParent() )->calculateCellValue($this, $resetLog); + $this->getWorksheet()->getParent()->setActiveSheetIndex($index); // We don't yet handle array returns if (is_array($result)) { while (is_array($result)) { diff --git a/tests/PhpSpreadsheetTests/Cell/CellTest.php b/tests/PhpSpreadsheetTests/Cell/CellTest.php index 8c95e864..0d9ce337 100644 --- a/tests/PhpSpreadsheetTests/Cell/CellTest.php +++ b/tests/PhpSpreadsheetTests/Cell/CellTest.php @@ -46,4 +46,23 @@ class CellTest extends TestCase { return require 'tests/data/Cell/SetValueExplicitException.php'; } + + public function testNoChangeToActiveSheet(): void + { + $spreadsheet = new Spreadsheet(); + $sheet1 = $spreadsheet->getActiveSheet(); + $sheet1->setTitle('Sheet 1'); + $sheet3 = $spreadsheet->createSheet(); + $sheet3->setTitle('Sheet 3'); + $sheet1->setCellValue('C1', 123); + $sheet1->setCellValue('D1', 124); + $sheet3->setCellValue('A1', "='Sheet 1'!C1+'Sheet 1'!D1"); + $sheet1->setCellValue('A1', "='Sheet 3'!A1"); + $cell = 'A1'; + $spreadsheet->setActiveSheetIndex(0); + self::assertEquals(0, $spreadsheet->getActiveSheetIndex()); + $value = $spreadsheet->getActiveSheet()->getCell($cell)->getCalculatedValue(); + self::assertEquals(0, $spreadsheet->getActiveSheetIndex()); + self::assertEquals(247, $value); + } }