Skip to content

Commit b774082

Browse files
authored
Merge pull request #158 from pascallieverse/main
Add the option to check if a sheet exists by name
2 parents f6a97de + a61b53f commit b774082

3 files changed

Lines changed: 33 additions & 0 deletions

File tree

README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,13 @@ $rows = SimpleExcelReader::create($pathToXlsx)
133133
->getRows();
134134
```
135135

136+
if you want to check if a sheet exists, you can use the `sheetExists()` method.
137+
138+
```php
139+
$sheetExists = SimpleExcelReader::create($pathToXlsx)
140+
->sheetExists("sheet1");
141+
```
142+
136143
#### Retrieving header row values
137144

138145
If you would like to retrieve the header row as an array, you can use the `getHeaders()` method.

src/SimpleExcelReader.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,20 @@ public function take(int $count): SimpleExcelReader
152152
return $this;
153153
}
154154

155+
public function hasSheet(string $sheetName) : bool
156+
{
157+
$this->setReader();
158+
159+
$this->reader->open($this->path);
160+
161+
foreach ($this->reader->getSheetIterator() as $sheet) {
162+
if ($sheetName != "" && $sheetName === $sheet->getName()) {
163+
return true;
164+
}
165+
}
166+
return false;
167+
}
168+
155169
public function fromSheet(int $sheetNumber): SimpleExcelReader
156170
{
157171
$this->sheetNumber = $sheetNumber;

tests/SimpleExcelReaderTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -590,6 +590,18 @@ function () {
590590
]);
591591
});
592592

593+
it('Can check if a sheet exists by name', function () {
594+
$reader = SimpleExcelReader::create(getStubPath('multiple_sheets.xlsx'));
595+
596+
expect($reader->hasSheet("sheet1"))->toBeTrue();
597+
});
598+
599+
it('Can check if a sheet doesn\'t exists by name', function () {
600+
$reader = SimpleExcelReader::create(getStubPath('multiple_sheets.xlsx'));
601+
602+
expect($reader->hasSheet("sheet0"))->toBeFalse();
603+
});
604+
593605
it('will not open non-existing sheets by name', function () {
594606
SimpleExcelReader::create(getStubPath('multiple_sheets.xlsx'))
595607
->fromSheetName("sheetNotExists")

0 commit comments

Comments
 (0)