PHPExcel Check if sheet exists

Get Off My Lawn picture Get Off My Lawn · Mar 12, 2013 · Viewed 32.2k times · Source

I am using phpExcel, and I can't find anything to check if a sheet exists. What I would like to accomplish is something like this:

if(!$excel->sheetExists(1)){
    $excel->createSheet(1);
    $sheet = $excel->setSheet(1);
}
// Do some stuff with the sheet

So. My question: How can I check if a sheet exists?

Edit

Would this work?

try{
    $sheet = $this->excel->setActiveSheetIndex(1);
}catch(Exception $e){
    $excel->createSheet(1);
    $sheet = $excel->setActiveSheetIndex(1);
}

Answer

Mark Baker picture Mark Baker · Mar 12, 2013

If you simply want to know whether a sheetexists at index 1, then

$sheetCount = $excel->getSheetCount();

will return a count of the worksheets. As sheets are indexed incrementally from 0, then a sheet at index 1 will only exist if the count is 2 or more.

If you want to know whether a named sheet exists, then

$sheetNames = $excel->getSheetNames();

will return an array of sheet names (indexed by their index position), and you can then test using in_array();

The

$excel->getSheet()

method will throw an exception if the requested sheet (by index) doesn't exist, so wrap it in a try/catch block would be another approach

$excel->getSheetByName()

returns a NULL value if the named worksheet doesn't exist