直接上代码:
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 ‘../db/Db.php‘; require_once ‘../backend/PHPExcel/PHPExcel.php‘; $PHPReader = new PHPExcel_Reader_Excel2007(); $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‘ => $cell = $currentSheet->getCell(‘A‘.$rowIndex)->getValue(), ‘brand‘ => $cell = $currentSheet->getCell(‘A‘.$rowIndex)->getValue(), ‘goods_code‘ => $cell = $currentSheet->getCell(‘C‘.$rowIndex)->getValue(), ‘credit_code‘ => $cell = $currentSheet->getCell(‘D‘.$rowIndex)->getValue(), ‘f_code‘ => $cell = $currentSheet->getCell(‘E‘.$rowIndex)->getValue(), ‘c_code‘ => $cell = $currentSheet->getCell(‘F‘.$rowIndex)->getValue(), ‘adapt_mod‘ => $cell = $currentSheet->getCell(‘G‘.$rowIndex)->getValue(), ‘oe_code‘ => $cell = $currentSheet->getCell(‘H‘.$rowIndex)->getValue(), ‘img_code‘ => $cell = $currentSheet->getCell(‘I‘.$rowIndex)->getValue(), ‘acc_info‘ => $cell = $currentSheet->getCell(‘J‘.$rowIndex)->getValue(), ); } //执行数据库操作 $dbObj = new DB(); foreach($data as $row){ if(empty($row[‘name‘])){ continue; } $dbObj -> insert("tb_goods",$row); } echo "<script>location.href = ‘product.php‘;</script>";
本文出自 “kangjunfei” 博客,转载请与作者联系!
原文地址:http://kangjunfei.blog.51cto.com/11556647/1969324