phpexcel資料匯入資料庫
阿新 • • 發佈:2018-11-27
這裡分2中情況:
1.字尾為xls和xlsx
2.字尾為csv
注意:字尾為csv的一次可以匯入上萬條資料,字尾為xls和xlsx的能導幾千條,csv是一個黑科技
字尾為csv的情況:
1.獲取上傳的檔名$_FILES['file']['name']
2.上傳的零時檔案$_FILES['file']['tmp_name']
3.獲取檔案的字尾名:主要用到的:explode
4.設定上傳路徑$savePath 和 給檔案建立的新的檔名(一般以時間來命名)
5.複製檔案到專案中:用到:copy($tmp_file,新的路徑.新的檔名)
6.讀取儲存的檔案:file_get_contents(新的路徑.新的檔名);
7.進行資料的替換
8.插入資料庫
9.刪除上傳的檔案
具體程式碼如下
字尾為xls和xlsx(excel)
1.需要匯入phpexcel類
import("Org.Util.PHPExcel");
$objPHPExcel = new \PHPExcel();
import("Org.Util.PHPExcel.IOFactory");
import("Org.Util.PHPExcel.Cell");
2.關於phpexcel的學習這裡就不介紹了(可以自己查文件)
3.具體程式碼如下
程式碼如下:
public function order_import() { header('content-type:text/html;charset=utf-8'); // if(!empty($this->now_id)){ set_time_limit(0); if (!empty ($_FILES ['file'] ['name'])) { //上傳的檔名 $old_name = $_FILES['file'] ['name']; //上傳的零時檔案 $tmp_file = $_FILES ['file'] ['tmp_name']; //以.將檔名分割成陣列 $file_types = explode(".", $old_name); //獲取檔名的字尾 $file_type = $file_types [count($file_types) - 1]; //string(3) "xls" /*判別是不是.xls檔案,判別是不是excel檔案*/ if (strtolower($file_type) != "xls" && strtolower($file_type) != "xlsx") { if (strtolower($file_type) != "csv") { $this->ajaxReturn(array('code' => '100003', 'result' => '上傳型別錯誤')); } /*設定上傳路徑*/ $savePath = C('IMAGE_SAVE_PATH') . C('XLS_DIR'); /*以時間來命名上傳的檔案*/ $str = date('Ymdhis'); $file_name = $str . "." . $file_type; //string(18) "20170526020302.xls" if (!copy($tmp_file, $savePath . $file_name)) { $this->ajaxReturn(array('code' => '100002', 'result' => '上傳失敗')); } // 讀取儲存的檔案 $show_data = file_get_contents($savePath . $file_name); $show_data = str_replace('"', '', $show_data); $wrap = array("\n\r", "\r", "\n"); $replace = '<br/>'; $newstr = str_replace($wrap, $replace, $show_data); $list = explode('<br/>', trim($newstr)); foreach ($list as $list_k => $list_v) { $test_kong = explode(',', $list_v); if ($test_kong[0] == '') { unset($list[$list_k]); } } $list = array_values($list); // 對檔案進行中文亂碼處理,以及插入資料庫 M()->startTrans(); try { foreach ($list as $show_data_k => $show_data_v) { if ($show_data_v) { $handle[] = explode(',', iconv('gbk', 'utf-8', $show_data_v)); $mark = $str . '-' . $this->now_id;//上傳標記 if ($show_data_k >= 1) { if ($handle[$show_data_k][17] == '') { $handle[$show_data_k][17] = date('1970-1-1 0:0:0', time()); } if ($handle[$show_data_k][18] == '') { $handle[$show_data_k][18] = date('1970-1-1 0:0:0', time()); } if ($handle[$show_data_k][51] == '') { $handle[$show_data_k][51] = date('1970-1-1 0:0:0', time()); } $shopName = $handle[$show_data_k][26]; $ordno = trim(trim($handle[$show_data_k][0], '='), '"'); if ($handle[$show_data_k][53] == '') { $handle[$show_data_k][53] = 'null'; } $param = [ 'order_no' => $ordno, 'customer_name' => $handle[$show_data_k][1], 'alipay_account' => $handle[$show_data_k][2], 'need_payprice' => $handle[$show_data_k][3], 'customer_postage' => $handle[$show_data_k][4], 'need_integral' => $handle[$show_data_k][5], 'total_price' => $handle[$show_data_k][6], 'get_integral' => $handle[$show_data_k][7], 'real_payprice' => $handle[$show_data_k][8], 'real_integral' => $handle[$show_data_k][9], 'order_status' => $handle[$show_data_k][10], 'coustomer_msg' => $handle[$show_data_k][11], 'shr_name' => $handle[$show_data_k][12], 'shr_address' => $handle[$show_data_k][13], 'deliver_method' => $handle[$show_data_k][14], 'shr_tele' => $handle[$show_data_k][15], 'shr_phone' => $handle[$show_data_k][16], 'created_at' => $handle[$show_data_k][17], 'pay_at' => $handle[$show_data_k][18], 'goods_title' => $handle[$show_data_k][19], 'goods_type' => $handle[$show_data_k][20], 'express_no' => $handle[$show_data_k][21], 'comtype' => $handle[$show_data_k][22], 'order_note' => $handle[$show_data_k][23], 'goods_num' => $handle[$show_data_k][24], 'shop_id' => $handle[$show_data_k][25], 'shop_name' => $handle[$show_data_k][26], 'close_reason' => $handle[$show_data_k][27], 'seller_serfee' => $handle[$show_data_k][28], 'buyer_serfee' => $handle[$show_data_k][29], 'invoice_header' => $handle[$show_data_k][30], 'is_phoneorder' => $handle[$show_data_k][31], 'stage_info' => $handle[$show_data_k][32], 'privilege_orderid' => $handle[$show_data_k][33], 'contract_img' => $handle[$show_data_k][34], 'receipts_img' => $handle[$show_data_k][35], 'is_otherpay' => $handle[$show_data_k][36], 'deposit_rank' => $handle[$show_data_k][37], 'edited_sku' => $handle[$show_data_k][38], 'edited_address' => $handle[$show_data_k][39], 'error_msg' => $handle[$show_data_k][40], 'Tmall_coupon' => $handle[$show_data_k][41], 'jfb_coupon' => $handle[$show_data_k][42], 'is_o2o' => $handle[$show_data_k][43], 'retail_type' => $handle[$show_data_k][44], 'retail_shop' => $handle[$show_data_k][45], 'retail_shop_id' => $handle[$show_data_k][46], 'retail_sent' => $handle[$show_data_k][47], 'retail_sent_id' => $handle[$show_data_k][48], 'refund_amount' => $handle[$show_data_k][49], 'appointment_store' => $handle[$show_data_k][50], 'confirm_getgoods' => $handle[$show_data_k][51], 'pay_seller' => $handle[$show_data_k][52], 'individual_red' => $handle[$show_data_k][53], 'upload_mark' => $mark ]; $result = D('order')->add($param); // if (empty($result)) { // @M('order')->where(array('upload_mark' => $mark))->delete(); // } } } } M()->commit(); } catch (\Exception $e) { M()->rollback(); $this->ajaxReturn(array('result' => '100003', 'result' => '上傳失敗!')); } @unlink($savePath . $file_name); $order_nums = count($list); if ($result) { M('upload_record')->add($rec = [ 'upload_mark' => $mark, 'action_user' => $this->now_id, 'upload_at' => time(), 'order_num' => $order_nums, 'shop_name' => $shopName, 'file_name' => $old_name, ]); $rec['upload_at'] = date('Y-m-d H:i:s', $rec['upload_at']); $rec['active'] = $this->now_id == $rec['action_user'] ? 1 : 0; $rec['username'] = M('admin')->where(array('id' => $this->now_id))->getField('username'); $this->ajaxReturn(array('code' => '100000', 'result' => '上傳成功!', 'add_record' => $rec)); } else { $this->ajaxReturn(array('code' => '100003', 'result' => '上傳失敗!')); } $this->ajaxReturn(array('code' => '100000', 'result' => '上傳成功!', 'add_record' => $rec)); } /*是xls和xlsx*/ /*設定上傳路徑*/ $savePath = C('IMAGE_SAVE_PATH') . C('XLS_DIR'); //dump($savePath);die; /*以時間來命名上傳的檔案*/ $str = date('Ymdhis'); $file_name = $str . "." . $file_type; //string(18) "20170526020302.xls" if (!copy($tmp_file, $savePath . $file_name)) { $this->ajaxReturn(array('code' => '100002', 'result' => '上傳失敗')); } // var_dump('ssssss');die; /* *對上傳的Excel資料進行處理生成程式設計資料,這個函式會在下面第三步的ExcelToArray類中 *注意:這裡呼叫執行了第三步類裡面的read函式,把Excel轉化為陣列並返回給$res,再進行資料庫寫入 */ // $res = Service ( 'ExcelToArray' )->read ( $savePath . $file_name ); import("Org.Util.PHPExcel"); $objPHPExcel = new \PHPExcel(); import("Org.Util.PHPExcel.IOFactory"); import("Org.Util.PHPExcel.Cell"); //讀取檔案 if (strtolower($file_type) == "xlsx") { $objReader = \PHPExcel_IOFactory::createReader('Excel2007'); } else { $objReader = \PHPExcel_IOFactory::createReader('Excel5'); } $objReader->setReadDataOnly(true); $objPHPExcel = $objReader->load($savePath . $file_name); //得到當前活動的表 $objWorksheet = $objPHPExcel->getActiveSheet(); $highestRow = $objWorksheet->getHighestRow(); $highestColumn = $objWorksheet->getHighestColumn(); $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn); $excelData = array(); for ($row = 2; $row <= $highestRow; $row++) { for ($col = 0; $col < $highestColumnIndex; $col++) { if ($col == 17 || $col == 18 || $col == 51) {//指定列為時間格式還原所在列 $excelData[$row][] = gmdate("Y-m-d H:i:s", \PHPExcel_Shared_Date::ExcelToPHP((string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue())); } else { $excelData[$row][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue(); } } } //剔除空的 foreach ($excelData as $excelData_k => $excelData_v) { if ($excelData_v[0] == '') { unset($excelData[$excelData_k]); } } // dump($excelData);die; $excelData = array_values($excelData); $mark = $str . '-69';//上傳標記 M()->startTrans(); try { foreach ($excelData as $k => $v) { $shopName = $v[26]; $ordno = trim(trim($v[0], '='), '"'); if ($v[53] == '') { $v[53] = 'null'; } $param = [ 'order_no' => $ordno, 'customer_name' => $v[1], 'alipay_account' => $v[2], 'need_payprice' => $v[3], 'customer_postage' => $v[4], 'need_integral' => $v[5], 'total_price' => $v[6], 'get_integral' => $v[7], 'real_payprice' => $v[8], 'real_integral' => $v[9], 'order_status' => $v[10], 'coustomer_msg' => $v[11], 'shr_name' => $v[12], 'shr_address' => $v[13], 'deliver_method' => $v[14], 'shr_tele' => $v[15], 'shr_phone' => $v[16], 'created_at' => $v[17], 'pay_at' => $v[18], 'goods_title' => $v[19], 'goods_type' => $v[20], 'express_no' => $v[21], 'comtype' => $v[22], 'order_note' => $v[23], 'goods_num' => $v[24], 'shop_id' => $v[25], 'shop_name' => $v[26], 'close_reason' => $v[27], 'seller_serfee' => $v[28], 'buyer_serfee' => $v[29], 'invoice_header' => $v[30], 'is_phoneorder' => $v[31], 'stage_info' => $v[32], 'privilege_orderid' => $v[33], 'contract_img' => $v[34], 'receipts_img' => $v[35], 'is_otherpay' => $v[36], 'deposit_rank' => $v[37], 'edited_sku' => $v[38], 'edited_address' => $v[39], 'error_msg' => $v[40], 'Tmall_coupon' => $v[41], 'jfb_coupon' => $v[42], 'is_o2o' => $v[43], 'retail_type' => $v[44], 'retail_shop' => $v[45], 'retail_shop_id' => $v[46], 'retail_sent' => $v[47], 'retail_sent_id' => $v[48], 'refund_amount' => $v[49], 'appointment_store' => $v[50], 'confirm_getgoods' => $v[51], 'pay_seller' => $v[52], 'individual_red' => $v[53], 'upload_mark' => $mark ]; $result = D('order')->add($param); if (empty($result)) { @M('order')->where(array('upload_mark' => $mark))->delete(); } } M()->commit(); } catch (\Exception $e) { M()->rollback(); $this->ajaxReturn(array('result' => '100003', 'result' => '上傳失敗!')); } @unlink($savePath . $file_name); $order_num = count($excelData); if ($result) { M('upload_record')->add($rec = [ 'upload_mark' => $mark, 'action_user' => $this->now_id, 'upload_at' => time(), 'order_num' => $order_num, 'shop_name' => $shopName, 'file_name' => $old_name, ]); $rec['upload_at'] = date('Y-m-d H:i:s', $rec['upload_at']); $rec['active'] = $this->now_id == $rec['action_user'] ? 1 : 0; $rec['username'] = M('admin')->where(array('id' => $this->now_id))->getField('username'); $this->ajaxReturn(array('code' => '100000', 'result' => '上傳成功!', 'add_record' => $rec)); } else { $this->ajaxReturn(array('code' => '100003', 'result' => '上傳失敗!')); } } else { //列表展示頁面 $page = I('page', 1); $pagesize = 7; $totalPage = M('upload_record')->count('id'); $record = M('upload_record ur')->join('LEFT JOIN __ADMIN__ a ON a.id=ur.action_user') ->order('upload_at desc') ->field('ur.*,a.username') ->limit(($page - 1) * $pagesize, $pagesize)->select(); foreach ($record as $key => $val) { $record[$key]['upload_at'] = date('Y-m-d H:i:s', $val['upload_at']);//上傳時間格式化 $record[$key]['active'] = $this->now_id == $val['action_user'] ? 1 : 0; //判斷是否可操作 } $this->ajaxReturn(array('code' => '100000', 'record' => $record ? $record : [], 'pagesize' => $pagesize, 'total' => (int)$totalPage)); } // }else{ // $this->ajaxReturn(array('code' => '100004', 'result' => '請重新登入')); // } }