如何使用 PHPExcel 加入 Excel 文档?
我正在使用 PHPExcel 来动态生成订单收据.
I'm using PHPExcel to dynamically generate order receipts.
我希望能够生成一个摘要"Excel 文件,其中包含所有订单收据(每个工作表一个).
I'd like to be able to generate a "summary" Excel file, containing all the order receipts (one per worksheet).
有没有办法用 PHPExcel 将两个(或多个)Excel 文档连接"成一个?
Is there a way to "join" two (or more) Excel documents into one with PHPExcel ?
推荐答案
在 Excel 中,选项卡"被称为工作表".您可以在 PHPExcel 中创建包含多个工作表的 Excel 工作簿.
In Excel, "tabs" are known as "worksheets". You can create an Excel workbook with multiple worksheets in PHPExcel.
作为参考,关于 SO 的另一个答案有 关于如何向现有工作簿添加其他工作表的易于遵循的指南.
For reference, another answer on SO has an easy-to-follow guide on how to add additional Worksheets to an existing workbook.
Codeplex 上的这篇文章 有一个添加外部工作表的示例.不过,我不确定是否需要所有重命名舞蹈.(Codeplex 链接鼓励您克隆工作表并复制克隆的工作表,以免将其从原始工作簿中删除,但我认为这不是问题,除非您将输出写入源工作簿.)我认为这样的事情应该可行:
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);
}
然后你可以调用 createMasterWorkbook('receipts.xlsx', array(1, 2, 3));
.
相关文章