此例子只使用execel2003的.xls文檔,若使用的是其餘版本,能夠保存格式爲「Execel 97-2003 工做簿(*.xls)」即.xls文件類型便可!php
功能說明:只能上傳Excel2003類型的xls文件,大小不超過5M。可下載例子模板添加數據後便可上傳!html
前臺test.php頁面mysql
<!DOCTYPE html> <html> <head> <title></title> </head> <meta charset="utf-8"> <body> <form enctype="multipart/form-data" action="./Process.php" method="post"> <table> <tr><td align="center" colspan="2"><font style="font-size: 40px; font-family: 華文彩雲;" >上傳表格</font></td></tr> <tr><td>請先<a href="./sample/sample01.xls">下載excel例子模板</a>編輯後上傳文件</td></tr>
<tr> <td>請選擇你要上傳的文件</td> <td><input type="file" name="myfile"></td> </tr> <tr><td><input type="submit" value="上傳文件" /></td></tr> </table> </form> </body> </html>
運行結果:sql
後臺Process.php頁面數據庫
<?php header("Content-type:text/html;charset=utf-8"); //連接數據庫 $link = @mysql_connect('localhost','root','') or die('鏈接數據庫失敗'); mysql_select_db('test',$link); mysql_query('set names utf8'); function upExecel(){ //判斷是否選擇了要上傳的表格 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_type = $_FILES['myfile']['type']; //application/vnd.ms-excel 爲xls文件類型 if ($file_type!='application/vnd.ms-excel') { echo "<script>alert('上傳失敗,只能上傳excel2003的xls格式!');history.go(-1)</script>"; exit(); } //判斷表格是否上傳成功 if (is_uploaded_file($_FILES['myfile']['tmp_name'])) { require_once 'PHPExcel.php'; require_once 'PHPExcel/IOFactory.php'; require_once 'PHPExcel/Reader/Excel5.php'; //以上三步加載phpExcel的類 $objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format //接收存在緩存中的excel表格 $filename = $_FILES['myfile']['tmp_name']; $objPHPExcel = $objReader->load($filename); //$filename能夠是上傳的表格,或者是指定的表格 $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); // 取得總行數 // $highestColumn = $sheet->getHighestColumn(); // 取得總列數 //循環讀取excel表格,讀取一條,插入一條 //j表示從哪一行開始讀取 從第二行開始讀取,由於第一行是標題不保存 //$a表示列號 for($j=2;$j<=$highestRow;$j++) { $a = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();//獲取A(業主名字)列的值 $b = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//獲取B(密碼)列的值 $c = $objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();//獲取C(手機號)列的值 $d = $objPHPExcel->getActiveSheet()->getCell("D".$j)->getValue();//獲取D(地址)列的值 //null 爲主鍵id,自增可用null表示自動添加 $sql = "INSERT INTO house VALUES(null,'$a','$b','$c','$d')"; // echo "$sql"; // exit(); $res = mysql_query($sql); if ($res) { echo "<script>alert('添加成功!');window.location.href='./test.php';</script>"; }else{ echo "<script>alert('添加失敗!');window.location.href='./test.php';</script>"; exit(); } } } } //調用 upExecel(); ?>
效果爲:若未選擇要上傳的文件,會提示「未選擇表格」;若表格文件超過5M,提示;若上傳的文件類型不是xls,會提示!緩存
使用PHPExcel批量導入到數據庫至此完畢,對於使用PHPExcel導出數據能夠參看使用PHPExcel實現數據批量導出爲excel表格app