laravel的excel導出


第一步:先在App文件目錄下創建libs目錄
第二步:將Excel.php第三方類文件引入
第三步:進入composer.json文件中,在autoload數組中classmap加入路徑""app/libs/Excel.php""
第四步:到項目的根目錄下,在命令行中運行composer dumpautoload
調用的方法為:
  use Excel;
 //excel表導出
    public function excel()
    {
        $name=date("Y-m-d-H:i:s").rand(1000,9999).'.xls';
        $data=DB::table('admin')->get();
        $obj=new Excel();
        foreach($data as $k=>$v)
        {
            $info[$k][] = $v->admin_id;
            $info[$k][] = $v->admin_name;
            $info[$k][] = $v->admin_pwd;
        }

        $headtitle="<tr><th colspan='3'>數據導出</th></tr>";
        $title="ID號\t登錄姓名\t登錄密碼\t\n";
        $filename = $name;
        $obj->excelData($info,$title,$headtitle,$filename);
    }


Excel.php
<?php
 class Excel{
      /**
      * @desc   將數據導出到Excel中
      * @param  $data array 設置表格數據
      * @param  $titlename string 設置head
      * @param  $title string 設置表頭
      * @param  $filename 設置默認文件名
      * @return 將字符串輸出,即輸出字節流,下載Excel文件
     */
     public function excelData($data,$titlename,$title,$filename){
         #xmlns即是xml的命名空間
         $str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>";
         #以下構建一個html類型格式的表格
         $str .= $title;
         $str .="<table border=1><head>".$titlename."</head>";
         foreach ($data  as $key=> $rt )
         {
             $str .= "<tr>";
             foreach ( $rt as $k => $v )
             {
                 $str .= "<td>{$v}</td>";
             }
             $str .= "</tr>\n";
         }
         $str .= "</table></body></html>";
         header( "Content-Type: application/vnd.ms-excel; name='excel'" );   #類型
         header( "Content-type: application/octet-stream" );     #告訴瀏覽器響應的對象的類型(字節流、瀏覽器默認使用下載方式處理)
         header( "Content-Disposition: attachment; filename=".$filename );   #不打開此文件,刺激瀏覽器彈出下載窗口、下載文件默認命名
         header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
         header( "Pragma: no-cache" );   #保證不被緩存或者說保證獲取的是最新的數據
         header( "Expires: 0" );
         exit( $str );
     }
}
?>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM