可能有必要以 excel 格式将数据导出到浏览器,或者仅根据从数据库或任何其他来源接收的数据创建 excel 文档。在此示例中,我们将创建一个 (PHP) Web 应用程序,将数据导出到 Excel。

对于这个例子,我们将使用:

  • 安装了 PHP >= 5.5 的计算机
  • 记事本++
  • Microsoft Excel 测试示例
  • PHPExcel

1.PHPExcel

根据该网站,PhpExcel 是一个为 PHP 编程语言提供一组类的项目,它允许您写入和读取不同的电子表格文件格式,如 Excel (BIFF) .xls、Excel 2007 (OfficeOpenXML) .xlsx , CSV, Libre/OpenOffice Calc .ods, Gnumeric, PDF, HTML, … 这个项目是围绕微软的 OpenXML 标准和 PHP 构建的。

PHPExcel 允许您创建一个 excel 文件并将电子表格元数据添加到您的文件中,例如标题、描述、作者、最后修改者、类别、主题等 我们将在此示例中使用 PHPExcel 创建我们的 Excel 文档。
PHPExcel 的要求是

  • PHP 5.2.0 或更高版本
  • 启用 PHP 扩展 php_zip
  • 启用 PHP 扩展 php_xml
  • 启用 PHP 扩展 php_gd2(如果未编译)

要使用 PHP Excel 即时创建 Excel 文件,

  1. 你必须从github下载它
  2. 将内容提取到计算机上合适的位置。
  3. 复制解压缩文件夹中的 classes 文件夹并将其放在应用程序所在的位置。因此,您的文件结构类似于以下文件结构:
    \var\www\Classes
    \var\www\your_app

index.php

<?php

/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');

define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

/** Include PHPExcel */
require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';

// we Create a new PHPExcel object
$objPHPExcel = new PHPExcel();

// Set the excel document properties or metadata
$objPHPExcel->getProperties()->setCreator(" john mark simeon ")
->setLastModifiedBy("john mark simeon ")
->setTitle("john mark simeon phpexcel document ")
->setSubject("john mark simeon phpexcel document")
->setDescription(" This is a test document for webcodegeeks.")
->setKeywords("office PHPExcel php")
->setCategory(" Test result file ");


// Add some data to the excel document
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');

// Miscellaneous glyphs, UTF-8
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A4', 'Miscellaneous glyphs')
->setCellValue('A5', 'test it');
$objPHPExcel->getActiveSheet()->getStyle('A4')->getAlignment()->setWrapText(true);

$objPHPExcel->getActiveSheet()->setCellValue('A8',"Hello\nWorld");
$objPHPExcel->getActiveSheet()->getRowDimension(8)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);


$value = "-ValueA\n-Value B\n-Value C";
$objPHPExcel->getActiveSheet()->setCellValue('A10', $value);
$objPHPExcel->getActiveSheet()->getRowDimension(10)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getStyle('A10')->getAlignment()->setWrapText(true);// we wrap the text in this column so it wouldnt cross it boundary, set this to false and see what happens
$objPHPExcel->getActiveSheet()->getStyle('A10')->setQuotePrefix(true);



// Rename worksheet
echo date('H:i:s') , " Rename worksheet" , EOL;
$objPHPExcel->getActiveSheet()->setTitle('Simple');


// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);


// Save Excel 2007 file
echo date('H:i:s') , " Write to Excel2007 format" , EOL;
$callStartTime = microtime(true);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
?>

在上面的代码中,我们使用 PHPExcel 创建一个 excel 文档。确保完全按照上面关于如何让 PHPExcel 工作的说明进行操作。
在第 18 行,我们创建了一个 PHPExcel 对象。在第 21 行,我们设置文档属性,并在第 30 行开始向 Excel 文档添加数据。
上面的代码教您如何开始使用 PHPExcel。您应该深入了解文档以充分了解 PHPExcel 的所有功能。

index2.php

<?php



<?php
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE); 
ini_set('display_startup_errors', TRUE); 
date_default_timezone_set('Europe/London');

define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

/** Include PHPExcel */
require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';


