直接上代码:
html:
<tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="10%" height="30" align="right" bgcolor="#f2f2f2" class="left_txt2">上传文件</td> <td width="1%" bgcolor="#f2f2f2"> </td> <td width="32%" height="30" bgcolor="#f2f2f2"> <input type="file" name="excelPacket" class="file"> </td> </tr> <tr> <td height="30" colspan="4" align="center" class="left_txt"><input type="submit" name="button" id="button" value="创建" /> <input type="reset" name="button2" id="button2" value="重置" /></td> </tr> </table</td>
php:(另外在该文件包上一级建立一个文件夹用于存放要导入的excel表)
记得引入PHPexcel类包
header("Content-type:text/html;charset=utf-8"); require_once 'backend_islogin.php'; require_once '../db/Db.php'; require_once '../backend/PHPExcel/PHPExcel.php'; $PHPReader = new PHPExcel_Reader_Excel2007(); //print_r ($_SESSION);exit; $fileExtArr = explode(".",$_FILES['excelPacket']['name']); $fileExt = ".".$fileExtArr[1]; $path=$_SERVER['DOCUMENT_ROOT'].'/excelupload/'.time().md5($_FILES['excelPacket']['name'].rand()).$fileExt; move_uploaded_file($_FILES['excelPacket']['tmp_name'],$path); if( ! $PHPReader->canRead($path)) { $PHPReader = new PHPExcel_Reader_Excel5(); if( ! $PHPReader->canRead($path)){ echo 'no Excel'; return ; } } $PHPExcel = $PHPReader->load($path); //读取文件 $currentSheet = $PHPExcel->getSheet(0); //读取第一个工作簿 $allColumn = $currentSheet->getHighestColumn(); // 所有列数 $allRow = $currentSheet->getHighestRow(); // 所有行数 $data = array(); //下面是读取想要获取的列的内容 for ($rowIndex = 2; $rowIndex <= $allRow; $rowIndex++) { $data[] = array( 'name' => $currentSheet->getCell('A'.$rowIndex)->getValue(), 'brand' => $currentSheet->getCell('B'.$rowIndex)->getValue(), 'goods_code' => $currentSheet->getCell('C'.$rowIndex)->getValue(), 'credit_code' => $currentSheet->getCell('D'.$rowIndex)->getValue(), 'f_code' => $currentSheet->getCell('E'.$rowIndex)->getValue(), 'c_code' => $currentSheet->getCell('F'.$rowIndex)->getValue(), 'adapt_mod' => $currentSheet->getCell('G'.$rowIndex)->getValue(), 'oe_code' => $currentSheet->getCell('H'.$rowIndex)->getValue(), 'img_code' => $currentSheet->getCell('I'.$rowIndex)->getValue(), 'acc_info' => $currentSheet->getCell('J'.$rowIndex)->getValue(), 'user_id' => $_SESSION['session_id'], 'audit' => 0, ); } $dbObj = new DB(); foreach($data as $row){ $oe_code = $row["oe_code"]; $oe_code = $dbObj->get_one("select 'oe_code' from tb_goods where oe_code = '$oe_code'"); if(!empty($oe_code)){ echo "<script> alert('商品重复请重新上传'); location.href = 'backend_product.php'; </script>"; break; }else{ $re = $dbObj -> insert("tb_goods",$row); if($re){ echo "<script>alert('编辑成功');location.href='backend_product.php';</script>"; } } }