thinkphp5導出Excel表格例子

首先是用到了PHPExcel這個類,你能夠去官網下載一個而後隨便找個位置複製過去,我把他粘到了vendor裏面;php

excel導出是吧數據一行一行的寫入到excel而後再下載下來;app

第一行通常是表頭:post

public function excel()
 {      
        $data = array();excel

        //個人數據信息
         $LuntanContentModel = new \app\luntan\model\LuntanContent();   
         $contentRows = $LuntanContentModel->select();
         if($contentRows){
             foreach ($contentRows as $contentRow){
                 $info = array();
                 $row = $contentRow->toArray();對象

                 $info['id'] = $row['id'];
                 $info['author'] = $row['author'];
                 $info['abstract'] = $row['abstract'];
                 $info['title_simple'] = $row['title_simple'];
                 $info['title'] = $row['title'];
                 $info['browse'] = $row['browse'];
                 $data[] = $info;
             }
         }
    //定義表名稱
         $name = 'ABC';get

    //引入PHPExcel,注意看一下是引入的什麼!並非你下載PHPExcel 都是須要的,須要什麼就拿過來什麼好了
         Vendor("PHPExcel.Classes.PHPExcel"); ,
         $excel = new \PHPExcel();it

//定義列數,與excel中的列的命名同樣
         $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'F', 'G');io

//定義表頭信息
         $tableheader = array('ID', '做者', '摘要', '簡約標題', '標題', '瀏覽量');table


         for ($i = 0; $i < count($tableheader); $i++)
         {
             $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
         }function

//寫入信息到excel
         for ($i = 2; $i <= count($data) + 1; $i++)
         {
                 $j = 0;
                 foreach ($data[$i - 2] as $key => $value)
                 {
                     $excel->getActiveSheet()->setCellValue("$letter[$j]$i", "$value");
                     $j++;
                 }
         }

// $dat的數據類型是這樣的

//    array[

  //      array1[],

   //    array2[].

        …

    ]


         //建立Excel輸入對象
         $write = new \PHPExcel_Writer_Excel5($excel);
         header("Pragma: public");
         header("Expires: 0");
         header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
         header("Content-Type:application/force-download");
         header("Content-Type:application/vnd.ms-execl");
         header("Content-Type:application/octet-stream");
         header("Content-Type:application/download");
         header('Content-Disposition:attachment;filename="'.$name.'".xls"');
         header("Content-Transfer-Encoding:binary");
         $write->save('php://output');
 }    

 

 

 

相關文章
相關標籤/搜索