Reputation: 5
I'm trying to add template in multiple sheets with phpexcel:
$sheet = $objPHPExcel->getActiveSheet();
//Start adding next sheets
$i=0;
while ($i < 10) {
$objPHPExcel = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objPHPExcel->load('template.xlsx'); // Empty 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++;
}
Unfortunately this doesn't work. I only get two sheets, sheet with template and sheet with "9" title
So this is the result (sheet titles[image]):
Upvotes: 0
Views: 723
Reputation: 142
You can use PHPSpreadhsheet. This is what the currently deprecated PHPExcel library has been continued as.
Include the library in your .php file in the following way -
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
?>
You can set title by adding-
$spreadsheet->setActiveSheetIndex(0)->setCellValue('A1','Hello');
$spreadsheet->getActiveSheet()->setTitle('new');
$writer = new Xlsx($spreadsheet);
$filename = 'XXX';
header('Content-Disposition: attachment;filename="'. $filename .'.xls"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
Upvotes: 2