本文章来给大家介绍一款PHPExcel读取excel并导入数据库代码实现,有需要了解的朋友可参考,这里我们介绍的是读取表格之后再创建mysql连接,然后保存到mysql数据库.
PHPExcel是相当强大的 MS Office Excel 文档生成类库,当需要输出比较复杂格式数据的时候,PHPExcel 是个不错的选择,不过其使用方法相对来说也就有些繁琐,代码如下:
- <?php
- set_time_limit(20000);
- ini_set('memory_limit','-1');
- require_once './PHPExcel.php';
- require_once './PHPExcel/IOFactory.php';
- require_once './PHPExcel/Reader/Excel5.php';
-
-
- $dsn = "mysql:host=localhost;dbname=alumni;";
- $user = "root";
- $password = "";
- try{
- $dbh = new PDO($dsn,$user,$password);
- $dbh->query('set names utf8;');
- }catch(PDOException $e){
- echo "连接失败".$e->getMessage();
- }
-
- $stmt = $dbh->prepare("insert into alumni(gid,student_no,name) values (:gid,:student_no,:name) ");
- $stmt->bindParam(":gid", $gid,PDO::PARAM_STR);
- $stmt->bindParam(":student_no", $student_no,PDO::PARAM_STR);
- $stmt->bindParam(":name", $name,PDO::PARAM_STR);
-
- $objReader = new PHPExcel_Reader_Excel5();
- $objPHPExcel = $objReader->load('bks.xls');
- $sheet = $objPHPExcel->getSheet(0);
- $highestRow = $sheet->getHighestRow();
- $highestColumn = $sheet->getHighestColumn();
-
- for($j=1;$j<=10;$j++)
- {
-
- $student_no = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();
- $name = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();
- $gid = $objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();
- }
-
- $stmt->execute();
- ?>
|