1

Currently using template excel sheet to add data, the requirement is add new sheet too, so need to add new sheet with same template.

My starts with new tamplate :

$filePath = public_path('Template.xls');
$objPHPExcel = PHPExcel_IOFactory::load($filePath);

Now, I have to create new sheet in same file with same tamplate without clone first sheet, because need to load fresh template without data.

151291
  • 3,308
  • 7
  • 48
  • 81

2 Answers2

3

You don't simply want to create a new sheet, you want to copy a sheet with all its existing styleing

So create a clone of the existing sheet, give it a new title (because worksheet titles must be unique), and attach that clone to the workbook.

$newSheet = clone $objPHPExcel->getActiveSheet();
$newSheet->setTitle('Worksheet 2');
$objPHPExcel->addSheet($newSheet);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • I should not clone from active sheet, because it copies from all entered data. I need a fresh template getting loaded. but condition is after fill first sheet. – 151291 Aug 05 '17 at 13:55
1

You've modified the question since I posted the answer to your original question.

If you need to create a new worksheet from the template after you've already loaded the original template and populated it with data, then you'll need to reload the template as a new PHPExcel object, and inject the worksheet from that into your original workbook:

$filePath = public_path('Template.xls');
$objPHPExcel = PHPExcel_IOFactory::load($filePath);
// fill with data
$template = PHPExcel_IOFactory::load($filePath);
$newSheet = clone $template->getActiveSheet();
$objPHPExcel->addExternalSheet($newSheet);

the addExternalSheet() method ensures that all styles and structure (merged cells) are copied cleanly with the worksheet when it is added. Simply using the addSheet() method isn't guaranteed to copy that information correctly

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • Hope, my heading shows clearly that I need new template not a clone of filled data. i just added for explanation at bottom. nothing new I added in my question. – 151291 Aug 07 '17 at 07:19
  • Well a template is generally without data; once you've added data to a template, it ceases to be a template – Mark Baker Aug 07 '17 at 09:42