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.
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++;
}