日期:2014-05-16  浏览次数:20475 次

PHP 如何把excel表中的数据插入数据库
最近因为开发的需要,要把大量的数据导入到数据库中做一个软件使用前真实数据的测试,就用到了要把excel中的数据导入数据库中。
下面咱就直接入题:
我是在Thinkphp下开发的,需要用到第三方类我已经以附件的形式传上来了。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>上传</title>
<form method="POST" name="form" enctype="multipart/form-data">
	<input name="uploadfile" type="file" id="uploadfile"/>
	<input name="submit" type="submit" class="inputButton"  value="批量上传"/>(通过excel上传)
</form>
</body>
</html>
<?PHP
$dir = dirname(_FILE_);//获得编译文件当前目录
$dir = str_replace("\\", "/", $dir)."/";
$filename = 'uploadfile.xls';
$path = $dir.$filename;
$result = move_uploaded_file($_FILES['uploadfile']['tmp_name'], $path);
if ($result){
Vendor('Excel.reader');//调用第三方类,可以是require_once('指向reader.php文件所在的路径')
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('utf-8');
$data->read($path);
error_reporting(E_ALL ^ E_NOTICE);
for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
	$arr = array();
	for ($j = 2; $j <= $data->sheets[0]['numCols']; $j++) {
		$arr[] = $data->sheets[0]['cells'][$i][$j];
	}
	mysql_query("set names 'utf-8'");
	$Upload = D("Upload");
	$Upload>query("insert into ts_upload (userid,useremail,status,description,postdate) 
			            values ('".$arr[0]."','".$arr[1]."','".$arr[2]."','".$arr[3]."','".$arr[4]."')");
}
       unlink($path);
       $this->success("上传成功!");
}else{
	$this->error("上传失败!");
}

编码已完成!
在没有导入公司的大量的数据前我自己做了个excel,里面 手动 插入了些简单的数据,测试时没有问题。数据库里是可以插入数据的。可是我再插入公司的提供的excel文件的时候,问题出现了就是  $data->sheets[] 这个数据是空的,当是我以为是调用文件里有什么限制。把原来的内容拷贝一部分到其他的excel文件中再插入还是不行。这个问题搞了很久都没有搞出什么原因来。后来我把原来excel的内容全部拷贝到txt文档中,然后再把txt文档中的内容全部拷贝到一个新的excel文件中。把新的excel导入,上传成功!  后来发现是公司提供的excel中表格添加了很多属性,导致数据读取不出来。
以上信息希望能给大家带来一些方便,同时也是自己在工作中的一个记录!~~~