php excel data export

General amount of data.

The example code for exporting excel is as follows. The main idea is that mysql reads the data to php variable and saves it, organizes it into a string in the beginning format of excel, writes it to the file, and saves it as a xxx.csv file. The characteristics of the excel file must be GBK, and use iconv to convert Custom character encoding iconv("utf-8","GBK//TRANSLIT",$csvStr); A If the content is less excel content, directly inform the file header information, then header("Content-type:text/csv"); header( "Content-Disposition:attachment;filename=".$fileNameCsv); echo it out. Remember to exit. cut off.

B has a lot of data in the file. It needs to paginate to get the data, write to the file, and then header(' Location://http://xxx.xxx.xxx/xx.csv '); Whether the paging ends, you need do{}while() ; If there are multiple servers, you need to use the redis key to store the file name and status (0, no, 1 has a file. The expiration time is one day), and then the data can be judged without worrying about whether it has been generated in the background. . At this time, the timing script is executed every 3 minutes to avoid multi-task accumulation, memory consumption, and service hang. Use exec('ps -efH|grep "'.basename( FILE ).'"', $output); if(count($output) > 3) { //Similar to a daemon process, it is guaranteed to run only 1 of this process print_r ($output); exit; } To determine whether the current execution has been executed, you need to wait for the last execution before executing this time. This program exports 23w, the data is about 1 hour. The business does not need too accurate data, and a delay of several hours is acceptable. When the key value expires in 24 hours, then judge whether the key value has been generated and ask me, and the new file replaces the old file

then download the file

public function crontExportExcel()
    {
        global $redis_obj;
        $saveCsv = F('saveCsv');
        $xml = '';
        $key = 'ORDER:exportExcel';
        $dataArr = json_decode($redis_obj->rPop($key), true);
        if(!$dataArr){
            echo __FILE__.' LINE:'.__LINE__.'; dataArr is empty!'.PHP_EOL;
            return true;
        }
        $saveCsv->crontInit(WEB_PATH.'html/orderExcel/exportExcelGeneral/', $dataArr['exceltype'], $dataArr['ostatus'], $dataArr['otype'], $dataArr['userId']);
        $conditions = json_decode($dataArr['conditions'], true);
        $userCnname = $dataArr['userCnname'];
        $shipOrderList    = M("Order")->getOrderList($conditions,1,2);
        M('Order')->clearReadDB();
        if(empty($shipOrderList)){
            $statusStr    = '没有数据!';
            echo '<script language="javascript">
                                alert("'.$statusStr.'");
                                history.back();
                              </script>';
            exit;
        }
        $shipOrderListSku    = $this->getfullOrderSkuInfo($shipOrderList);
        ############################基础数据##########################################
        $accounts        = $this->getAccountList();//账号数组
        $carriers        = $this->getCarrierList();//运输方式数组
        $AbbToNames      = getCarrierNameByAbb();
        $channels        = $this->getChannelLists();//渠道数组
        $users           = $this->getUserList();//用户数组
        $stores          = array(1=>"赛维网络");
        F('order');
        /*
        $fileName    = "Files_FHQD" . date ( "Y-m-d_H_i_s" ) . ".xls";
        $excel       = new ExportDataExcel ( 'browser', $fileName );
        $excel->initialize();
        */
        //发柜目的仓库,订单号,发柜清单号、发柜时间、SKU、数量、对应SKU销售单价、销售总金额(订单总金额),币种;
        $cellData = array(
            'A'  =>'编号',
            'S'  =>"订单编号",
            'S1'  =>"是否拆分",
            'B'  =>'日期',
            'C'  =>'ebay store',
            'D'  =>'交易号',
            'E'  =>'客户ID',
            'F'  =>'料号',
            'F0' =>'实际库存',
            'F1' =>'组合料号',
            'F2' =>'产品状态',
            'G'  =>'仓位',
            'H'  =>'价格',
            'I'  =>'运费',
            'J'  =>'数量',
            'K'  =>'国家',
            'L'  =>'包裹总价值',
            'M'  =>'币种',
            'N'  =>"包装员",
            'O'  =>"挂号条码",
            'P'  =>"重量",
            'Q'  =>"邮费",
            'R'  =>"运输方式",
            'T'  =>"客户邮箱",
            'U'  =>"同步时间",
            'V'  =>"退回时间",
            'W'  =>"城市",
            'X'  =>"县/洲",
            'Y'  =>"街道",
            'AA'  =>"邮编",
            'AB'  =>"手机号",
            'AC'  =>"电话",
        );
        $spuStatus    = array(
            "1"   =>'在线',
            "2"   =>'停售',
            "3"   =>'暂时停售',
            "4"   =>'部分侵权-ebay',
            "5"   =>'部分侵权-B2B',
            "6"   =>'部分侵权-其他平台',
            "51"  =>'PK产品',
            "101" =>'料号转化'
        );
        $csvStr =  '"'.implode('","', $cellData).'"'.PHP_EOL;
        $xmlHead = iconv("utf-8","GBK//TRANSLIT",$csvStr);
        $saveCsv->saveCsv($xmlHead);
        $numIndex    = 1;
        $usoverseaseObjc  = F('skudailyinfooversease');
        $i = 1;
        $shipOrderList = [];
        do{
            $shipOrderList = M("Order")->getOrderList($conditions,$i,500);
            if(empty($shipOrderList)){
                continue;
            }
            $i++;
            $xml = '';
            foreach ( $shipOrderList as $key => $value ) { // key代表最外层的维数
                /*
                 * $value分别有7个对应的键分别为
                * order订单表头数据记录
                * orderExtension//订单表扩展数据记录
                * orderUserInfo//订单表中客户的数据记录
                * orderWarehouse//物料对订单进行操作的数据记录
                * orderNote //订单的备注(销售人员添加)记录
                * orderTracknumber//订单的追踪号记录
                * orderDetail //订单明细记录
                */
                $orderData            = $value['order'];            // 订单表头数据记录,为一维数组
                $orderExtenData       = $value['orderExtension'];   // 扩展表头数据记录,为一维数组
                $orderUserInfoData    = $value['orderUserInfo'];    // 订单客户数据记录,为一维数组
                $orderWhInfoData      = $value['orderWarehouse'];   // 物料对订单进行操作的数据记录,为一维数组
                $orderNote            = $value['orderNote'];        // 订单备注记录,二维数组
                $orderTracknumber     = $value['orderTracknumber']; // 订单跟踪号,一维数组
                $orderDetail          = $value['orderDetail'];      // 订单明细记录,三维数组
                $orderId              = $orderData['id'];           // ****订单编号 $ebay_id
                $is_split             = $orderData['isSplit'] == 2 ? "是" :"否";           // ****订单编号 $ebay_id
                $accountId            = $orderData['accountId'];
                $platformId           = $orderData['platformId'];
                $accountName          = $accounts[$accountId];
                $orderStore           = $orderData['orderStore'];
                $recordNumber         = $orderData['recordNumber'];
                $paymentTime          = date("Y-m-d H:i:s",$orderData['paymentTime']);
                $actualTotal          = $orderData['actualTotal'];
                $calcWeight           = $orderData['calcWeight'];
                $calcShipping         = $orderData['calcShipping'];
                $transportId          = $orderData['transportId'];
                $orderType            = $orderData['orderType'];
                //获取城市相关信息
                $countryName = $orderUserInfoData['countryName'];
                $city = $orderUserInfoData['city'];
                $state = $orderUserInfoData['state'];
                $address1 = $orderUserInfoData['address1'];
                $zipCode = $orderUserInfoData['zipCode'];
                $mobilePhone = $orderUserInfoData['mobilePhone'];
                $phone = $orderUserInfoData['phone'];
                $orderAddTime         = $orderData['orderAddTime'];
                $orderAddTime         = date("Y-m-d H:i:s",$orderAddTime);
                $operateTime          = "";
                if($orderType == 232 ){
                    $whData               = M('Order')->getAllData("om_unshipped_order_wh","*"," omOrderId=$orderId and orderStatus=232 ");
                    $operateTime          = $whData[0]['operateTime'];
                    $operateTime          = empty($operateTime) ? "" : date("Y-m-d H:i:s",$operateTime);
                }
                $usoverseaseObjc  = F('skudailyinfooversease');
                $carriername          = $carriers[$transportId];
                if(in_array($accountId,array(591,592,593))){ //独立商城特殊处理
                    $transportId      = $orderData['ORtransport'];
                    $carriername      = $AbbToNames[$transportId ];
                }
                if($platformId == 11){
                    $transportId          = M("Order")->getCalOrderTransportId($orderId );
                    $carriername          = $carriers[$transportId];
                }
                $orderTracknumber     = isset($value['orderTracknumber']) ? $value['orderTracknumber'] : array();
                $tracknumber          = isset($orderTracknumber[0]['tracknumber']) ? "'".$orderTracknumber[0]['tracknumber']: "无";
                $orderUserInfo        = $value['orderUserInfo'];
                $userId               = $orderUserInfo['username'];
                $platformUsername     = $orderUserInfo['platformUsername'];
                $countryName          = $orderUserInfo['countryName'];
                $currency             = $orderUserInfo['currency'];
                $email                = hideEmailStr($orderUserInfo['email']);
                $cellData             = array(
                    "A"  => "",
                    "S"  => $orderId,
                    "S1"  => $is_split,
                    "B"  => $paymentTime,
                    "C"  => $accountName,
                    "D"  => $recordNumber,
                    "E"  => $platformUsername,
                    "F"  => "",
                    "F0" => '',
                    "F1" => "",
                    "F2" => "",
                    "G"  => "",//仓位
                    "H"  => "",
                    "I"  => "",
                    "J"  => "",
                    "K"  => $countryName,
                    "L"  => $actualTotal,
                    "M"  => $currency,
                    "N"  => "",//包装员
                    "O"  => $tracknumber,
                    "P"  => $calcWeight,//实际重量
                    "Q"  => $calcShipping,//时际运费
                    "R"  => $carriername,
                    "T"  => $email,//加*号
                    "U"  => $orderAddTime,
                    "V"  => $operateTime,
                    "W"  => $city,
                    "X"  => $state,
                    "Y"  => $address1,
                    "Z"  => $zipCode,
                    "Z1"  => $mobilePhone,
                    "Z2"  => $phone,
                );
                $orderDetails         = $value['orderDetail'];
                $detailNum            = count($orderDetails);
                if($detailNum<=1){
                    $orderDetail      = array_values($orderDetails);
                    $orderDetail      = $orderDetail[0]['orderDetail'];
                    $sku              = $orderDetail['sku'];
                    $amount           = $orderDetail['amount'];
                    $itemPrice        = $orderDetail['itemPrice'];
                    $shippingFee      = $orderDetail['shippingFee'];
                    $skuinfos         = $shipOrderListSku[$sku];
                    $skuinfo          = isset($skuinfos['skuInfo']) ? $skuinfos['skuInfo'] : array() ;
                    if(!empty($skuinfo)){
                        foreach ($skuinfo as $truesku => $trueskuInfo) {//真实sku信息
                            $goodsStatus          = $trueskuInfo['skuDetail']['goodsStatus'];//商品状态 1.在线 2.停售 3.暂时停售 4.部分侵权-ebay 5.部分侵权-B2B 6.部分侵权-其他平台,51.PK产品,101,料号转化。默认为1,在线
                            if(!empty($orderStore)){
                                //获取实际库存
                                //这个地方改成从缓存获取
                                $keyConfig  = array(
                                    1=>  "SkuData:info:",
                                    22=>  "SkuData:info:",
                                    4=>  "us01_overseaseSkuData:info:",
                                    15=> "de01_15_overseaseSkuData:info:",
                                    16=> "us01_16_overseaseSkuData:info:",
                                    20=> "uk01_20_overseaseSkuData:info:",
                                    21=> "jp01_21_overseaseSkuData:info:",
                                    25=> "us01_25_overseaseSkuData:info:",
                                    26=> "us01_26_overseaseSkuData:info:",
                                );
                                $actualStockCount = 0;
                                if(array_key_exists($orderStore,$keyConfig)){
                                    $this_key = $keyConfig[$orderStore];
                                    $this_key .= $truesku;
                                    global $redis_obj;
                                    $stockInfo = $redis_obj->get($this_key);
                                    if(!empty($stockInfo)){
                                        $stockInfo = json_decode($stockInfo,true);
                                        if(in_array($orderStore,array(1))){
                                            $actualStockCount = $stockInfo["stock_qty_shenzhen"];
                                        }elseif(in_array($orderStore,array(22))){
                                            $actualStockCount = $stockInfo["stock_qty_dongguan"];
                                        }else{
                                            $actualStockCount = $stockInfo["stock_qty"];
                                        }
                                    }
                                }
                            }
                            $cellData['F0']       = $actualStockCount;
                            $cellData['F2']       = $spuStatus[$goodsStatus];
                            $cellData['F']    = $truesku;
                            if($sku!=$truesku){
                                $cellData['F1']  = $sku;
                            }
                            $cellData['H']    = $itemPrice;
                            $cellData['I']    = $shippingFee;
                            $cellData['J']    = $amount;
                            if(count($skuinfo)>1){
                                $cellData['A']    = "";
                                $cellData = array_map("html_entity_decode",$cellData);
                                //$excel->addRow($cellData);
                                $csvStr =  '"'.implode('","', $cellData).'"'.PHP_EOL;
                                $xml .= iconv("utf-8","GBK//TRANSLIT",$csvStr);
                                $csvStr = "";
                            }else{
                                $cellData['A']    = $numIndex;
                                $cellData = array_map("html_entity_decode",$cellData);
                                //$excel->addRow($cellData);
                                $csvStr =  '"'.implode('","', $cellData).'"'.PHP_EOL;
                                $xml .= iconv("utf-8","GBK//TRANSLIT",$csvStr);
                                $csvStr = "";
                                $numIndex++;
                            }
                        }
                    }else{
                        $cellData['F']    = $sku;
                        $cellData['F1']    = $sku;
                        $cellData['H']    = $itemPrice;
                        $cellData['I']    = $shippingFee;
                        $cellData['J']    = $amount;
                        $cellData['A']    = $numIndex;
                        $cellData = array_map("html_entity_decode",$cellData);
                        $csvStr =  '"'.implode('","', $cellData).'"'.PHP_EOL;
                        $xml .= iconv("utf-8","GBK//TRANSLIT",$csvStr);
                        $csvStr = "";
                        $numIndex++;
                    }
                    unset($orderDetail);
                }else{
                    //$orderDetailNE      = array_values($orderDetails);
                    //$orderDetailArr     = $orderDetailNE['orderDetail'];
                    $totalMoney         = 0;
                    $totalShipFee       = 0;
                    $totalamount        = 0;
                    $cellDatasSplilts    = array();
                    foreach($orderDetails as $orderDetail){
                        $sku              = $orderDetail['orderDetail']['sku'];
                        $amount           = $orderDetail['orderDetail']['amount'];
                        $totalamount     += $amount;
                        $itemPrice        = $orderDetail['orderDetail']['itemPrice'];
                        $totalMoney      += $amount*$itemPrice;
                        $shippingFee      = $orderDetail['orderDetail']['shippingFee'];
                        $totalShipFee    += $shippingFee;
                        $skuinfos          = $shipOrderListSku[$sku];
                        $skuinfo          = isset($skuinfos['skuInfo']) ? $skuinfos['skuInfo'] : array() ;
                        if(!empty($skuinfo)){
                            foreach ($skuinfo as $truesku => $trueskuInfo) {//真实sku信息
                                $cellData['F']    = $truesku;
                                //$skuShippedInfo   = M('Order')->GetSkuDailystatus($truesku);
                                //$actualStockCount     = $skuShippedInfo[0]['actualStockCount'];//实际库存
                                //这个地方改成从缓存获取
                                $keyConfig  = array(
                                    1=>  "SkuData:info:",
                                    22=>  "SkuData:info:",
                                    4=>  "us01_overseaseSkuData:info:",
                                    15=> "de01_15_overseaseSkuData:info:",
                                    16=> "us01_16_overseaseSkuData:info:",
                                    20=> "uk01_20_overseaseSkuData:info:",
                                    21=> "jp01_21_overseaseSkuData:info:",
                                    25=> "us01_25_overseaseSkuData:info:",
                                    26=> "us01_26_overseaseSkuData:info:",
                                );
                                $actualStockCount = 0;
                                if(array_key_exists($orderStore,$keyConfig)){
                                    $this_key = $keyConfig[$orderStore];
                                    $this_key .= $truesku;
                                    $stockInfo = $redis_obj->get($this_key);
                                    if(!empty($stockInfo)){
                                        $stockInfo = json_decode($stockInfo,true);
                                        if(in_array($orderStore,array(1))){
                                            $actualStockCount = $stockInfo["stock_qty_shenzhen"];
                                        }elseif(in_array($orderStore,array(22))){
                                            $actualStockCount = $stockInfo["stock_qty_dongguan"];
                                        }else{
                                            $actualStockCount = $stockInfo["stock_qty"];
                                        }
                                    }
                                }
                                $goodsStatus          = $trueskuInfo['skuDetail']['goodsStatus'];//商品状态 1.在线 2.停售 3.暂时停售 4.部分侵权-ebay 5.部分侵权-B2B 6.部分侵权-其他平台,51.PK产品,101,料号转化。默认为1,在线
                                $cellData['F0']       = $actualStockCount;
                                $cellData['F2']       = $spuStatus[$goodsStatus];
                                if($sku!=$truesku){
                                    $cellData['F1']  = $sku;
                                }
                                $cellData['H']    = $itemPrice;
                                $cellData['I']    = $shippingFee;
                                $cellData['J']    = $amount;
                                $cellData['A']    = "";
                                $cellDatasSplilts[]=$cellData;
                            }
                        }else{
                            $cellData['F']    = $sku;
                            $cellData['F1']   = $sku;
                            $cellData['H']    = $itemPrice;
                            $cellData['I']    = $shippingFee;
                            $cellData['J']    = $amount;
                            $cellData['A']    = "";
                            $cellDatasSplilts[]=$cellData;
                        }
                    }
                    $cellData['F']         = "无";
                    $cellData['F1']        = "无";
                    $cellData['F2']        = '';
                    $cellData['H'] = "";
                    $cellData['I'] = "";
                    $cellData['J'] = "";
                    $cellData['A'] = $numIndex;
                    $numIndex++;
                    $cellData = array_map("html_entity_decode",$cellData);
                    $csvStr =  '"'.implode('","', $cellData).'"'.PHP_EOL;
                    $xml .= iconv("utf-8","GBK//TRANSLIT",$csvStr);
                    $csvStr = "";
                    foreach ($cellDatasSplilts as $cellData) {
                        $csvStr =  '"'.implode('","', $cellData).'"'.PHP_EOL;
                        $xml .= iconv("utf-8","GBK//TRANSLIT",$csvStr);
                        $csvStr = "";
                    }
                }//end of else; */
            }//end of foreach orderLists
            $status = $saveCsv->saveCsv($xml, 1);
        }while(!empty($shipOrderList));
        $fileKey = $saveCsv->getFileKey();
        $redis_obj->set($fileKey, 1, 90000);
        $title = '订单系统小包缺货excel 下载通知邮件';
        $contact = '你好,'.PHP_EOL;
        $contact .= 'time: '.date('Y-m-d H:i').'. 订单系统小包缺货excel 已经同步完成,请回到页面点击下载';
        $emailResult = M("InterfaceNotice")->sendMessageByNoticeSys($contact, $title, $userCnname);
        if ($emailResult['errCode'] == 2013) {
            echo date('Y-m-d H:i')."订单系统小包缺货excel 下载通知邮件已经发出", PHP_EOL;
        }
        return $status;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325064118&siteId=291194637