A5下载 - 努力做内容最丰富最安全的下载站!

A5站长下载站

当前位置:A5下载 > 源码技巧 > 其它源码教程 > PHP导入Excel到MySQL的方法

PHP导入Excel到MySQL的方法

时间:2015-04-02 09:13作者:zhao人气:264

研究了一下~方法不少~最后决定用Excel导入~在网上搜了很多这方面的资料,发现都是将excel文件另存为csv文件,然后从csv文件导入。这里介绍一个直接将excel文件导入mysql的例子。我花了一晚上的时间测试,无论导入简繁体都不会出现乱码,非常好用。

header("Content-type: text/html; charset=utf-8");

require_once 'reader.php'; // ExcelFile($filename, $encoding); $data = new Spreadsheet_Excel_Reader(); // Set output Encoding. $data->setOutputEncoding('gbk');

//”data.xls”是指要导入到mysql中的excel文件

$data=new Spreadsheet_Excel_Reader;

$data->read('data.xls');

@$db = mysql_connect('localhost', 'root', '123456') or

die("Could not connect to database.");//连接数据库

mysql_query("set names 'utf8'");//输出中文

mysql_select_db('ddd'); //选择数据库

error_reporting(E_ALL ^ E_NOTICE);

for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {

//以下注释的for循环打印excel表数据

$result="select * from aaa where user_name=".$data->sheets[0]['cells'][$i][1];

$row = mysql_query($result);

if(!$row){

//以下代码是将excel表数据【3个字段】插入到mysql中, 根据你的excel表字段的多少,改写以下代码吧!

$sql = "INSERT INTO aaa (wid, email, user_name, password,mobile_phone) VALUES('".

$data->sheets[0]['cells'][$i][1]."','".

$data->sheets[0]['cells'][$i][2]."','".

$data->sheets[0]['cells'][$i][3]."','".

$data->sheets[0]['cells'][$i][4]."')";

$res = mysql_query($sql);

echo $i." 插入成功 ".$data->sheets[0]['cells'][$i][1]."

";

}

else{

echo $i." 已经存在 失败 ".$data->sheets[0]['cells'][$i][1]."

";

}

}

?>

文件下载地址:______Excl.rar

标签PHP,导入,Excel,MySQL,方法,研究,一下,方法

相关下载

查看所有评论+

网友评论

网友
您的评论需要经过审核才能显示

公众号