首页 > 开发 > PHP > 正文

PHP导出EXCEL快速开发指南--PHPEXCEL的使用详解

2024-05-04 22:26:44
字体:
来源:转载
供稿:网友
PHP导出EXCEL快速开发指南
phpexcel有专有的开发文档,详细操作请参考其开发文档,本文档只是对其在使用上作了优化整合,便于在新项目中快速开发。
phpexcel生成文件同样有两种方式,一种方式为直接输出,一种方式为生成静态文件。
直接输出:
主文件为(class目录的同目录文件):
代码如下:
<?php
include("./class/class.php"); // 包含class的基本头文件
include("./class/phpexcel/PHPExcel.php"); // 生成excel的基本类定义(注意文件名的大小写)
// 如果直接输出excel文件,则要包含此文件
include("./class/phpexcel/PHPExcel/IOFactory.php");
// 创建phpexcel对象,此对象包含输出的内容及格式
$m_objPHPExcel = new PHPExcel();
// 模板文件,为了实现格式与内容分离,有关输出文件具体内容实现在模板文件中
// 模板文件将对象$m_objPHPExcel进行操作
include("./include/excel.php");
// 输出文件的类型,excel或pdf
$m_exportType = "excel";
$m_strOutputExcelFileName = date('Y-m-j_H_i_s').".xls"; // 输出EXCEL文件名
$m_strOutputPdfFileName = date('Y-m-j_H_i_s').".pdf"; // 输出PDF文件名
// PHPExcel_IOFactory, 输出excel
//require_once dirname(__FILE__).'/Classes/PHPExcel/IOFactory.php';
// 如果需要输出EXCEL格式
if($m_exportType=="excel"){
$objWriter = PHPExcel_IOFactory::createWriter($m_objPHPExcel, 'Excel5');
// 从浏览器直接输出$m_strOutputExcelFileName
header("Pragma: public");
header("Expires: 0");
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type: application/vnd.ms-excel;");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");
header("Content-Disposition:attachment;filename=".$m_strOutputExcelFileName);
header("Content-Transfer-Encoding:binary");
$objWriter->save("php://output");
}
// 如果需要输出PDF格式
if($m_exportType=="pdf"){
$objWriter = PHPExcel_IOFactory::createWriter($m_objPHPExcel, 'PDF');
$objWriter->setSheetIndex(0);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type: application/pdf");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");
header("Content-Disposition:attachment;filename=".$m_strOutputPdfFileName);
header("Content-Transfer-Encoding:binary");
$objWriter->save("php://output");
}
?>

模板文件内容(附加常用操作)
代码如下:
<?php
global $m_objPHPExcel; // 由外部文件定义
// 设置基本属性
$m_objPHPExcel->getProperties()->setCreator("Sun Star Data Center")
->setLastModifiedBy("Sun Star Data Center")
->setTitle("Microsoft Office Excel Document")
->setSubject("Test Data Report -- From Sunstar Data Center")
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表