PHP:基于phpExcel的导出Excel工具类
1 <?php 2 /* 3 * 类的功能 4 * 传入二位数组导出excel 5 * 传入excel 导出二位数组 6 * @author mrwu 7 */ 8 require('PHPExcel.php'); 9 require_once 'PHPExcel/Reader/Excel5.php'; 10 include 'PHPExcel/IOFactory.php'; 11 12 class plugin_phpexcel 13 { 14 private $export_excel_title;//导出excel标题 15 private $export_sheet_title;//导出sheet标题 16 private $letters; 17 private $php_excel;//php_excel操作类 18 private $active_sheet; 19 20 function __construct($export_excel_title='excel',$export_sheet_title='sheet1') 21 { 22 $this->letters=range('A','Z',1); 23 $this->php_excel=new PHPExcel(); 24 $this->php_excel->setActiveSheetIndex(0); 25 $this->active_sheet=$this->php_excel->getActiveSheet(); 26 $this->export_excel_title=$export_excel_title; 27 $this->export_sheet_title=$export_sheet_title; 28 } 29 30 /* 31 * $title='标题' array 32 * $import_arr 插入excel的数组 要求二位数组 33 */ 34 function export($title=array(),$import_arr) 35 { 36 //有设置excel第一行的标题 37 if($title) 38 { 39 $count=count($title); 40 for($i=0;$i<=$count;$i++) 41 { 42 $this->active_sheet->setCellValue($this->letters[$i].'1',$title[$i]); 43 } 44 } 45 //循环插入二维数组 46 $count=count($import_arr[0]); 47 $row=1; 48 foreach($import_arr as $value) 49 { 50 51 $row++; 52 $j=0; 53 foreach($value as $key=>$v) 54 { 55 $this->active_sheet->setCellValue($this->letters[$j].$row,$v); 56 echo $value[$j]; 57 $j++; 58 } 59 } 60 $phpWriter=PHPExcel_IOFactory::createWriter($this->php_excel,'Excel5'); 61 //设置一些标题等 62 $file=$this->export_excel_title; 63 $this->active_sheet->setTitle($this->export_sheet_title); 64 65 //设置header 66 header("Pragma: public"); 67 header("Expires: 0"); 68 header("Cache-Control:must-revalidate, post-check=0, pre-check=0"); 69 header("Content-Type:application/force-download"); 70 header("Content-Type:application/vnd.ms-execl"); 71 header("Content-Type:application/octet-stream"); 72 header("Content-Type:application/download"); 73 header('Content-Disposition:attachment;filename="excel.xls"'); 74 header("Content-Transfer-Encoding:binary"); 75 76 $phpWriter->save('php://output'); 77 78 79 } 80 } 81 //测试 82 $php_excel=new plugin_phpexcel('excel','sheet1'); 83 $php_excel->export(array('title','content'),array(array('title'=>'haha','content'=>'shit'),array('title'=>'hehe','content'=>'fuck')));