// Create new PHPExcel object
echo date('H:i:s') , " Create new PHPExcel object" , EOL;
$objPHPExcel = new PHPExcel();

// Set document properties
echo date('H:i:s') , " Set document properties" , EOL;
// Set the excel document properties or metadata
$objPHPExcel->getProperties()->setCreator(" john mark simeon ")
->setLastModifiedBy("john mark simeon ")
->setTitle("john mark simeon phpexcel document ")
->setSubject("john mark simeon phpexcel document")
->setDescription(" This is a test document for webcodegeeks.")
->setKeywords("office PHPExcel php")
->setCategory(" Test result file ");

// Set default font
echo date('H:i:s') , " Set default font" , EOL;
$objPHPExcel->getDefaultStyle()->getFont()->setName('Arial')
->setSize(13);

// Add some data, resembling some different data types
echo date('H:i:s') , " Add some data" , EOL;
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'String')
->setCellValue('B1', 'Simple')
->setCellValue('C1', 'PHPExcel');

$objPHPExcel->getActiveSheet()->setCellValue('A2', 'String')
->setCellValue('B2', 'Symbols')
->setCellValue('C2', '!+&=()~§±æþ');

$objPHPExcel->getActiveSheet()->setCellValue('A3', 'String')
->setCellValue('B3', 'UTF-8')
->setCellValue('C3', 'Создать MS Excel Книги из PHP скриптов');

$objPHPExcel->getActiveSheet()->setCellValue('A4', 'Number')
->setCellValue('B4', 'Integer')
->setCellValue('C4', 12);

$objPHPExcel->getActiveSheet()->setCellValue('A5', 'Number')
->setCellValue('B5', 'Float')
->setCellValue('C5', 34.56);

$objPHPExcel->getActiveSheet()->setCellValue('A6', 'Number')
->setCellValue('B6', 'Negative')
->setCellValue('C6', -7.89);

$objPHPExcel->getActiveSheet()->setCellValue('A7', 'Boolean')
->setCellValue('B7', 'True')
->setCellValue('C7', true);

$objPHPExcel->getActiveSheet()->setCellValue('A8', 'Boolean')
->setCellValue('B8', 'False')
->setCellValue('C8', false);

$dateTimeNow = time();
$objPHPExcel->getActiveSheet()->setCellValue('A9', 'Date/Time')
->setCellValue('B9', 'Date')
->setCellValue('C9', PHPExcel_Shared_Date::PHPToExcel( $dateTimeNow ));
$objPHPExcel->getActiveSheet()->getStyle('C9')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);

$objPHPExcel->getActiveSheet()->setCellValue('A10', 'Date/Time')
->setCellValue('B10', 'Time')
->setCellValue('C10', PHPExcel_Shared_Date::PHPToExcel( $dateTimeNow ));
$objPHPExcel->getActiveSheet()->getStyle('C10')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4);

$objPHPExcel->getActiveSheet()->setCellValue('A11', 'Date/Time')
->setCellValue('B11', 'Date and Time')
->setCellValue('C11', PHPExcel_Shared_Date::PHPToExcel( $dateTimeNow ));
$objPHPExcel->getActiveSheet()->getStyle('C11')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME);

$objPHPExcel->getActiveSheet()->setCellValue('A12', 'NULL')
->setCellValue('C12', NULL);

$objRichText = new PHPExcel_RichText();
$objRichText->createText('你好 ');

$objPayable = $objRichText->createTextRun('你 好 吗?');
$objPayable->getFont()->setBold(true);
$objPayable->getFont()->setItalic(true);
$objPayable->getFont()->setColor( new PHPExcel_Style_Color( PHPExcel_Style_Color::COLOR_DARKGREEN ) );

$objRichText->createText(', unless specified otherwise on the invoice.');

$objPHPExcel->getActiveSheet()->setCellValue('A13', 'Rich Text')
->setCellValue('C13', $objRichText);


$objRichText2 = new PHPExcel_RichText();
$objRichText2->createText("black text\n");

$objRed = $objRichText2->createTextRun("red text");
$objRed->getFont()->setColor( new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_RED ) );

