PHP批量导入excell表格到mysql数据库,本人通过亲自测试,在这里分享给大家
1,下载 php excell类库
网上搜索可以下载,这里不写地址
2,建html文件
<form method="post" action="http://www.96net.com.cn/index.php?c=good&a=index" name="theForm" onsubmit="return validate()" enctype="multipart/form-data">
<table cellspacing="1" cellpadding="3" width="100%">
<tr>
<td class="label">请选择你要上传的EXCELL:</td>
<td>excell下载模板</td>
</tr>
<tr>
<td class="label">请选择你要上传的excell:</td>
<td><input type="file" name="myfile"></td>
</tr>
<tr>
<td colspan="2" align="center"><br />
<input type="submit" class="button" value="提交" />
</td>
</tr>
</table>
</form>
3,php代码写入
//批量上传操作
function upExecel(){
//判断是否选择了要上传的表格
if (empty($_POST[\'myfile\'])) {
echo "<script>alert(您未选择表格);history.go(-1);</script>";
}
$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\'])) {
if ($file_type=="application/vnd.ms-excel")
{
$objReader = PHPExcel_IOFactory::createReader(\'Excel5\');
}
else
{
$objReader = PHPExcel_IOFactory::createReader(\'Excel2007\');
}
$filename = $_FILES[\'myfile\'][\'tmp_name\'];
$objPHPExcel = $objReader->load($filename);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
for($j=2;$j<=$highestRow;$j++)
{
$a = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();
$b = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();
$c = $objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();
$d = $objPHPExcel->getActiveSheet()->getCell("D".$j)->getValue();
$e = $objPHPExcel->getActiveSheet()->getCell("E".$j)->getValue();
$f = $objPHPExcel->getActiveSheet()->getCell("F".$j)->getValue();
$g = $objPHPExcel->getActiveSheet()->getCell("G".$j)->getValue();
$h = $objPHPExcel->getActiveSheet()->getCell("H".$j)->getValue();
//null 为主键id,自增可用null表示自动添加
//$sql = "INSERT INTO house VALUES(null,\'$a\',\'$b\',\'$c\',\'$d\',\'$e\',\'$f\',\'$g\',\'$h\')";
$newrow = array(
\'title\' => $c,
\'pid\' => $b,
\'huohao\' => $a,
\'guige\' => $d,
\'price\' => $e,
\'huoc\' => $f,
\'wendu\' => $g,
\'zbq\' => $h,
\'content\' => $content,
\'upfile\' => \'/upload/12.jpg\',
\'add_time\' => time(),
);
$row=spClass(\'goods_list\')->create($newrow);
if ($row){
echo "<script>alert(\'添加成功!\');window.location.href=\'http://www.96net.com.cn/index.php?c=goods&a=index\';</script>";
}else{
echo "<script>alert(\'添加失败!\');window.location.href=\'http://www.96net.com.cn/index.php?c=goods&a=ppaddpage\';</script>";
exit();
}
}
}
}
需要注意是:xls文件 用 $objReader = PHPExcel_IOFactory::createReader(\'Excel5\'); xlsx文件 用 $objReader = PHPExcel_IOFactory::createReader(\'Excel2007\');