PHPExcel读取excel并导入mysql数据库
本文章来给大家介绍一款PHPExcel读取excel并导入数据库代码实现,有需要了解的朋友可参考,这里我们介绍的是读取表格之后再创建mysql连接,然后保存到mysql数据库.
PHPExcel是相当强大的 MS Office Excel 文档生成类库,当需要输出比较复杂格式数据的时候,PHPExcel 是个不错的选择,不过其使用方法相对来说也就有些繁琐,代码如下:
1<?php
2 set_time_limit(20000);
3 ini_set('memory_limit','-1');
4 require_once './PHPExcel.php';
5 require_once './PHPExcel/IOFactory.php';
6 require_once './PHPExcel/Reader/Excel5.php';
7 //使用pdo连接数据库
8 $dsn = "mysql:host=localhost;dbname=alumni;";
9 $user = "root";
10 $password = "";
11 try{
12 $dbh = new PDO($dsn,$user,$password);
13 $dbh->query('set names utf8;');
14 }catch(PDOException $e){
15 echo "连接失败".$e->getMessage();
16 }
17 //pdo绑定参数操作
18 $stmt = $dbh->prepare("insert into alumni(gid,student_no,name) values (:gid,:student_no,:name) ");
19 $stmt->bindParam(":gid", $gid,PDO::PARAM_STR);
20 $stmt->bindParam(":student_no", $student_no,PDO::PARAM_STR);
21 $stmt->bindParam(":name", $name,PDO::PARAM_STR);
22 $objReader = new PHPExcel_Reader_Excel5(); //use excel2007
23 $objPHPExcel = $objReader->load('bks.xls'); //指定的文件
24 $sheet = $objPHPExcel->getSheet(0);
25 $highestRow = $sheet->getHighestRow(); // 取得总行数
26 $highestColumn = $sheet->getHighestColumn(); // 取得总列数
27 //开源代码phpfensi.com
28 for($j=1;$j<=10;$j++)
29 {
30 $student_no = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();//第一列学号
31 $name = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//第二列姓名
32 $gid = $objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();//第三列gid
33 }
34 //将获取的excel内容插入到数据库
35 $stmt->execute();
36?>
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/php-excel-mysql/4495.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.