时间:2021-07-01 10:21:17 帮助过:2人阅读
$fname = $_FILES['MyFile']['tmp_name'];//获取上传的CSV文件 $handle=fopen("$fname","r");//打开文件 //判断导入文件类型是否为csv //如果为csv继续执行 if($_FILES['MyFile']['type'] !='application/vnd.ms-excel') { if($_FILES['MyFile']['type'] != 'text/comma-separated-values') { echo "";exit(); } } $num = 1; $total_num = 100;//设置每次添加的数据条数 //删除表中原有数据 $db->query("delete from hotel_activities_2"); //打开导入的csv //循环添加到表中 while(!feof($handle)) { $content = fgets($handle); $data = preg_split("/,/",$content); if($data[0] =='') { continue; } $subHotel_id = preg_replace('/[^0-9]/','',$data[0]); $subHotel_type= (int)preg_replace('/[^0-9]/','',$data[4]); if($num == $total_num ) { $num=1; $values .= " ($subHotel_id,'".$data[1]."','".$data[2]."','".$data[3]."',$subHotel_type),"; $values = rtrim($values,','); $sql ="insert into hotel_activities_2 (hotel_id,start_date,end_date,content,s_type) values " .$values; $aaa = $db->query($sql); $values =''; } else { $values .= " ($subHotel_id,'".$data[1]."','".$data[2]."','".$data[3]."',$subHotel_type),"; $num++; } } if(mysql_error!==1){ $values = rtrim($values,','); $sql ="insert into hotel_activities_2 (hotel_id,start_date,end_date,content,s_type) values " .$values; $db->query($sql); echo ""; }else { echo ""; } fclose($handle);
------解决方案--------------------
在 csv 格式标准中:字符串是需要用双引号括起的,但微软的工具软件却偏偏不加这个双引号
在 php5.3 以前的版本中,php 也认同这种做法
但自 php5.3 起,微软摆出了不合作姿态,于是 fgetcsv 也就残废了
------解决方案--------------------
读取excel数据要用到一个插件,直接这样读取肯定是不行的。
下面这个是将ecxcel数据读取到数据库的方法:
7.$handle = fopen (”test.csv”,”r”);
8.$sql=”insert into scores(idcard,names ,num,sex,nation,score) values(’”;
9.while ($data = fgetcsv ($handle, 1000, “,”)) {
10.$num = count ($data);
11.for ($c=0; $c < $num; $c++) {
12.if($c==$num-1){$sql=$sql.$data[$c].”‘)”;break;}
13.$sql=$sql.$data[$c].”‘,’”;
14.}
15.print “< br>”;
16.echo $sql.”< br>”;
17.$db->query($sql);
18.echo “SQL语句执行成功!< br>”;
19.$sql=”insert into scores(idcard,names ,num,sex,nation,score) values(’”;
20.}
21.fclose ($handle);
22.$time_end = getmicrotime();