PHP导出excel文件,第一步先实现PHP模板导出不带数据

2023-07-29,,

今天继续研究PHP导出excel文件,把复杂的事情简单化,一步步实现功能,首先实现模板文件的导出,随后再实现写入数据后导出,最终实现功能,这是基本思路。中间可以加一步,先自己写入数据导出试试,随后再数据库导入。我首先把程序提交到自建的eubexcel.php文件,选用post提交,导出excel文件的程序在这个页面里书写,参考昨天下载的PHPExcel-1.8组件里的参考文档,先部署导出excel,具体代码如下

<?php

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

if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');

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

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

// Read from Excel2007 (.xlsx) template
//echo date('H:i:s') , " Load Excel5 template file" , EOL;
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load("../template/eub.xls");
//print_r($objPHPExcel);
//die();

$filename = "eub-".date("YmdHis").".xls";

// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset="GB2312"');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
?>

在此期间遇到一个问题代码中的 createReader('Excel5');代码,是关于phpExcel导入不同excel版本的设置,我用的模板文件是(97-2003 工作表)是2003年以前的版本,2003以前的excel读取实例化excel5类,2003以后需要实例化excel2007类,so,改改$objReader实例化的地方:其中createReader('Excel2007')改为createReader('Excel5')

PHP导出excel文件,第一步先实现PHP模板导出不带数据的相关教程结束。

《PHP导出excel文件,第一步先实现PHP模板导出不带数据.doc》

下载本文的Word格式文档,以方便收藏与打印。