php excel數據導出

通常的數據量。javascript

導出excel 例子代碼以下,主要思路是mysql 讀取數據到php 變量保存,整理成excel 開頭格式的字符串,寫入文件,保存爲 xxx.csv 文件, excel 文件的特性,必須 是GBK, 使用 iconv 轉義 字符編碼 iconv("utf-8","GBK//TRANSLIT",$csvStr); A 若是內容少 excel 內容直接 告知文件頭信息,而後 header("Content-type:text/csv"); header("Content-Disposition:attachment;filename=".$fileNameCsv); echo 出來就能夠。 記得須要exit。斷掉。php

B 文件數據比較多,須要分頁獲取數據,寫入 文件,而後header('Location://http://xxx.xxx.xxx/xx.csv'); 分頁是否截至,須要 do{}while(); 若是是多臺服務器,那麼須要藉助 redis key ,存儲 文件名,還有狀態 (0,沒有,1有文件了。過時時間爲一天),而後數據就能夠不用擔憂判斷不出來 ,是否已經後臺生成了。 這個時候定時腳本沒3分鐘執行一次,避免多任務堆積,吃掉內存,服務掛機。使用 exec('ps -efH|grep "'.basename(FILE).'"', $output); if(count($output) > 3) { //相似守護進程,保證只運行1個此進程 print_r($output); exit; } 判斷當前是否已經執行過,須要等待上次執行後,此次才能執行。這個程序導出 23w ,數據大概是 1小時。業務不須要太準確數據,延時幾小時能夠接受。當鍵值24小時過時,那麼經過鍵值判斷是否已經生成問見我,新文件替換老文件html

而後下載文件java

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;
    }
相關文章
相關標籤/搜索