在网上找了excel读取的一些资料,个人觉得PHPExcel这还是挺好用的,相对比较全的工具。
主要功能是读取上传的excel文件,插入或更新到数据库。
iconv("gbk","utf8",$_FILES["file"]["tmp_name"]),mysql_query("SET NAMES 'utf8'"),编码转换防止中文在数据库中显示乱码;
以下是主要的源代码:
header("Content-type:text/html;charset=utf-8");
require_once('PHPExcel/Classes/PHPExcel.php');
require_once('PHPExcel/Classes/PHPExcel/IOFactory.php'); iconv("gbk","utf8",$_FILES["file"]["tmp_name"]);//编码转换 $fileType=PHPExcel_IOFactory::identify($_FILES["file"]["tmp_name"]);//判断文件的类型
$objReader=PHPExcel_IOFactory::createReader($fileType);//创建对象
$objPHPExcel=$objReader->load($_FILES['file']['tmp_name']);//导入数据 $currentSheet = $objPHPExcel->getSheet(0); //第一个工作簿
$allRow = $currentSheet->getHighestRow(); //行数
$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'); $con=mysql_connect('localhost','root','root')
or die('数据库链接失败!<br />'.mysql_error()); $db=mysql_select_db('db_product',$con);
mysql_query("SET NAMES 'utf8'");
for($currentRow = 3;$currentRow<=$allRow;$currentRow++){
$rowValues='';
$id=(string)($currentSheet->getCell('C'.$currentRow)->getValue()); $select_id=mysql_query("SELECT * FROM t_shop WHERE productNum='$id'");
$result=mysql_fetch_array($select_id); if(!$result){//判断是否存在
foreach ($letters_arr as $key => $value) {
$xh=$currentSheet->getCell($value.$currentRow)->getValue();
if($key>14)break;
$rowValues=$rowValues.($key>1?',':'').'\''.$xh.'\''; } $sql="INSERT INTO t_shop (shopName,brand,productNum,spec,barCode,category,productName,orderNumber,deliveryNumber,returnNumber,returnBackNumber,salesPrice,costPrice,profit) VALUES (".$rowValues.")";
mysql_query($sql);
}
else{ $reValues=re_row($result,$letters_arr,$currentSheet,$currentRow);
$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'";
mysql_query($sql);
echo mysql_error().$id.'###';
print_r($reValues);
echo '<br />';
} } mysql_close($con); function re_row($s,$a,$obj,$currentRow){
$b=$d='';
foreach ($a as $key => $value) {
$xh=$obj->getCell($value.$currentRow)->getValue();
if($key>14)break;
$d[]=$xh; } foreach ($d as $key => $value) {
if($key!=2 && $key<7){
$b[]= (string)$value;
}
elseif($key>6){
$b[]=$s[$key]+$value;
} }
return $b;
}