使用PHPExcel导入导出excel格式文件
使用PHPExcel导入导出excel格式文件
作者:zccst
由于导出使用较多,下面是导出实现过程。
第一步,将PHPExcel的源代码复制到项目的lib下
文件包括:PHPExcel.php 和 文件夹PHPExcel
源代码见附件
注1:源代码是zip格式,能在windows和linux通用。
注2:PHPExcel.zip是干净代码,可以直接引用。PHPExcel2.zip有svn记录,不适合直接引用。
第二步:在需要导出的handler页面中引用
1,在头部引入三个文件
//设置环境变量(新增PHPExcel) set_include_path('.'. PATH_SEPARATOR . Yii::app()->basePath.'/lib/PHPExcel' . PATH_SEPARATOR . get_include_path()); //注:在yii中,也可以直接Yii::import(“application.lib.PHPExcel.*”); //引入PHPExcel相关文件 require_once "PHPExcel.php"; require_once 'PHPExcel/IOFactory.php'; require_once 'PHPExcel/Writer/Excel5.php';
//新建 $resultPHPExcel = new PHPExcel(); //设置参数 //设值 $resultPHPExcel->getActiveSheet()->setCellValue('A1', '季度'); $resultPHPExcel->getActiveSheet()->setCellValue('B1', '名称'); $resultPHPExcel->getActiveSheet()->setCellValue('C1', '数量'); $i = 2; foreach($data as $item){ $resultPHPExcel->getActiveSheet()->setCellValue('A' . $i, $item['quarter']); $resultPHPExcel->getActiveSheet()->setCellValue('B' . $i, $item['name']); $resultPHPExcel->getActiveSheet()->setCellValue('C' . $i, $item['number']); $i ++; }
//设置导出文件名 $outputFileName = 'total.xls'; $xlsWriter = new PHPExcel_Writer_Excel5($resultPHPExcel); //ob_start(); ob_flush(); header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header('Content-Disposition:inline;filename="'.$outputFileName.'"'); header("Content-Transfer-Encoding: binary"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Pragma: no-cache"); $xlsWriter->save( "php://output" );
$writer = PHPExcel_IOFactory::createWriter($resultPHPExcel, 'Excel5'); $writer->setTempDir(Yii::app()->basePath.'/runtime'); $filename = "单.xls"; header("Pragma: public"); 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-Disposition: attachment;filename="' . $filename . '"'); header('Cache-Control: max-age=0'); $writer->save('php://output');
$objPHPExcel = new PHPExcel(); $objReader = PHPExcel_IOFactory::createReader('Excel5'); $objReader->setReadDataOnly(true); foreach($data2 as $item){ $fp = dirname(__FILE__) . "/../../../" . $item['file_path'] ; $objPHPExcel = $objReader->load($fp); $objWorksheet = $objPHPExcel->getActiveSheet(); $resultPHPExcel->addExternalSheet($objWorksheet); }
$finalFileName = (Yii::app()->basePath.'/runtime/'.time().'.xls'; $xlsWriter->save($finalFileName); echo file_get_contents($finalFileName); //file_get_contents() 函数把整个文件读入一个字符串中。和 file() 一样,不同的是 file_get_contents() 把文件读入一个字符串。