tp3.2导出csv

function test(){
        $csv=new \Think\Csv();
        $sql = "SELECT count(ga.parentId) as friendnum,a.id,a.uuid,a.nickName,a.agentUserType,a.roomCard,a.createTime,a.lastTime,a.gold,a.parentId FROM t_account as a LEFT JOIN t_account as ga on a.uuid=ga.parentId WHERE ( 1=1 ) GROUP BY a.uuid ORDER BY createTime desc ";
        $list = M('account')->query($sql);  //数据
        $csv_title=array('好友数量','ID','UUID','昵称','用户类型','房卡数量','创建时间','更新时间','金币数量','绑定ID');  //字段
        $csv->put_csv($list,$csv_title);
     }

Csv.class.php

<?php
namespace Think;
class Csv
{
   //导出csv文件
   public function put_csv($list,$title){
       $file_name="CSV".date("Y-m-d",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);
           $tit[]=$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);
               $tarr[]=$t;
           }
           fputcsv($file,$tarr);
           unset($tarr);
       }
       unset($list);
       fclose($file);
       exit();
   }    

}

?>

 

posted @ 2018-01-16 17:31  曹士达  阅读(765)  评论(0编辑  收藏  举报