0
votes

Is it not possible to create a function with PHPexcel like this?

$objPHPExcel = new PHPExcel();

global $objPHPExcel;

function Create($title, $index)
{
    global $objPHPExcel;

   $objPHPExcel->setActiveSheetIndex($index);
   $objPHPExcel->getActiveSheet()->setTitle($title);
}


Create('Title1', 0);
Create('Title2', 1);

I get this error: Fatal error: Uncaught exception 'PHPExcel_Exception' with message 'You tried to set a sheet active by the out of bounds index: 1. The actual number of sheets is 1

1
Check your error message, in the second call to Create you pass 1 as $index and it seems that you Excel file only has one sheet. - yorodm

1 Answers

0
votes

You missed createSheet() which is needed every time you...well...create a new Excel sheet. I've also passed the object as parameter into the function and used type hinting to only allow the object to be of the type needed (PHPExcel in your case).

   $objPHPExcel = new PHPExcel(); //Create your object

    function Create(PHPExcel $objPHPExcel, $title, $index) //Set param object to be of Type PHPExcel (Type Hinting)
    {

       $objPHPExcel->setActiveSheetIndex($index);
       $objPHPExcel->getActiveSheet()->setTitle($title);
       $objPHPExcel->createSheet(); //New Sheet

    }

    Create($objPHPExcel, 'Title1', 0); //Set Object For Each Param
    Create($objPHPExcel, 'Title2', 1); //Set Object For Each Param

See:

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration