mirror of
https://github.com/PHPOffice/PhpSpreadsheet.git
synced 2026-09-14 03:56:40 +00:00
7c1a65e17c
Cloning a worksheet attached to a spreadsheet creates a clone which is detached from the spreadsheet. This can have its uses, but I think it would also be useful to have the ability to duplicate the worksheet and keep the duplicate attached to the spreadsheet. You can do that in Excel and LibreOffice, and you can now do it in PhpSpreadsheet as well. The duplicated worksheet will come immediately after its source. The worksheet being duplicated could be identified in a number of ways - by passing the worksheet itself to the new method, by passing the worksheet title, or by passing the index of the worksheet within the spreadsheet. For now, I am just implementing the one I think is most useful (title).
60 lines
1.8 KiB
PHP
60 lines
1.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace PhpOffice\PhpSpreadsheetTests;
|
|
|
|
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
class SpreadsheetDuplicateSheetTest extends TestCase
|
|
{
|
|
private ?Spreadsheet $spreadsheet = null;
|
|
|
|
protected function tearDown(): void
|
|
{
|
|
if ($this->spreadsheet !== null) {
|
|
$this->spreadsheet->disconnectWorksheets();
|
|
$this->spreadsheet = null;
|
|
}
|
|
}
|
|
|
|
public function testDuplicate(): void
|
|
{
|
|
$this->spreadsheet = new Spreadsheet();
|
|
$sheet = $this->spreadsheet->getActiveSheet();
|
|
$sheet->setTitle('original');
|
|
$sheet->getCell('A1')->setValue('text1');
|
|
$sheet->getCell('A2')->setValue('text2');
|
|
$sheet->getStyle('A1')
|
|
->getFont()
|
|
->setBold(true);
|
|
$sheet3 = $this->spreadsheet->createSheet();
|
|
$sheet3->setTitle('added');
|
|
$newSheet = $this->spreadsheet
|
|
->duplicateWorksheetByTitle('original');
|
|
$this->spreadsheet->duplicateWorksheetByTitle('added');
|
|
self::assertSame('original 1', $newSheet->getTitle());
|
|
self::assertSame(
|
|
'text1',
|
|
$newSheet->getCell('A1')->getValue()
|
|
);
|
|
self::assertSame(
|
|
'text2',
|
|
$newSheet->getCell('A2')->getValue()
|
|
);
|
|
self::assertTrue(
|
|
$newSheet->getStyle('A1')->getFont()->getBold()
|
|
);
|
|
self::assertFalse(
|
|
$newSheet->getStyle('A2')->getFont()->getBold()
|
|
);
|
|
$sheetNames = [];
|
|
foreach ($this->spreadsheet->getWorksheetIterator() as $worksheet) {
|
|
$sheetNames[] = $worksheet->getTitle();
|
|
}
|
|
$expected = ['original', 'original 1', 'added', 'added 1'];
|
|
self::assertSame($expected, $sheetNames);
|
|
}
|
|
}
|