Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I join Excel documents using PHPExcel?

I'm using PHPExcel to dynamically generate order receipts.

I'd like to be able to generate a "summary" Excel file, containing all the order receipts (one per worksheet).

Is there a way to "join" two (or more) Excel documents into one with PHPExcel ?

like image 213
mike23 Avatar asked Sep 02 '11 16:09

mike23


People also ask

How do I merge cells in Excel using Phpexcel?

$sheet = $workbook->getActiveSheet(); $sheet->setCellValue('A1','A pretty long sentence that deserves to be in a merged cell'); $sheet->mergeCells('A1:C1');

How do I select a location to save an Excel file using Phpexcel?

Change the file name to desired path i.e, $name = '/path/to/folder/xyz. xlsx'; $objWriter->save($name);


1 Answers

In Excel, "tabs" are known as "worksheets". You can create an Excel workbook with multiple worksheets in PHPExcel.

For reference, another answer on SO has an easy-to-follow guide on how to add additional Worksheets to an existing workbook.

This post on Codeplex has an example of adding an external sheet. I'm not sure all of the renaming dance is needed though. (The Codeplex link encourages you to clone the worksheet and copy the cloned sheet so as not to remove it from the original workbook, but I don't think that would be an issue unless you're writing output to the source workbook.) I think something like this should work:

function getReceiptWorksheet( $receiptNumber ) {
    // Do something here to retrieve & return your existing receipt
}

function createMasterWorkbook( $filename, $receiptNumbers ) {
    $workbook= new PHPExcel();

    foreach( $receiptNumbers as $receiptNumber ){
         $worksheet = getReceiptWorksheet( $receiptNumber )
         $workbook->addExternalSheet( $worksheet );
    }

    $objWriter = new PHPExcel_Writer_Excel2007($workbook);
    $objWriter->save($filename);
}

Then you could just call createMasterWorkbook( 'receipts.xlsx', array( 1, 2, 3 ) );.

like image 92
Farray Avatar answered Nov 14 '22 05:11

Farray