將excel資料匯入到mysql資料庫
阿新 • • 發佈:2018-10-31
框架用的是thinkphp3.2框架 //將Excel匯入到資料庫的思想是:先將Excel中的資料轉為php陣列,然後執行addAll操作 public function upload() { ini_set('memory_limit', '1024M'); if (!empty($_FILES)) { $config = array( 'exts' => array('xlsx', 'xls'), 'maxSize' => 3145728000, 'rootPath' => "./Public/", 'savePath' => 'Uploads/', 'subName' => array('date', 'Ymd'), ); $upload = new \Think\Upload($config); if (!$info = $upload->upload()) { $this->error($upload->getError()); } vendor("PHPExcel.PHPExcel"); $file_name = $upload->rootPath . $info['photo']['savepath'] . $info['photo']['savename']; $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));//判斷匯入表格字尾格式 if ($extension == 'xlsx') { $objReader = \PHPExcel_IOFactory::createReader('Excel2007'); $objPHPExcel = $objReader->load($file_name, $encode = 'utf-8'); } else if ($extension == 'xls') { $objReader = \PHPExcel_IOFactory::createReader('Excel5'); $objPHPExcel = $objReader->load($file_name, $encode = 'utf-8'); } $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow();//取得總行數 $highestColumn = $sheet->getHighestColumn(); //取得總列數 //如果資料量比較大的話,每次插入100行,迴圈插入 $count = ceil($highestRow / 100); if ($count >= 2) {//如果$count>=2,表示至少進行兩次整體迴圈(100條以上資料) for ($j = 1; $j <= $count; $j++) {//迴圈插入資料表 for ($i = 2 + ($j - 1) * 100; $i <= 101 * $j; $i++) { //2---101,102---202,202--303,302--404,402--505,502--606重複 //看這裡看這裡,前面小寫的a是表中的欄位名,後面的大寫A是excel中位置 //$i-2,是的陣列的索引從0開始 $data[($i - 2) - ($j - 1) * 100]['pId'] = $objPHPExcel->getActiveSheet()->getCell("A" . $i)->getValue(); $data[($i - 2) - ($j - 1) * 100]['pName'] = $objPHPExcel->getActiveSheet()->getCell("B" . $i)->getValue(); $data[($i - 2) - ($j - 1) * 100]['pPrice'] = $objPHPExcel->getActiveSheet()->getCell("C" . $i)->getValue(); $data[($i - 2) - ($j - 1) * 100]['pCount'] = $objPHPExcel->getActiveSheet()->getCell("D" . $i)->getValue(); } //刪除重複的資料 if ($j >= 3) { for ($x = 3; $x <= $j; $x++) {//從第三波迴圈開始刪除操作,刪除重複的1個,第四波迴圈刪除重複的2個,第五波迴圈刪除3個... unset($data[$x - 3]); } $data = array_values($data);//重新建立索引 } D('pro_info')->addAll($data); } } else {//少於100條記錄的時候,只addAll一次 for ($i = 2; $i <= $highestRow; $i++) { //看這裡看這裡,前面小寫的a是表中的欄位名,後面的大寫A是excel中位置 //$i-2,是的陣列的索引從0開始 $data[$i - 2]['pId'] = $objPHPExcel->getActiveSheet()->getCell("A" . $i)->getValue(); $data[$i - 2]['pName'] = $objPHPExcel->getActiveSheet()->getCell("B" . $i)->getValue(); $data[$i - 2]['pPrice'] = $objPHPExcel->getActiveSheet()->getCell("C" . $i)->getValue(); $data[$i - 2]['pCount'] = $objPHPExcel->getActiveSheet()->getCell("D" . $i)->getValue(); } D('pro_info')->addAll($data); } $this->success('匯入成功!'); } else { $this->error("請選擇上傳的檔案"); } }