$objPHPExcel->getActiveSheet()->getCell("C14")->setValue($objRichText2);
$objPHPExcel->getActiveSheet()->getStyle("C14")->getAlignment()->setWrapText(true);


$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);

$objRichText3 = new PHPExcel_RichText();
$objRichText3->createText("Hello ");

$objUnderlined = $objRichText3->createTextRun("underlined");
$objUnderlined->getFont()->setUnderline(true);
$objRichText3->createText(' World.');

$objPHPExcel->getActiveSheet()
->getCell("C15")
->setValue($objRichText3);


$objPHPExcel->getActiveSheet()->setCellValue('A17', 'Hyperlink');

$objPHPExcel->getActiveSheet()->setCellValue('C17', 'www.phpexcel.net');
$objPHPExcel->getActiveSheet()->getCell('C17')->getHyperlink()->setUrl('http://www.phpexcel.net');
$objPHPExcel->getActiveSheet()->getCell('C17')->getHyperlink()->setTooltip('Navigate to website');

$objPHPExcel->getActiveSheet()->setCellValue('C18', '=HYPERLINK("mailto:abc@def.com","abc@def.com")');


// Rename worksheet
echo date('H:i:s') , " Rename worksheet" , EOL;
$objPHPExcel->getActiveSheet()->setTitle('Datatypes');


// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);


// Save Excel 2007 file
echo date('H:i:s') , " Write to Excel2007 format" , EOL;
$callStartTime = microtime(true);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;

echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
// Echo memory usage
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;


echo date('H:i:s') , " Reload workbook from saved file" , EOL;
$callStartTime = microtime(true);

$objPHPExcel = PHPExcel_IOFactory::load(str_replace('.php', '.xlsx', __FILE__));

$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
echo 'Call time to reload Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
// Echo memory usage
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;


//var_dump($objPHPExcel->getActiveSheet()->toArray());


// Echo memory peak usage
echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;

// Echo done
echo date('H:i:s') , " Done testing file" , EOL;
echo 'File has been created in ' , getcwd() , EOL;

与第一个脚本相比,上面的示例似乎更复杂,因为它使用了 PHPExcel 的更多功能。我们添加不同类型的原始值,布尔值,整数,浮点数(第 48、52、60 行)。我们将单元格值设置为超链接、电子邮件等。对于初学者来说,使用 PHPExcel 可能会让人不知所措,但如果您遵循并阅读上面的说明和脚本,您将足够快地掌握这个概念。

让我们看一个只有非常基础的非常简单的示例。

index3.php

<?php
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');


define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');


/** Include PHPExcel */
require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';


// Create new PHPExcel object
$objPHPExcel = new PHPExcel();


// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                             ->setLastModifiedBy("Maarten Balliauw")
                             ->setTitle("Office 2007 XLSX Test Document")
                             ->setSubject("Office 2007 XLSX Test Document")
                             ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                             ->setKeywords("office 2007 openxml php")
                             ->setCategory("Test result file");



// Add some data
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'just')
            ->setCellValue('B1', 'the')
            ->setCellValue('C1', 'basics')
            ->setCellValue('D1', '!!!!!');


// Miscellaneous glyphs, UTF-8
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A4', 'Basics Only');
            





$objPHPExcel->getActiveSheet()->setCellValue('A8',"Hello\nWorld");
$objPHPExcel->getActiveSheet()->getRowDimension(8)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);





$value = "-ValueA\n-Value B\n-Value C";
$objPHPExcel->getActiveSheet()->setCellValue('A10', $value);
$objPHPExcel->getActiveSheet()->getRowDimension(10)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getStyle('A10')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('A10')->setQuotePrefix(true);


// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');


// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);


// Save Excel 2007 file


$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));


echo 'Files have been created in ' , getcwd() , EOL;

上面的脚本直截了当,它只是添加了一些数据并创建了 excel 文档(没有什么幻想或复杂的)。

2.总结

在这个例子中,我们学习了如何使用 PHPExcel 在 PHP 中创建一个 excel 文档。我们还学习了如何使用 phpexcel 函数创建 excel 文档。

3.下载源代码

点击下载源码
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。