一个导出类分享给大家,有更好的也可以讨论

jerry thinkphp 2015年11月19日 收藏
php导出类。支持csv和phpexcel,以前写的
  1. <?php

  2. namespace Common\Event;
  3. use Common\Controller\CommonController;
  4.     /**
  5.      * 数据导出类 用于导出数据
  6.      * @author  Jack<602628161@qq.com>
  7.      * @time    20150113
  8.      */
  9.     class DataPutEvent extends CommonController{
  10.         public function _initialize(){
  11.             parent::_initialize();
  12.             C('SHOW_PAGE_TRACE',false);
  13.         }
  14.         /***
  15.         *测试导出方法,必须放到Controller运行
  16.         function test(){
  17.             $head = array('哈哈','呵呵','嘿嘿','嘎嘎','赫赫','嘻嘻',);
  18.             $data = array(
  19.                 '0'=>array(
  20.                     'aa'=>1,
  21.                     'bb'=>1,
  22.                     'cc'=>1,
  23.                     'dd'=>1,
  24.                     'ee'=>1,
  25.                     'ff'=>1,
  26.                 ),
  27.                 '1'=>array(
  28.                     'aa'=>1,
  29.                     'bb'=>2,
  30.                     'cc'=>1,
  31.                     'dd'=>74,
  32.                     'ee'=>1,
  33.                     'ff'=>52,
  34.                 ),
  35.                 '2'=>array(
  36.                     'aa'=>17,
  37.                     'bb'=>257,
  38.                     'cc'=>157,
  39.                     'dd'=>747,
  40.                     'ee'=>1527,
  41.                     'ff'=>5275,
  42.                 )
  43.             );
  44.             $event = A('Common/DataPut','Event');
  45.             //$result = $event->csvPut($data,$head);
  46.             //$result = $event->csvPut($data);
  47.             //$result = $event->phpexcelPut($data,$head);
  48.             //$result = $event->phpexcelPut($data);
  49.         }
  50.         ****/
  51.         
  52.         
  53.         /**
  54.          * csv数据格式导出
  55.          * @author  Jack<602628161@qq.com>
  56.          * @param     Array     $head     Excel列名信息 
  57.           * @param     Array     $data     Excel数据 二维数组
  58.          * @param     String     $filename     Excel文件名
  59.          * @return  Bool
  60.          **/
  61.         public function csvPut($data=array(), $head=array(), $filename=''){

  62.             if(!$data) return false;
  63.             $array_keys = array_keys($data[0]); //数据数组字段名称
  64.             $head = $head ? $head : $array_keys;
  65.             $filename = $filename ? $filename : (date('YmdHis').'导出记录.csv');
  66.             // 输出Excel文件头
  67.             header("Content-Type: application/vnd.ms-excel");
  68.             header("Content-Disposition: attachment;filename={$filename}");
  69.             header("Cache-Control: max-age=0");
  70.             
  71.             // 打开PHP文件句柄,php://output 表示直接输出到浏览器
  72.             $fp = fopen('php://output', 'a');
  73.             if(!$fp) return false;
  74.             
  75.             // 输出Excel列名信息        
  76.             foreach ($head as $i => $v) {
  77.                 // CSV的Excel支持GBK编码,一定要转换,否则乱码
  78.                 $head[$i] = iconv('utf-8', 'gbk', $v);
  79.             }
  80.             
  81.             // 将头信息通过fputcsv写到文件句柄
  82.             fputcsv($fp, $head);
  83.             
  84.             // 计数器
  85.             $cnt = 0;
  86.             // 每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
  87.             $limit = 100000;
  88.             
  89.             // 逐行取出数据,不浪费内存
  90.             $count = count($data);
  91.             for($t=0;$t<$count;$t++) {
  92.                 $cnt ++;
  93.                 if ($limit == $cnt) { //刷新一下输出buffer,防止由于数据过多造成问题
  94.                     ob_flush();
  95.                     flush();
  96.                     $cnt = 0;
  97.                 }
  98.                 $row = $data[$t];
  99.                 foreach ($row as $i => $v) {
  100.                     $row[$i] = iconv('utf-8', 'gbk', $v);
  101.                 }
  102.                 fputcsv($fp, $row);
  103.             }
  104.             
  105.             return true;
  106.         }
  107.         
  108.         
  109.         
  110.         
  111.         
  112.         
  113.         /**
  114.          * phpexcel数据格式导出
  115.          * @author  Jack<602628161@qq.com>
  116.          * @param     Array     $head     Excel列名信息
  117.           * @param     Array     $data     Excel数据 二维数组
  118.          * @param     String     $title     Excel文件标题
  119.          * @return  Bool
  120.          */
  121.         public function phpexcelPut($data=array(),$head=array(),$title=''){
  122.             if(!$data) return false;
  123.             $array_keys = array_keys($data[0]); //数据数组字段名称
  124.             $head = $head ? $head : $array_keys;
  125.             $title = $title ? $title : (date('YmdHis').'导出记录');
  126.             // 输出Excel文件头
  127.             if(!import('ORG.Phpexcel.Phpexcel')) return false;
  128.             // Create new PHPExcel object
  129.             $objPHPExcel = new PHPExcel();
  130.             // Set document properties
  131.             $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
  132.                                          ->setLastModifiedBy("Maarten Balliauw")
  133.                                          ->setTitle("Office 2007 XLSX Test Document")
  134.                                          ->setSubject("Office 2007 XLSX Test Document")
  135.                                          ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
  136.                                          ->setKeywords("office 2007 openxml php")
  137.                                          ->setCategory("Test result file");    
  138.                                          
  139.             $count = count($data);
  140.             $Array = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
  141.             if($head){ 
  142.                 foreach($head as $k    => $v){
  143.                     $objPHPExcel->getActiveSheet()->getColumnDimension($Array[$k])->setAutoSize(true);   //内容自适应
  144.                     $objPHPExcel->setActiveSheetIndex(0)->setCellValue($Array[$k]."1", $head[$k]);
  145.                 }
  146.             }
  147.             
  148.             $objPHPExcel->setActiveSheetIndex(0);   
  149.             for($i = 2; $i <= $count+1; $i++){    
  150.                 foreach($head as $key => $val){
  151.                     $objPHPExcel->getActiveSheet()->setCellValue($Array[$key].$i,' '.$data[$i-2][$array_keys[$key]]);
  152.                     
  153.                 }

  154.             }
  155.             
  156.             $objPHPExcel->getActiveSheet()->setTitle($title);
  157.             $objPHPExcel->setActiveSheetIndex(0);
  158.             // Redirect output to a client's web browser (Excel5)
  159.             header("Content-Type: application/vnd.ms-excel");
  160.             header('Content-Disposition: attachment;filename="'.$title.'.xls"');
  161.             header("Cache-Control: max-age=0");
  162.             // If you're serving to IE 9, then the following may be needed
  163.             header("Cache-Control: max-age=1");

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

  169.             $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
  170.             $objWriter->save('php://output');
  171.             exit;
  172.         }
  173.     
  174.     }