這篇文章介紹的內容是關於PHP寫了個批量Excel匯入發貨,記錄下,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
function upExecel(){ include 'data/extend/phpexcel_classes/PHPExcel.php'; //判斷是否選擇了要上傳的表格 if (empty($_POST['myfile'])) { echo "<script>alert(您未選擇表格);history.go(-1);</script>"; } //擷取表格的大小,限制上傳表格的大小5M $file_size = $_FILES['myfile']['size']; if ($file_size>5*1024*1024) { echo "<script>alert('上傳失敗,上傳的表格不能超過5M的大小');history.go(-1);</script>"; exit(); } //限制上傳表格類型 $file_name = $_FILES['myfile']['name']; //application/vnd.ms-excel 為xls檔案類型 $extension = strtolower( pathinfo($file_name, PATHINFO_EXTENSION) ); //判斷表格是否上傳成功 if (is_uploaded_file($_FILES['myfile']['tmp_name'])) { //接收存在緩衝中的excel表格 $filename = $_FILES['myfile']['tmp_name']; if ($extension =='xlsx') { $objReader = \PHPExcel_IOFactory::createReader('Excel2007');//use excel2007 for 2007 format $objPHPExcel = $objReader ->load($filename); } else if ($extension =='xls') { $objReader = \PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format $objPHPExcel = $objReader ->load($filename); } //$objPHPExcel = $objReader->load($filename); //$filename可以是上傳的表格,或者是指定的表格 $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); // 取得總行數 // $highestColumn = $sheet->getHighestColumn(); // 取得總列數 //迴圈讀取excel表格,讀取一條,插入一條 //j表示從哪一行開始讀取 從第二行開始讀取,因為第一行是標題不儲存 /*if ($shipping_type == 1) { $res = $order_service->orderDelivery($order_id, $order_goods_id_array, $express_name, $shipping_type, $express_company_id, $express_no,$suppliercode);*/ $order_service = new OrderService(); $express = new NsOrderExpressCompanyModel(); $num = 0; for($j=2;$j<=$highestRow;$j++) { $a = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();//order_id $b = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//order_goods_id $c = $objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();//express_name $d = $objPHPExcel->getActiveSheet()->getCell("D".$j)->getValue();//express_no $express_id = $express->where('company_name',$c)->value('co_id'); if(!$express_id || !is_numeric($d)){ echo "<script>alert('第".$j."行快遞公司名稱或單號不正確');window.location.href='/admin/spell/countspellgroup';</script>"; break; } $res = $order_service->orderDelivery($a, $b, $c, 1, $express_id,$d,''); // exit(); Db::execute("insert into ns_wxmsg_spellgroup(orderid,msgtype,addtime,senttime,status) (select order_id,'10',".time().",0,'' from ns_spellgroup where pay_time>0 and order_id=".$a.")"); $num++; } if ($num) { echo "<script>alert($num.'行資料添加成功!');window.location.href='/admin/spell/countspellgroup';</script>"; } } }
剛開始寫PHP,有很多不足的地方,請多多指正,本來想寫個事務,暫時沒弄好,就這樣先用了,後續在最佳化