PHPExcel:将2个Excel文件合并为1到同一工作表中

时间:2013-11-08 21:53:48

标签: php phpexcel

我有2个excel文件 birds.xlsx bees.xlsx ,这两个文件具有相同的列数和相同类型的列标题。我已经看到PHPExcel如何使用excel文件创造奇迹,但有没有办法将2个单独的文件合并到同一个工作表中并将其保存为新文件?想到的类比就像SQL UNION命令一样。

1 个答案:

答案 0 :(得分:3)

类似的东西:

// Load both spreadsheet files
$objPHPExcel1 = PHPExcel_IOFactory::load("birds.xlsx");
$objPHPExcel2 = PHPExcel_IOFactory::load("bees.xlsx");

// Find the last cell in the second spreadsheet
$findEndDataRow = $objPHPExcel2->getActiveSheet->getHighestRow();
$findEndDataColumn = $objPHPExcel2->getActiveSheet->getHighestColumn();
$findEndData = $findEndDataColumn . $findEndDataRow;
// Read all the data from second spreadsheet to a normal PHP array
//    skipping the headers in row 1
$beeData = $objPHPExcel2->getActiveSheet->rangeToArray('A2:' . $findEndData);

// Identify the row in the first spreadsheet where we want to start 
//     adding merged bee data without overwriting any bird data
$appendStartRow = $objPHPExcel1->getActiveSheet->getHighestRow() + 1;
// Add bee data from the PHP array into the bird data
$objPHPExcel1->getActiveSheet->fromArray($beeData, null, 'A' . $appendStartRow);

// Save the spreadsheet with the merged data
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1, 'Excel2007');
$objWriter->save(str_replace('animals.xlsx');