<? if($_POST['leadExcel'] == "true") { $filename = $_FILES['inputExcel']['name']; $tmp_name = $_FILES['inputExcel']['tmp_name']; $msg = uploadFile($filename,$tmp_name); echo $msg; } //匯入Excel檔案 function uploadFile($file,$filetempname) { //自己設定的上傳檔案存放路徑 $filePath = 'upFile/'; $str = ""; //下面的路徑按照你PHPExcel的路徑來修改 require_once '../PHPExcel/PHPExcel.php'; require_once '../PHPExcel/PHPExcel/IOFactory.php'; require_once '../PHPExcel/PHPExcel/Reader/Excel5.php'; //注意設定時區 $time=date("y-m-d-H-i-s");//去當前上傳的時間 //擷取上傳檔案的副檔名 $extend=strrchr ($file,'.'); //上傳後的檔案名稱 $name=$time.$extend; $uploadfile=$filePath.$name;//上傳後的檔案名稱地址 //move_uploaded_file() 函數將上傳的檔案移動到新位置。若成功,則返回 true,否則返回 false。 $result=move_uploaded_file($filetempname,$uploadfile);//假如上傳到目前的目錄下 //echo $result; if($result) //如果上傳檔案成功,就執行匯入excel操作 { include "conn.php"; $objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format $objPHPExcel = $objReader->load($uploadfile); $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); //取得總行數 $highestColumn = $sheet->getHighestColumn(); //取得總列數 /* 第一種方法 //迴圈讀取excel檔案,讀取一條,插入一條 for($j=1;$j<=$highestRow;$j++) //從第一行開始讀取資料 { for($k='A';$k<=$highestColumn;$k++) //從A列讀取資料 { // 這種方法簡單,但有不妥,以'\'合并為數組,再分割\為欄位值插入到資料庫 實測在excel中,如果某儲存格的值包含了\匯入的資料會為空白 // $str .=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().'\';//讀取儲存格 } //echo $str; die(); //explode:函數把字串分割為數組。 $strs = explode("\",$str); $sql = "INSERT INTO te(`1`, `2`, `3`, `4`, `5`) VALUES ( '{$strs[0]}', '{$strs[1]}', '{$strs[2]}', '{$strs[3]}', '{$strs[4]}')"; //die($sql); if(!mysql_query($sql)) { return false; echo 'sql語句有誤'; } $str = ""; } unlink($uploadfile); //刪除上傳的excel檔案 $msg = "匯入成功!"; */ /* 第二種方法*/ $objWorksheet = $objPHPExcel->getActiveSheet(); $highestRow = $objWorksheet->getHighestRow(); echo 'highestRow='.$highestRow; echo "<br>"; $highestColumn = $objWorksheet->getHighestColumn(); $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//總列數 echo 'highestColumnIndex='.$highestColumnIndex; echo "<br>"; $headtitle=array(); for ($row = 1;$row <= $highestRow;$row++) { $strs=array(); //注意highestColumnIndex的列數索引從0開始 for ($col = 0;$col < $highestColumnIndex;$col++) { $strs[$col] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue(); } $sql = "INSERT INTO te(`1`, `2`, `3`, `4`, `5`) VALUES ( '{$strs[0]}', '{$strs[1]}', '{$strs[2]}', '{$strs[3]}', '{$strs[4]}')"; //die($sql); if(!mysql_query($sql)) { return false; echo 'sql語句有誤'; } } } else { $msg = "匯入失敗!"; } return $msg; } ?> |