標籤:
1.串連資料庫的connection.php檔案
<?php//修改下面代碼來聯結資料庫// mysql_connect開啟一個到 MySQL 伺服器的串連,如果成功則返回一個 MySQL 串連標識,失敗則返回 FALSE。$mysql=mysql_connect("localhost","root","root"); //integer mysql_connect(主機,使用者名稱,口令);mysql_select_db("test",$mysql); //boolean mysql_select_db(資料庫名,串連號);mysql_query("set names GBK"); //這就是指定資料庫字元集,一般放在串連資料庫後面就系了?>
2.頁面調用
<?phprequire("connection.php"); require("UpLoad_Excel.php"); if($leadExcel == "true"){ //擷取上傳的檔案名稱 $filename = $HTTP_POST_FILES[‘inputExcel‘][‘name‘]; //上傳到伺服器上的臨時檔案名稱 $tmp_name = $_FILES[‘inputExcel‘][‘tmp_name‘]; $msg = uploadFile($filename,$tmp_name);}?><form method="post" enctype="multipart/form-data"> <input type="hidden" name="leadExcel" value="true"> <table align="center" width="90%" border="0"> <tr> <td> <input type="file" name="inputExcel"><input type="submit" value="匯入資料"> </td> </tr> </table></form>
3.匯入的UpLoad_Excel.php檔案
<?php
require("connection.php");//匯入Excel檔案function uploadFile($file,$filetempname){ //自己設定的上傳檔案存放路徑 $filePath = ‘upFile/‘; $str = ""; //下面的路徑按照你PHPExcel的路徑來修改 set_include_path(‘.‘. PATH_SEPARATOR . ‘D:\xampp\htdocs\XM1\PHPExcel‘ . PATH_SEPARATOR .get_include_path()); require_once ‘PHPExcel.php‘; require_once ‘PHPExcel\IOFactory.php‘; require_once ‘PHPExcel\Reader\Excel5.php‘; $filename=explode(".",$file);//把上傳的檔案名稱以“.”好為準做一個數組。 $time=date("y-m-d-H-i-s");//去當前上傳的時間 $filename[0]=$time;//取檔案名稱t替換 $name=implode(".",$filename); //上傳後的檔案名稱 $uploadfile=$filePath.$name;//上傳後的檔案名稱地址 //move_uploaded_file() 函數將上傳的檔案移動到新位置。若成功,則返回 true,否則返回 false。 $result=move_uploaded_file($filetempname,$uploadfile);//假如上傳到目前的目錄下 if($result) //如果上傳檔案成功,就執行匯入excel操作 { $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=2;$j<=$highestRow;$j++) { for($k=‘A‘;$k<=$highestColumn;$k++) { $str .= iconv(‘utf-8‘,‘gbk‘,$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue()).‘\\‘;//讀取儲存格 } //explode:函數把字串分割為數組。 $strs = explode("\\",$str); $sql = "INSERT INTO tab_zgjx_award (jx_name,jx_degree,jx_item_name,jx_unit,dy_originator,de_originator,xm_intro,hj_item_id) VALUES(‘". $strs[0]."‘,‘". //獎項名稱 $strs[1]."‘,‘". //獎項屆次 $strs[2]."‘,‘". //獲獎項目名 $strs[3]."‘,‘". //獲獎單位 $strs[4]."‘,‘". //第一發明人 $strs[5]."‘,‘". //第二發明人 $strs[6]."‘,‘". //項目簡介 $strs[7]."‘)"; //獲獎項目編號 mysql_query("set names GBK");//這就是指定資料庫字元集,一般放在串連資料庫後面就系了 if(!mysql_query($sql)) { return false; } $str = ""; } unlink($uploadfile); //刪除上傳的excel檔案 $msg = "匯入成功!"; } else { $msg = "匯入失敗!"; }return $msg;}?>
使用PHPExcel匯入Excel到MySql