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.
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 ...
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.
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++; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With