如何从PHP生成具有多个工作表的Excel文档?

我想从PHP生成MS Excel文件。我知道一个人可以做这样的事情:

header ( "Content-type: application/vnd.ms-excel" );

header ( "Content-Disposition: attachment; filename=foo_bar.xls" );

但是它将生成一个只有一张图纸的文件。我要生成的文件有多个工作表。我怎样才能做到这一点?也许有第三方图书馆,但我还没有发现太多。

回答:

尝试查看PHPExcel。这是一个简单的示例,该示例创建一个包含两页的Excel文件:

<?php

require_once 'PHPExcel.php';

require_once 'PHPExcel/IOFactory.php';

// Create new PHPExcel object

$objPHPExcel = new PHPExcel();

// Create a first sheet, representing sales data

$objPHPExcel->setActiveSheetIndex(0);

$objPHPExcel->getActiveSheet()->setCellValue('A1', 'Something');

// Rename sheet

$objPHPExcel->getActiveSheet()->setTitle('Name of Sheet 1');

// Create a new worksheet, after the default sheet

$objPHPExcel->createSheet();

// Add some data to the second sheet, resembling some different data types

$objPHPExcel->setActiveSheetIndex(1);

$objPHPExcel->getActiveSheet()->setCellValue('A1', 'More data');

// Rename 2nd sheet

$objPHPExcel->getActiveSheet()->setTitle('Second sheet');

// Redirect output to a client’s web browser (Excel5)

header('Content-Type: application/vnd.ms-excel');

header('Content-Disposition: attachment;filename="name_of_file.xls"');

header('Cache-Control: max-age=0');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

$objWriter->save('php://output');

以上是 如何从PHP生成具有多个工作表的Excel文档? 的全部内容, 来源链接: utcz.com/qa/416894.html

回到顶部