'An extra worksheet present when creating multiple sheets using phpexcel

I am creating an excel file with different sheets. The different sheets are created by iteration. But my iteration results in an extra sheet named worksheet. My code is:

        $result = fetch results from database;
        $count = COUNT($result);
        foreach ( $result as $key=>$value){ 
            $objPHPExcel->createSheet($key);   
            $objPHPExcel->getActiveSheet()
                   ->setTitle($value['title']);  
        }

My database has got 3 results and it generates three worksheets along with a fourth one which is named as 'Worksheet'.

If I am using a checking condition with

if ($key > 0) {
     execute above code
}
else {
     $objPHPExcel->setActiveSheetIndex(0)->setTitle($value['title']);
}

it works fine. why is it so? Where is the mistake?



Solution 1:[1]

There is nothing wrong with your code. When you instantiate a new PHPExcel object using $objPHPExcel = new PHPExcel(), it is created with a single sheet called "worksheet"; delete that if you want to create only your own sheets

$objPHPExcel->removeSheetByIndex(0);

Solution 2:[2]

Mark Baker's accepted answer as always helped me but I want to expand and explain further on it.

I found that both $objPHPExcel = new PHPExcel() and $objPHPExcel->createSheet() create a single sheet called "worksheet". So use either one.

In the following sample which creates multiple sheets:

$objPHPExcel = new PHPExcel();
// First sheet
$objWorkSheet = $objPHPExcel->createSheet(); // NOT NEEDED
$objWorkSheet = $objPHPExcel->getActiveSheet();
// code for putting first sheet data

// Second sheet
$objWorkSheet = $objPHPExcel->createSheet();
// code for putting second sheet data

// Third, fourth sheets etc

createSheet() isn't needed for the first sheet where I've commented and it'll create that extra blank sheet. new PHPExcel() already made my first one me as he said.

So putting $objPHPExcel->removeSheetByIndex(0) at the end to remove it will work -- But just removing this unneeded line solves it the 'right' way and removes that redundancy. It seems like your code roughly does it like this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark Baker
Solution 2 joeljpa