Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPExcel - creating multiple sheets by iteration

Tags:

php

phpexcel

I'm trying to create multiple sheets by iteration in phpexcel:

$i=0;  while ($i < 10) {  // Add new sheet $objWorkSheet = $objPHPExcel->createSheet();  //  Attach the newly-cloned sheet to the $objPHPExcel workbook $objPHPExcel->addSheet($objWorkSheet);  // Add some data $objPHPExcel->setActiveSheetIndex($i);  $sheet = $objPHPExcel->getActiveSheet();  $sheet->setCellValue('A1', 'Hello'.$i)         ->setCellValue('B2', 'world!')         ->setCellValue('C1', 'Hello')         ->setCellValue('D2', 'world!');  // Rename sheet $sheet->setTitle($i);  $i++; } 

Unfortunately this doesn't work. I only get some sheets of this iteration filled with data and renamed and about the half are empty.

So this is the result (sheet titles):

0, 2, 4, 6, 8, 9, and 5 empty sheets

I can't figure out why only even numbered (and sheet 9) are correct in the result.

like image 350
Chris Avatar asked Mar 24 '12 07:03

Chris


People also ask

How can I create multiple sheets in Excel using Phpexcel?

When you first instantiate the $objPHPExcel, it already has a single sheet (sheet 0); you're then adding a new sheet (which will become sheet 1), but setting active sheet to sheet $i (when $i is 0)... so you're renaming and populating the original worksheet created when you instantiated $objPHPExcel rather than the one ...

Is Phpexcel deprecated?

PHP Excel was officially deprecated in 2017 and permanently archived in 2019. PHP Excel has not be maintained for years and must not be used anymore. All users must migrate to its direct successor PhpSpreadsheet, or another alternative.


1 Answers

You dont need call addSheet() method. After creating sheet, it already add to excel. Here i fixed some codes:

    //First sheet     $sheet = $objPHPExcel->getActiveSheet();      //Start adding next sheets     $i=0;     while ($i < 10) {        // Add new sheet       $objWorkSheet = $objPHPExcel->createSheet($i); //Setting index when creating        //Write cells       $objWorkSheet->setCellValue('A1', 'Hello'.$i)                    ->setCellValue('B2', 'world!')                    ->setCellValue('C1', 'Hello')                    ->setCellValue('D2', 'world!');        // Rename sheet       $objWorkSheet->setTitle("$i");        $i++;     } 
like image 131
safarov Avatar answered Sep 27 '22 19:09

safarov