使用phpExcel批量上传excel表数据到mysql数据库中
/*批量上传数据*/ if(isset($_POST['submit']) && $_POST['submit']=='上传文件') { //导入类文件 require_once ("../Classes/PHPExcel.php"); require_once ("../Classes/PHPExcel/IOFactory.php"); //判断是否未选中文件 if($_FILES['file']['size']==0) { echo "<script>alert('您未选中任何文件,请重新选择!');history.go(-1);</script>"; } //限制上传表格大小,最大为5M $file_size=$_FILES['file']['size']; $maxSize=5242880; if($file_size >= $maxSize) { echo "<script>alert('上传失败,上传表格的大小不能超过5M');history.go(-1);</script>"; } //检测上传文件的类型 $type=$_FILES['file']['type']; $type1='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $type2='application/vnd.ms -excel'; if(($type!==$type1)&&($type !==$type2)) { echo "<script>alert('您上传的文件不是EXCEL表格!');history.go(-1);</script>"; } //对于不同类型的EXCEL文件,传入不同的PHPEXCEL类 if($type==$type1) { require_once ("../Classes/PHPExcel/Reader/Excel2007.php"); $objReader = \PHPExcel_IOFactory::createReader('Excel2007'); } elseif($type==$type2) { require_once ("../Classes/PHPExcel/Reader/Excel5.php"); $objReader = \PHPExcel_IOFactory::createReader('Excel5'); } else { echo "<script>alert('您上传的文件不是EXCEL表格!')</script>"; } //判断是否成功传入服务器,取出放在缓存中的表格 if(is_uploaded_file($_FILES['file']['tmp_name'])) { $objPHPExcel = new PHPExcel(); $filename = $_FILES['file']['tmp_name']; $objPHPExcel = PHPExcel_IOFactory::load($filename); //得到表单、行数及列数 $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); $highestColumn = $sheet->getHighestColumn(); $usefulColumn= PHPExcel_Cell::columnIndexFromString($highestColumn); $cell=''; $i=0; //循环读取插入数据库 for($k = 2; $k<=$highestRow; $k++){ for($j=0; $j<$usefulColumn; $j++){ $colIndex = PHPExcel_Cell::stringFromColumnIndex($j); $address = $colIndex.$k; $cell .= "'". addslashes($sheet->getCell($address)->getValue())."'".','; } $strValue=substr($cell,0,-1); $sql="INSERT INTO page VALUES (null,$strValue)"; $result=mysqli_query($link,$sql); $i++; $cell=''; } if ($result) { echo "<script>alert('成功导入".$i."条数据');window.location.href='../View/AddPaper.php';</script>"; } else { echo "<script>alert('添加失败!');window.location.href='../View/AddPaper.php';</script>"; exit(); } } else { echo "<script>alert('上传失败!');history.go(-1);</script>"; } }