In many cases we will need to upload tables to the database in batches, so today I will teach you how to use PHP to upload tables in batches.
First of all, you need to download PHPExcel and put it in the vendor folder. My path is: project/vendor/PHPExcel/, put the downloaded PHPExcel file here
Front-end code
<!DOCTYPE html> <html> <head> <title>批量导入数据</title> </head> <body> <form action="{:url('/index/index/importExcel')}" method="post" enctype="multipart/form-data"> <input type="file" name="myfile"><br/> <input type="submit" value="批量的导入"> </form> </body> </html>
Backend code
/** * 导入表格数据 * 先把文件上传到服务器,然后再读取数据存到数据库 */ public function importExcel(){ header("content-type:text/html;charset=utf-8"); //上传excel文件 $file = request()->file('myfile'); //移到/public/uploads/excel/下 $info = $file->move(ROOT_PATH.'public'.DS.'uploads'.DS.'excel'); //上传文件成功 if ($info) { //引入PHPExcel类 vendor('PHPExcel.PHPExcel.Reader.Excel5'); //获取上传后的文件名 $fileName = $info->getSaveName(); //文件路径 $filePath = 'public/uploads/excel/'.$fileName; //实例化PHPExcel类 $PHPReader = new \PHPExcel_Reader_Excel5(); //读取excel文件 $objPHPExcel = $PHPReader->load($filePath); //读取excel文件中的第一个工作表 $sheet = $objPHPExcel->getSheet(0); $allRow = $sheet->getHighestRow(); //取得总行数 //$allColumn = $sheet->getHighestColumn(); //取得总列数 //从第二行开始插入,第一行是列名 for ($j=2; $j <= $allRow; $j++) { $data['name'] = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue(); $data['tel'] = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue(); $data['addr'] = $objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue(); $last_id = Db::table('users')->insertGetId($data);//保存数据,并返回主键id if ($last_id) { echo "第".$j."行导入成功,users表第:".$last_id."条!<br/>"; }else{ echo "第".$j."行导入失败!<br/>"; } } }else{ echo "上传文件失败!"; } }
Output results
Note:
Introduce third party Class libraryUse vendor( ); is in the form of namespace. The underlying code will automatically replace "." with "/", so when using "/", use "." instead;
The above code can be copied and used directly, but the database related information must be changed to your own !
# I believe you have mastered the methods after reading these cases. For more exciting information, please pay attention to other related articles on the php Chinese website!
Related reading:
php uses git deployment environment
Detailed explanation of javascript data types and git usage code
The above is the detailed content of How to use PHPExcel to upload tables in batches. For more information, please follow other related articles on the PHP Chinese website!