thinkphp导出csv格式的表格

时间:2021-04-13 07:39:31
 <?php
 /**
  * Created by PhpStorm.
  * User: hanks
  * Date: 2016/4/20
  * Time: 13:51
  */

 namespace Home\Controller;
 use Think\Controller;

 class CsvController extends Controller
 {
     //导出csv文件
     private static function put_csv($list,$title){
         $file_name="CSV".date("mdHis",time()).".csv";
         header ( 'Content-Type: application/vnd.ms-excel' );
         header ( 'Content-Disposition: attachment;filename='.$file_name );
         header ( 'Cache-Control: max-age=0' );
         $file = fopen('php://output',"a");
         $limit=1000;
         $calc=0;
         foreach ($title as $v){
             $tit[]=iconv('UTF-8', 'GB2312//IGNORE',$v);
         }
         fputcsv($file,$tit);
         foreach ($list as $v){
             $calc++;
             if($limit==$calc){
                 ob_flush();
                 flush();
                 $calc=0;
             }
             foreach ($v as $t){
                 $tarr[]=iconv('UTF-8', 'GB2312//IGNORE',$t);
             }
             fputcsv($file,$tarr);
             unset($tarr);
         }
         unset($list);
         fclose($file);
         exit();
     }

     public function export_data(){
         $list=M("admin_menu")->field('id,menu,c,a')->select();//查询数据,可以进行处理
         $csv_title=array('用户ID','菜单名','控制器名','方法名');
        self::put_csv($list,$csv_title);
     }
 }
 ?>