diff --git a/src/PhpSpreadsheet/Worksheet/Worksheet.php b/src/PhpSpreadsheet/Worksheet/Worksheet.php index 525513b250..137d2b4b6c 100644 --- a/src/PhpSpreadsheet/Worksheet/Worksheet.php +++ b/src/PhpSpreadsheet/Worksheet/Worksheet.php @@ -3984,4 +3984,22 @@ public function applyStylesFromArray(string $coordinate, array $styleArray): boo return true; } + + public function copyFormula(string $fromCell, string $toCell): void + { + $formula = $this->getCell($fromCell)->getValue(); + $newFormula = $formula; + if (is_string($formula) && $this->getCell($fromCell)->getDataType() === DataType::TYPE_FORMULA) { + [$fromColInt, $fromRow] = Coordinate::indexesFromString($fromCell); + [$toColInt, $toRow] = Coordinate::indexesFromString($toCell); + $helper = ReferenceHelper::getInstance(); + $newFormula = $helper->updateFormulaReferences( + $formula, + 'A1', + $toColInt - $fromColInt, + $toRow - $fromRow + ); + } + $this->setCellValue($toCell, $newFormula); + } } diff --git a/tests/PhpSpreadsheetTests/Worksheet/Issue1203Test.php b/tests/PhpSpreadsheetTests/Worksheet/Issue1203Test.php new file mode 100644 index 0000000000..01ddf44827 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Worksheet/Issue1203Test.php @@ -0,0 +1,31 @@ +getActiveSheet(); + $sheet->setCellValue('A1', 1); + $sheet->setCellValue('A5', 5); + $sheet->setCellValue('E5', '=A5+$A$1'); + $sheet->insertNewRowBefore(5, 1); + $e5 = $sheet->getCell('E5')->getValue(); + self::assertNull($e5); + self::assertSame('=A6+$A$1', $sheet->getCell('E6')->getValue()); + $sheet->copyFormula('E6', 'E5'); + self::assertSame('=A5+$A$1', $sheet->getCell('E5')->getValue()); + $sheet->copyFormula('E6', 'H9'); + self::assertSame('=D9+$A$1', $sheet->getCell('H9')->getValue()); + $sheet->copyFormula('A6', 'Z9'); + self::assertSame(5, $sheet->getCell('Z9')->getValue()); + $spreadsheet->disconnectWorksheets(); + } +}