0

I have two xlsx files: first.xlsx and second.xlsx, I would combine this two files in one and color the second part of the last file appended(second.xlsx). What can I do?

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
Carme
  • 13
  • 1
  • 3

1 Answers1

1

Open/load both files as two separate PHPExcel objects, and use the addExternalSheet() method to move sheets from the second PHPExcel object to the first, then colour to taste and save the first.

$objPHPExcel1 = PHPExcel_IOFactory::load("MergeBook1.xlsx");
$objPHPExcel2 = PHPExcel_IOFactory::load("MergeBook2.xlsx");

foreach($objPHPExcel2->getSheetNames() as $sheetName) {
    $sheet = $objPHPExcel2->getSheetByName($sheetName);
    $sheet->setTitle($sheet->getTitle() . ' copied');
    $objPHPExcel1->addExternalSheet($sheet);
}

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1, 'Excel2007');
$objWriter->save('mergedBooks.xlsx');

The use of addExternalSheet() ensures that all styling, merges, etc as well as cell data is transferred over from the second workbook to the first

You can do whatever additional styling and colouring you want after the merge loop, and before saving

EDIT

If you simply want to copy data from one workbook to another, then something like:

$objPHPExcel1 = PHPExcel_IOFactory::load("MergeBook1.xlsx");
$objPHPExcel2 = PHPExcel_IOFactory::load("MergeBook2.xlsx");

$objPHPExcel1->getActiveSheet()->fromArray(
    $objPHPExcel2->getActiveSheet->toArray(),
    null,
    'A' . ($objPHPExcel1->getActiveSheet()->getHighestRow() + 1)
);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1, 'Excel2007');
$objWriter->save('mergedBooks.xlsx');
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • Sorry, but i don't need to create one file with two worksheet. I would create one file that contains all the cells from file 'one.xlsx' and all cells from file 'two.xlsx'. For example: third_fil.xlsx = (text from first file) + (text from second file) – Carme Jul 16 '15 at 21:02
  • If you only want to take cell data from one file and copy it to another, then load both files and iterate through the cells reading values, styles, etc and copying them across to where you want.... but there's no magic methods for it – Mark Baker Jul 16 '15 at 21:11
  • Can you make me an example? I never used PHPExcel library before – Carme Jul 16 '15 at 21:29
  • This code returns me two errors: "Notice: Undefined property: PHPExcel::$getActiveSheet" and "Fatal error: Call to a member function fromArray() on a non-object" – Carme Jul 16 '15 at 21:59
  • Fixed.... `getActiveSheet()`.... not `getActiveSheet`..... please start reading the PHPExcel documentation and looking at the examples – Mark Baker Jul 16 '15 at 22:01
  • Thanks a lot! I will follow your advice – Carme Jul 16 '15 at 22:06