14

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);
}
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

6 Answers6

33

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

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • I updated my question with a try catch. Its not the same as the `getSheet` but it is similar. – Get Off My Lawn Mar 12 '13 at 15:56
  • 1
    It would work, yes.... one of the great things about open source libraries is that you can actually look at the code and see yourself what it does – Mark Baker Mar 12 '13 at 15:59
3

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

Chris L
  • 616
  • 1
  • 5
  • 11
1

getSheet($sheetNumber) is how you check if a sheet exists.

Matt
  • 5,315
  • 1
  • 30
  • 57
0

Yes your code will also work:

try {
        $objWorksheet =  $objPHPExcel->setActiveSheetIndex(1); 
}
catch (Exception $e) {
    echo 'Sheet is not exists!';
}
Biswadeep Sarkar
  • 841
  • 9
  • 17
0
$sheet=$excel->getSheet(1);
// or you can get sheet by name $sheet=$excel->getSheetByName("Sheet1");
if(!empty($sheet)&&is_object($sheet)){
      //sheet already exist
}else{
      //sheet does not exist. Write your code here!
}
ashraf mohammed
  • 1,322
  • 15
  • 20
0

"TO KNOW THE PRESENT ACTIVE SHEET NUMBER(INDEX)" $this->activeSheet->getActiveSheetIndex()

NOTE: $loadExcel=PHPExcel_IOFactory::load("excelSheetName.xlsx"); $this->activeSheet=$loadExcel;