下面小编就为大家带来一篇php使用phpexcel实现批量上传到数据库的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
此例子只使用execel2003的.xls文档,若使用的是其他版本,可以保存格式为“execel 97-2003 工作簿(*.xls)”即.xls文件类型即可!
功能说明:只能上传excel2003类型的xls文件,大小不超过5m。可下载例子模板添加数据后即可上传!
前台test.php页面
<!doctype html>
<html>
<head>
<title></title>
</head>
<meta charset="utf-8">
<body>
<form enctype="multipart/form-data" action="./process.php" method="post">
<table>
<tr><td align="center" colspan="2"><font style="font-size: 40px; font-family: 华文彩云;" >上传表格</font></td></tr>
<tr><td>请先<a href="./sample/sample01.xls" rel="external nofollow" >下载excel例子模板</a>编辑后上传文件</td></tr>
<tr>
<td>请选择你要上传的文件</td>
<td><input type="file" name="myfile"></td>
</tr>
<tr><td><input type="submit" value="上传文件" /></td></tr>
</table>
</form>
</body>
</html>
运行结果:
后台process.php页面
<?php
header("content-type:text/html;charset=utf-8");
//链接数据库
$link = @mysql_connect('localhost','root','') or die('连接数据库失败');
mysql_select_db('test',$link);
mysql_query('set names utf8');
function upexecel(){
//判断是否选择了要上传的表格
if (empty($_post['myfile'])) {
echo "<script>alert(您未选择表格);history.go(-1);</script>";
}
//获取表格的大小,限制上传表格的大小5m
$file_size = $_files['myfile']['size'];
if ($file_size>5*1024*1024) {
echo "<script>alert('上传失败,上传的表格不能超过5m的大小');history.go(-1);</script>";
exit();
}
//限制上传表格类型
$file_type = $_files['myfile']['type'];
//application/vnd.ms-excel 为xls文件类型
if ($file_type!='application/vnd.ms-excel') {
echo "<script>alert('上传失败,只能上传excel2003的xls格式!');history.go(-1)</script>";
exit();
}
//判断表格是否上传成功
if (is_uploaded_file($_files['myfile']['tmp_name'])) {
require_once 'phpexcel.php';
require_once 'phpexcel/iofactory.php';
require_once 'phpexcel/reader/excel5.php';
//以上三步加载phpexcel的类
$objreader = phpexcel_iofactory::createreader('excel5');//use excel2007 for 2007 format
//接收存在缓存中的excel表格
$filename = $_files['myfile']['tmp_name'];
$objphpexcel = $objreader->load($filename); //$filename可以是上传的表格,或者是指定的表格
$sheet = $objphpexcel->getsheet(0);
$highestrow = $sheet->gethighestrow(); // 取得总行数
// $highestcolumn = $sheet->gethighestcolumn(); // 取得总列数
//循环读取excel表格,读取一条,插入一条
//j表示从哪一行开始读取 从第二行开始读取,因为第一行是标题不保存
//$a表示列号
for($j=2;$j<=$highestrow;$j++)
{
$a = $objphpexcel->getactivesheet()->getcell("a".$j)->getvalue();//获取a(业主名字)列的值
$b = $objphpexcel->getactivesheet()->getcell("b".$j)->getvalue();//获取b(密码)列的值
$c = $objphpexcel->getactivesheet()->getcell("c".$j)->getvalue();//获取c(手机号)列的值
$d = $objphpexcel->getactivesheet()->getcell("d".$j)->getvalue();//获取d(地址)列的值
//null 为主键id,自增可用null表示自动添加
$sql = "insert into house values(null,'$a','$b','$c','$d')";
// echo "$sql";
// exit();
$res = mysql_query($sql);
if ($res) {
echo "<script>alert('添加成功!');window.location.href='./test.php';</script>";
}else{
echo "<script>alert('添加失败!');window.location.href='./test.php';</script>";
exit();
}
}
}
}
//调用
upexecel();
?>
效果为:若未选择要上传的文件,会提示“未选择表格”;若表格文件超过5m,提示;若上传的文件类型不是xls,会提示!
相关推荐:
php实现批量上传数据到数据库的方法
thinkphp5框架整合plupload实现图片批量上传
thinkphp5+phpexcel实现批量上传表格数据功能
以上就是php使用phpexcel实现批量上传到数据库的详细内容。