Skip to content

Commit 50b91e8

Browse files
committed
Remove table By name
Option to remove the table from table collection of worksheet
1 parent 3c3d949 commit 50b91e8

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/PhpSpreadsheet/Worksheet/Worksheet.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2057,6 +2057,24 @@ public function addTableByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row
20572057
return $this->addTable(new Table($cellRange, $this));
20582058
}
20592059

2060+
/**
2061+
* Remove Table by name.
2062+
*
2063+
* @param string $name Table name
2064+
*
2065+
* @return $this
2066+
*/
2067+
public function removeTableByName(string $name): self
2068+
{
2069+
foreach($this->tableCollection as $key => $table) {
2070+
if ($table->getName() === $name) {
2071+
unset($this->tableCollection[$key]);
2072+
}
2073+
}
2074+
2075+
return $this;
2076+
}
2077+
20602078
/**
20612079
* Remove collection of Tables.
20622080
*/
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
namespace PhpOffice\PhpSpreadsheetTests\Worksheet\Table;
4+
5+
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
6+
7+
class RemoveTableTest extends SetupTeardown
8+
{
9+
private const INITIAL_RANGE = 'H2:O256';
10+
11+
public function testRemoveTable(): void
12+
{
13+
$sheet = $this->getSheet();
14+
15+
$table = new Table(self::INITIAL_RANGE, $sheet);
16+
$table->setName('Table1');
17+
$sheet->addTable($table);
18+
19+
self::assertEquals(1, $sheet->getTableCollection()->count());
20+
21+
$sheet->removeTableByName('Table1');
22+
self::assertEquals(0, $sheet->getTableCollection()->count());
23+
}
24+
25+
public function testRemoveCollection(): void
26+
{
27+
$sheet = $this->getSheet();
28+
29+
$table = new Table(self::INITIAL_RANGE, $sheet);
30+
$table->setName('Table1');
31+
$sheet->addTable($table);
32+
33+
self::assertEquals(1, $sheet->getTableCollection()->count());
34+
35+
$sheet->removeTableCollection();
36+
self::assertEquals(0, $sheet->getTableCollection()->count());
37+
}
38+
}

0 commit comments

Comments
 (0)