美文网首页
thinkphp Vue 导出excle

thinkphp Vue 导出excle

作者: wyc0859 | 来源:发表于2019-05-23 10:47 被阅读0次

    lib文件夹下,新建Csv.php

    <?php
    namespace app\lib;
    class Csv
    {
        //导出csv文件
        public 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();
        }
    }
    ?>
    

    控制器方法

    use app\lib\Csv;
     public function daochu()
        {
            $list= OrderModel::order('id desc')->select();
            if(count($list)<1){
                $this->error('没数据怎么导出呢?');
            }
            foreach ($list as $k => $v) {
                $arr[$k]['xu']=$k+1;
                $arr[$k]['number']=$v['order_num'];
                $arr[$k]['status']=$v['status']?'已使用':'待使用';
                $arr[$k]['play_time']=$v['play_time'];
                $arr[$k]['pay_time']=$v['pay_time'];
                $arr[$k]['create_time']=date('Y-m-d H:i:s',$v['create_time']);
            }
    
            $csv=new Csv();
            $csv_title=array('序号','编号','状态','使用时间','付款时间','创建时间');
            $csv->put_csv($arr,$csv_title);
        }
    

    当然把lib的csv类提出来直接放控制器也是OK的
    如果导出是乱码,基本是服务器环境问题!虚拟空间容易导出乱码,服务器一般不会!如果导出是乱码,notepad转无bom头即可

    Vue部分

    A标签下载最简便,href是TP控制器的方法

     daochu(){ 
              const aLink = document.createElement('a');
              let token=localStorage.getItem('token');
              aLink.href = 'https://www.xxx.com/daochu?token='+token
              aLink.target='_blank'
              aLink.download = '2019.csv';
              aLink.click();
              aLink.remove(); 
    }
    

    相关文章

      网友评论

          本文标题:thinkphp Vue 导出excle

          本文链接:https://www.haomeiwen.com/subject/aoqvzqtx.html