1.下载PHPExcel-1.8
下载地址:https://codeload.github.com/PHPOffice/PHPExcel/zip/1.8
2.前端页面-通过form表单提交
必须设置enctype="multipart/form-data"
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="./a.php" method="post" enctype="multipart/form-data"> <input type="file" name="file">EXCEL上传 <input type="submit"> </form> </body> </html>
3.php操作页面
<?php /* * PDO连接数据库 */ $dsn = 'mysql:dbname=brick;host=127.0.0.1'; $user = 'root'; $password = 'root'; try { $pdo = new PDO($dsn, $user, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } /* * 引入PHPexcel包 */ require_once("./PHPExcel-1.8/Classes/PHPExcel/IOFactory.php"); $file = $_FILES; //临时文件存放路径 $fileTmp = $file['file']['tmp_name']; $fileSize = $file['file']['size']; $fileName = $file['file']['name']; //错误,输出0,表示文件提交成功 $fileError = $file['file']['error']; $inputFileName = $fileTmp; if ($fileError == 0) { date_default_timezone_set('PRC'); try { $inputFileType = PHPExcel_IOFactory::identify($inputFileName); $objReader = PHPExcel_IOFactory::createReader($inputFileType); $objPHPExcel = $objReader->load($inputFileName); } catch (Exception $e) { } } // 确定要读取的sheet,什么是sheet,看excel的右下角 $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow();//行数 $highestColumn = $sheet->getHighestColumn();//列数 // 把数据处理后存入数组 for ($row = 2; $row <= $highestRow; $row++) { $rowData[] = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, TRUE); } /* * $rowData是一个三维数组 * 所以遍历两次 */ foreach ($rowData as $row) { foreach ($row as $v) { $name = $v['0']; $age = $v['1']; $gender = $v['2']; $class = $v['3'];
$sql = "insert into excel (name,age,gender,class) values ('$name',$age,'$gender','$class')"; $pp=$pdo->exec($sql); if($pp) echo "添加成功"; else echo "添加失败"; } }
4.代码例子
数据库信息
标签:原生,sheet,name,gender,EXCEL,file,PHPExcel,PHP,row From: https://www.cnblogs.com/junwuxiao/p/17031655.html