Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPExcel Check if sheet exists

Tags:

php

phpexcel

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);
}
like image 602
Get Off My Lawn Avatar asked Mar 12 '13 15:03

Get Off My Lawn


2 Answers

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

like image 120
Mark Baker Avatar answered Oct 14 '22 09:10

Mark Baker


You can check if a sheet exists by name with the method sheetNameExists($pSheetName).

like image 3
Chris L Avatar answered Oct 14 '22 07:10

Chris L