Exception when remove a sheet with named ranges

Author: cia1Created Nov 30, 2018Updated Jun 10, 2026

This is:

- [x] a bug report
- [ ] a feature request
- [ ] **not** a usage question (ask them on https://stackoverflow.com/questions/tagged/phpspreadsheet or https://gitter.im/PHPOffice/PhpSpreadsheet)

What is the expected behavior?

Write the spreadsheet to file.

What is the current behavior?

"Sheet does not exist" exception on PhpSpreadsheet\Spreadsheet.php:748 line.

What are the steps to reproduce?

  • I have xlsx template, contains sheets with named ranges ("Sheet1" for example);
  • load this template;
  • drop "Sheet1" - Spreadsheet::removeSheetByIndex();
  • save to file - Xlsx::save(). I got exception this step.
php
<?php
$template = IOFactory::load('some-file.xlsx');
$template->removeSheetByIndex(0);
$writer = new Xlsx($template);
$writer->save('some-file.xlsx');

I fix this problem this way:

php
<?php
$template = IOFactory::load('some-file.xlsx');

$sheet = $template->getSheetByName('Sheet1');
foreach ($template->getNamedRanges() as $range) {
	$template->removeNamedRange($range->getName(), $sheet);
}
$template->removeSheetByIndex(0);

$writer = new Xlsx($template);
$writer->save('some-file.xlsx');

But I think the removeSheetByIndex() method has to drop named ranges with deleting. Maybe Worksheet::__destruct() has to check this relations.

Which versions of PhpSpreadsheet and PHP are affected?

PHP 7.1 PHPSpreadsheet 1.5.2

Source: PHPOffice/PhpSpreadsheet