在網上找了excel讀取的一些資料,我的以爲PHPExcel這仍是挺好用的,相對比較全的工具。php
主要功能是讀取上傳的excel文件,插入或更新到數據庫。html
iconv("gbk","utf8",$_FILES["file"]["tmp_name"]),mysql_query("SET NAMES 'utf8'"),編碼轉換防止中文在數據庫中顯示亂碼;mysql
如下是主要的源代碼:sql
1 header("Content-type:text/html;charset=utf-8"); 2 require_once('PHPExcel/Classes/PHPExcel.php'); 3 require_once('PHPExcel/Classes/PHPExcel/IOFactory.php'); 4 5 iconv("gbk","utf8",$_FILES["file"]["tmp_name"]);//編碼轉換 6 7 $fileType=PHPExcel_IOFactory::identify($_FILES["file"]["tmp_name"]);//判斷文件的類型 8 $objReader=PHPExcel_IOFactory::createReader($fileType);//建立對象 9 $objPHPExcel=$objReader->load($_FILES['file']['tmp_name']);//導入數據 10 11 $currentSheet = $objPHPExcel->getSheet(0); //第一個工做簿 12 $allRow = $currentSheet->getHighestRow(); //行數 13 $letters_arr = array(1=>'A',2=>'B',3=>'C',4=>'D',5=>'E',6=>'F',7=>'G',8=>'H',9=>'I',10=>'J',11=>'K',12=>'L',13=>'M', 14=>'N',15=>'O',16=>'P',17=>'Q',18=>'R',19=>'S',20=>'T',21=>'U',22=>'V',23=>'W',24=>'X',25=>'Y',26=>'Z'); 14 15 16 $con=mysql_connect('localhost','root','root') 17 or die('數據庫連接失敗!<br />'.mysql_error()); 18 19 $db=mysql_select_db('db_product',$con); 20 mysql_query("SET NAMES 'utf8'"); 21 for($currentRow = 3;$currentRow<=$allRow;$currentRow++){ 22 $rowValues=''; 23 $id=(string)($currentSheet->getCell('C'.$currentRow)->getValue()); 24 25 $select_id=mysql_query("SELECT * FROM t_shop WHERE productNum='$id'"); 26 $result=mysql_fetch_array($select_id); 27 28 29 if(!$result){//判斷是否存在 30 foreach ($letters_arr as $key => $value) { 31 $xh=$currentSheet->getCell($value.$currentRow)->getValue(); 32 if($key>14)break; 33 $rowValues=$rowValues.($key>1?',':'').'\''.$xh.'\''; 34 35 36 } 37 38 $sql="INSERT INTO t_shop (shopName,brand,productNum,spec,barCode,category,productName,orderNumber,deliveryNumber,returnNumber,returnBackNumber,salesPrice,costPrice,profit) VALUES (".$rowValues.")"; 39 mysql_query($sql); 40 } 41 else{ 42 43 $reValues=re_row($result,$letters_arr,$currentSheet,$currentRow); 44 $sql="UPDATE t_shop SET shopName='$reValues[0]',brand='$reValues[1]',spec='$reValues[2]',barCode='$reValues[3]',category='$reValues[4]',productName='$reValues[5]',orderNumber=$reValues[6],deliveryNumber=$reValues[7],returnNumber=$reValues[8],returnBackNumber=$reValues[9],salesPrice=$reValues[10],costPrice=$reValues[11],profit=$reValues[12] WHERE productNum='$id'"; 45 mysql_query($sql); 46 echo mysql_error().$id.'###'; 47 print_r($reValues); 48 echo '<br />'; 49 } 50 51 52 53 } 54 55 mysql_close($con); 56 57 function re_row($s,$a,$obj,$currentRow){ 58 $b=$d=''; 59 foreach ($a as $key => $value) { 60 $xh=$obj->getCell($value.$currentRow)->getValue(); 61 if($key>14)break; 62 $d[]=$xh; 63 64 65 } 66 67 foreach ($d as $key => $value) { 68 if($key!=2 && $key<7){ 69 $b[]= (string)$value; 70 } 71 elseif($key>6){ 72 $b[]=$s[$key]+$value; 73 } 74 75 76 } 77 return $b; 78 }