框架用的是thinkphp3.2框架 //将Excel导入到数据库的思想是:先将Excel中的数据转为php数组,然后执行addAll操作 public function upload() { ini_set('memory_limit', '1024M'); if (!empty($_FILES)) { $config = array( 'exts' => array('xlsx', 'xls'), 'maxSize' => 3145728000, 'rootPath' => "./Public/", 'savePath' => 'Uploads/', 'subName' => array('date', 'Ymd'), ); $upload = new \Think\Upload($config); if (!$info = $upload->upload()) { $this->error($upload->getError()); } vendor("PHPExcel.PHPExcel"); $file_name = $upload->rootPath . $info['photo']['savepath'] . $info['photo']['savename']; $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));//判断导入表格后缀格式 if ($extension == 'xlsx') { $objReader = \PHPExcel_IOFactory::createReader('Excel2007'); $objPHPExcel = $objReader->load($file_name, $encode = 'utf-8'); } else if ($extension == 'xls') { $objReader = \PHPExcel_IOFactory::createReader('Excel5'); $objPHPExcel = $objReader->load($file_name, $encode = 'utf-8'); } $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow();//取得总行数 $highestColumn = $sheet->getHighestColumn(); //取得总列数 //如果数据量比较大的话,每次插入100行,循环插入 $count = ceil($highestRow / 100); if ($count >= 2) {//如果$count>=2,表示至少进行两次整体循环(100条以上数据) for ($j = 1; $j <= $count; $j++) {//循环插入数据表 for ($i = 2 + ($j - 1) * 100; $i <= 101 * $j; $i++) { //2---101,102---202,202--303,302--404,402--505,502--606重复 //看这里看这里,前面小写的a是表中的字段名,后面的大写A是excel中位置 //$i-2,是的数组的索引从0开始 $data[($i - 2) - ($j - 1) * 100]['pId'] = $objPHPExcel->getActiveSheet()->getCell("A" . $i)->getValue(); $data[($i - 2) - ($j - 1) * 100]['pName'] = $objPHPExcel->getActiveSheet()->getCell("B" . $i)->getValue(); $data[($i - 2) - ($j - 1) * 100]['pPrice'] = $objPHPExcel->getActiveSheet()->getCell("C" . $i)->getValue(); $data[($i - 2) - ($j - 1) * 100]['pCount'] = $objPHPExcel->getActiveSheet()->getCell("D" . $i)->getValue(); } //删除重复的数据 if ($j >= 3) { for ($x = 3; $x <= $j; $x++) {//从第三波循环开始删除操作,删除重复的1个,第四波循环删除重复的2个,第五波循环删除3个... unset($data[$x - 3]); } $data = array_values($data);//重新建立索引 } D('pro_info')->addAll($data); } } else {//少于100条记录的时候,只addAll一次 for ($i = 2; $i <= $highestRow; $i++) { //看这里看这里,前面小写的a是表中的字段名,后面的大写A是excel中位置 //$i-2,是的数组的索引从0开始 $data[$i - 2]['pId'] = $objPHPExcel->getActiveSheet()->getCell("A" . $i)->getValue(); $data[$i - 2]['pName'] = $objPHPExcel->getActiveSheet()->getCell("B" . $i)->getValue(); $data[$i - 2]['pPrice'] = $objPHPExcel->getActiveSheet()->getCell("C" . $i)->getValue(); $data[$i - 2]['pCount'] = $objPHPExcel->getActiveSheet()->getCell("D" . $i)->getValue(); } D('pro_info')->addAll($data); } $this->success('导入成功!'); } else { $this->error("请选择上传的文件"); } }
将excel数据导入到mysql数据库
最新推荐文章于 2024-09-06 10:40:56 发布