最近一个功能需要导出到excel中,但是使用phpexcel特别慢,30W起码半个小时。最后尝试用fputcsv去导出csv发现非常之快,30W数据只要10几秒。不过只能导出一般格式数据,如有合并单元格,设置多sheet,确是无能为力,不过提升的速度是非常之大。

 public function ce(){
            error_reporting(E_ALL);
            ini_set('display_errors', TRUE);
            ini_set('display_startup_errors', TRUE);
            ini_set("memory_limit", "2048M");
            set_time_limit(0);
            $dbs = DB::connection('mysql_online')->select('SELECT hwid,charge,valid,voltage,from_unixtime(client_time,"%Y-%m-%d %H:%i:%S") AS start ,from_unixtime(server_time,"%Y-%m-%d %H:%i:%S") as end FROM tb_logs_bp LIMIT 300000');
    //      $dbs = Logbp::all();
            $cellData=[];
    
            header('Content-Description: File Transfer');
            header('Content-Type: application/vnd.ms-excel');
          header('Content-Disposition: attachment; filename="'. $filename .'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            $fp = fopen('php://output', 'a');//打开output流
    
    
            foreach ($dbs as $db){
                $db->charge= $this->checkcharge($db->charge);
                $db->valid = $this->checkvalid($db->valid);
                $db->voltage  = $db->voltage/10;
                $data=[$db->hwid,$db->charge,$db->valid,$db->voltage,$db->start,$db->end];
                mb_convert_variables('GBK', 'UTF-8', $data);
                fputcsv($fp, $data);
            }
            unset($dbs);
            ob_flush();
            flush();
            fclose($fp);
            exit();
    
        }

注意不能使用 ajax的方式去请求,会导致不能够下载,要需要url请求的方式去请求例如:

  $('#do_excel').click(function () {
                var order_id = $('#order_id').val()
                var date  =$('#date').val()

                var url = '{{route('hwtc.excel.get_table')}}' + '?order_id=' + order_id+'&date='+date
                location.href = url;

            })
Logo

永洪科技,致力于打造全球领先的数据技术厂商,具备从数据应用方案咨询、BI、AIGC智能分析、数字孪生、数据资产、数据治理、数据实施的端到端大数据价值服务能力。

更多推荐