Search code examples
phpexcelworksheet

How to delete worksheet in PHPExcel


In PHPExcel how can I delete a sheet with the name worksheet?

I have this, but it does not work:

$objWorkSheet->removeSheetByIndex("Worksheet");

Solution

  • Worksheet is the name of a worksheet, not its index (position within the collection of worksheets). You need to identify its index position and use that as the argument to removeSheetByIndex()

    Something like:

    $objWorkSheet->setActiveSheetIndexByName('Worksheet');
    $sheetIndex = $objWorkSheet->getActiveSheetIndex();
    $objWorkSheet->removeSheetByIndex($sheetIndex);
    

    or

    $objWorkSheet->removeSheetByIndex(
        $objWorkSheet->getIndex(
            $objWorkSheet->getSheetByName('Worksheet')
        )
    );