Skip to content

Commit

Permalink
Clone Worksheet With Table
Browse files Browse the repository at this point in the history
Fix #3820. When cloning a worksheet, special handling is already included for `cellCollection` and `drawingCollection`. It needs to be added for `tableCollection` as well. In theory, `chartCollection` also needs it. However, there are no clone methods for any of the Chart objects, so that will be a substantially larger effort. There is no need to delay this fix waiting for that.
  • Loading branch information
oleibman committed Dec 11, 2023
1 parent 29c0162 commit 117f89c
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/PhpSpreadsheet/Worksheet/Worksheet.php
Original file line number Diff line number Diff line change
Expand Up @@ -3744,6 +3744,14 @@ public function __clone()
$newDrawing->setWorksheet($this);
}
}
} elseif ($key == 'tableCollection') {
$currentCollection = $this->tableCollection;
$this->tableCollection = new ArrayObject();
foreach ($currentCollection as $item) {
$newTable = clone $item;
$newTable->setName($item->getName() . 'clone');
$this->addTable($newTable);
}
} elseif (($key == 'autoFilter') && ($this->autoFilter instanceof AutoFilter)) {
$newAutoFilter = clone $this->autoFilter;
$this->autoFilter = $newAutoFilter;
Expand Down
41 changes: 41 additions & 0 deletions tests/PhpSpreadsheetTests/Worksheet/Table/Issue3820Test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

namespace PhpOffice\PhpSpreadsheetTests\Worksheet\Table;

use PhpOffice\PhpSpreadsheet\Worksheet\Table;

class Issue3820Test extends SetupTeardown
{
public function testTableOnOtherSheet(): void
{
// Clone worksheet failed when table was on sheet
$spreadsheet = $this->getSpreadsheet();
$sheet = $this->getSheet();
$sheet->setTitle('Original');
$sheet->fromArray(
[
['MyCol', 'Colonne2', 'Colonne3'],
[10, 20],
[2],
[3],
[4],
],
null,
'B1',
true
);
$table = new Table('B1:D5', 'Tableau1');
$sheet->addTable($table);
$clonedSheet = clone $sheet;
$clonedSheet->setTitle('Cloned');
$spreadsheet->addsheet($clonedSheet);
$originalTable = $spreadsheet->getTableByName('Tableau1');
$newTable = $spreadsheet->getTableByName('Tableau1clone');
self::assertNotNull($newTable);
self::assertSame($table, $originalTable);
self::assertSame('Cloned', $newTable->getWorksheet()?->getTitle());
self::assertSame('B1:D5', $newTable->getRange());
}
}

0 comments on commit 117f89c

Please sign in to comment.