Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge Excel files using php

Tags:

merge

php

excel

I have two excel files each with a single worksheet. I want to take the two excel files and create a single excel file with two worksheets. I would like to do this with PHP. Can anyone point me in the right direction?

like image 831
broncofan7 Avatar asked Apr 12 '26 06:04

broncofan7


1 Answers

Using PHPExcel

$inputFileType1 = 'Excel2007';
$inputFileName1 = 'inputData1.xlsx';
$inputFileType2 = 'Excel5';
$inputFileName2 = 'inputData2.xls';
$outputFileType = 'Excel5';
$outputFileName = 'outputData.xls';

// Load the first workbook (an xlsx file)
$objPHPExcelReader1 = PHPExcel_IOFactory::createReader($inputFileType1);
$objPHPExcel1 = $objPHPExcelReader1->load($inputFileName1);

// Load the second workbook (an xls file)
$objPHPExcelReader2 = PHPExcel_IOFactory::createReader($inputFileType2);
$objPHPExcel2 = $objPHPExcelReader2->load($inputFileName2);

// Merge the second workbook into the first
$objPHPExcel2->getActiveSheet()->setTitle('Unique worksheet name');
$objPHPExcel1->addExternalSheet($objPHPExcel2->getActiveSheet());

// Save the merged workbook under a new name (could save under the original name)
// as an xls file
$objPHPExcelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1,$outputFileType);
$objPHPExcelWriter->save($outputFileName);
like image 187
Mark Baker Avatar answered Apr 13 '26 20:04

Mark Baker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!