Skip to content

Commit 1e6668f

Browse files
committed
Copy Cell Adjusting Formula
Fix #1203. The issue actually complains about the documentation, but I think it wants documented functionality that doesn't yet exist. This PR adds a method for copying a formula from one cell to another, adjusting cell references in the formula as Excel would. For a non-formula, it copies the value without making any adjustments.
1 parent d88efca commit 1e6668f

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/PhpSpreadsheet/Worksheet/Worksheet.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3984,4 +3984,22 @@ public function applyStylesFromArray(string $coordinate, array $styleArray): boo
39843984

39853985
return true;
39863986
}
3987+
3988+
public function copyFormula(string $fromCell, string $toCell): void
3989+
{
3990+
$formula = $this->getCell($fromCell)->getValue();
3991+
$newFormula = $formula;
3992+
if (is_string($formula) && $this->getCell($fromCell)->getDataType() === DataType::TYPE_FORMULA) {
3993+
[$fromColInt, $fromRow] = Coordinate::indexesFromString($fromCell);
3994+
[$toColInt, $toRow] = Coordinate::indexesFromString($toCell);
3995+
$helper = ReferenceHelper::getInstance();
3996+
$newFormula = $helper->updateFormulaReferences(
3997+
$formula,
3998+
'A1',
3999+
$toColInt - $fromColInt,
4000+
$toRow - $fromRow
4001+
);
4002+
}
4003+
$this->setCellValue($toCell, $newFormula);
4004+
}
39874005
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace PhpOffice\PhpSpreadsheetTests\Worksheet;
6+
7+
use PhpOffice\PhpSpreadsheet\Spreadsheet;
8+
use PHPUnit\Framework\TestCase;
9+
10+
class Issue1203Test extends TestCase
11+
{
12+
public static function testCopyFormula(): void
13+
{
14+
$spreadsheet = new Spreadsheet();
15+
$sheet = $spreadsheet->getActiveSheet();
16+
$sheet->setCellValue('A1', 1);
17+
$sheet->setCellValue('A5', 5);
18+
$sheet->setCellValue('E5', '=A5+$A$1');
19+
$sheet->insertNewRowBefore(5, 1);
20+
$e5 = $sheet->getCell('E5')->getValue();
21+
self::assertNull($e5);
22+
self::assertSame('=A6+$A$1', $sheet->getCell('E6')->getValue());
23+
$sheet->copyFormula('E6', 'E5');
24+
self::assertSame('=A5+$A$1', $sheet->getCell('E5')->getValue());
25+
$sheet->copyFormula('E6', 'H9');
26+
self::assertSame('=D9+$A$1', $sheet->getCell('H9')->getValue());
27+
$sheet->copyFormula('A6', 'Z9');
28+
self::assertSame(5, $sheet->getCell('Z9')->getValue());
29+
$spreadsheet->disconnectWorksheets();
30+
}
31+
}

0 commit comments

Comments
 (0)