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

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

namespace Common\Event;
use Common\Controller\CommonController;
    /**
     * 数据导出类 用于导出数据
     * @author  Jack<602628161@qq.com>
     * @time    20150113
     */
    class DataPutEvent extends CommonController{
        public function _initialize(){
            parent::_initialize();
            C('SHOW_PAGE_TRACE',false);
        }
        /***
        *测试导出方法,必须放到Controller运行
        function test(){
            $head = array('哈哈','呵呵','嘿嘿','嘎嘎','赫赫','嘻嘻',);
            $data = array(
                '0'=>array(
                    'aa'=>1,
                    'bb'=>1,
                    'cc'=>1,
                    'dd'=>1,
                    'ee'=>1,
                    'ff'=>1,
                ),
                '1'=>array(
                    'aa'=>1,
                    'bb'=>2,
                    'cc'=>1,
                    'dd'=>74,
                    'ee'=>1,
                    'ff'=>52,
                ),
                '2'=>array(
                    'aa'=>17,
                    'bb'=>257,
                    'cc'=>157,
                    'dd'=>747,
                    'ee'=>1527,
                    'ff'=>5275,
                )
            );
            $event = A('Common/DataPut','Event');
            //$result = $event->csvPut($data,$head);
            //$result = $event->csvPut($data);
            //$result = $event->phpexcelPut($data,$head);
            //$result = $event->phpexcelPut($data);
        }
        ****/
        
        
        /**
         * csv数据格式导出
         * @author  Jack<602628161@qq.com>
         * @param     Array     $head     Excel列名信息 
          * @param     Array     $data     Excel数据 二维数组
         * @param     String     $filename     Excel文件名
         * @return  Bool
         **/
        public function csvPut($data=array(), $head=array(), $filename=''){

            if(!$data) return false;
            $array_keys = array_keys($data[0]); //数据数组字段名称
            $head = $head ? $head : $array_keys;
            $filename = $filename ? $filename : (date('YmdHis').'导出记录.csv');
            // 输出Excel文件头
            header("Content-Type: application/vnd.ms-excel");
            header("Content-Disposition: attachment;filename={$filename}");
            header("Cache-Control: max-age=0");
            
            // 打开PHP文件句柄,php://output 表示直接输出到浏览器
            $fp = fopen('php://output', 'a');
            if(!$fp) return false;
            
            // 输出Excel列名信息        
            foreach ($head as $i => $v) {
                // CSV的Excel支持GBK编码,一定要转换,否则乱码
                $head[$i] = iconv('utf-8', 'gbk', $v);
            }
            
            // 将头信息通过fputcsv写到文件句柄
            fputcsv($fp, $head);
            
            // 计数器
            $cnt = 0;
            // 每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
            $limit = 100000;
            
            // 逐行取出数据,不浪费内存
            $count = count($data);
            for($t=0;$t<$count;$t++) {
                $cnt ++;
                if ($limit == $cnt) { //刷新一下输出buffer,防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                $row = $data[$t];
                foreach ($row as $i => $v) {
                    $row[$i] = iconv('utf-8', 'gbk', $v);
                }
                fputcsv($fp, $row);
            }
            
            return true;
        }
        
        
        
        
        
        
        /**
         * phpexcel数据格式导出
         * @author  Jack<602628161@qq.com>
         * @param     Array     $head     Excel列名信息
          * @param     Array     $data     Excel数据 二维数组
         * @param     String     $title     Excel文件标题
         * @return  Bool
         */
        public function phpexcelPut($data=array(),$head=array(),$title=''){
            if(!$data) return false;
            $array_keys = array_keys($data[0]); //数据数组字段名称
            $head = $head ? $head : $array_keys;
            $title = $title ? $title : (date('YmdHis').'导出记录');
            // 输出Excel文件头
            if(!import('ORG.Phpexcel.Phpexcel')) return false;
            // Create new PHPExcel object
            $objPHPExcel = new PHPExcel();
            // Set document properties
            $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                                         ->setLastModifiedBy("Maarten Balliauw")
                                         ->setTitle("Office 2007 XLSX Test Document")
                                         ->setSubject("Office 2007 XLSX Test Document")
                                         ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                                         ->setKeywords("office 2007 openxml php")
                                         ->setCategory("Test result file");    
                                         
            $count = count($data);
            $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');
            if($head){ 
                foreach($head as $k    => $v){
                    $objPHPExcel->getActiveSheet()->getColumnDimension($Array[$k])->setAutoSize(true);   //内容自适应
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($Array[$k]."1", $head[$k]);
                }
            }
            
            $objPHPExcel->setActiveSheetIndex(0);   
            for($i = 2; $i <= $count+1; $i++){    
                foreach($head as $key => $val){
                    $objPHPExcel->getActiveSheet()->setCellValue($Array[$key].$i,' '.$data[$i-2][$array_keys[$key]]);
                    
                }

            }
            
            $objPHPExcel->getActiveSheet()->setTitle($title);
            $objPHPExcel->setActiveSheetIndex(0);
            // Redirect output to a client's web browser (Excel5)
            header("Content-Type: application/vnd.ms-excel");
            header('Content-Disposition: attachment;filename="'.$title.'.xls"');
            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, 'Excel5');
            $objWriter->save('php://output');
            exit;
        }
    
    }