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');