php excel reader讀取excel內(nèi)容存入數(shù)據(jù)庫實現(xiàn)代碼
上一篇文章介紹了php-excel-reader讀取excel文件的方法,因為需要,將excel這樣的數(shù)據(jù):
新建數(shù)據(jù)庫表如下:
-- 數(shù)據(jù)庫: `alumni`
-- 表的結(jié)構(gòu) `alumni`
CREATE TABLE IF NOT EXISTS `alumni` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`gid` varchar(20) DEFAULT NULL COMMENT '檔案編號',
`student_no` varchar(20) DEFAULT NULL COMMENT '學(xué)號',
`name` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `gid` (`gid`),
KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
導(dǎo)入后數(shù)據(jù)庫結(jié)果如下:
php源碼如下:
<?php
header("Content-Type:text/html;charset=utf-8");
require_once 'excel_reader2.php';
set_time_limit(20000);
ini_set("memory_limit","2000M");
//使用pdo連接數(shù)據(jù)庫
$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();
}
//pdo綁定參數(shù)操作
$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);
//使用php-excel-reader讀取excel內(nèi)容
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('UTF-8');
$data->read("stu.xls");
for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
for ($j = 1; $j <= 3; $j++) {
$student_no = $data->sheets[0]['cells'][$i][1];
$name = $data->sheets[0]['cells'][$i][2];
$gid = $data->sheets[0]['cells'][$i][3];
}
//將獲取的excel內(nèi)容插入到數(shù)據(jù)庫
$stmt->execute();
}
echo "執(zhí)行成功";
echo "最后插入的ID:".$dbh->lastInsertId();
?>
考慮到excel的量比較大,使用了PDO的綁定操作!
相關(guān)文章
thinkphp制作404跳轉(zhuǎn)頁的簡單實現(xiàn)方法
下面小編就為大家?guī)硪黄猼hinkphp制作404跳轉(zhuǎn)頁的簡單實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-09-09tp5.1 框架數(shù)據(jù)庫常見操作詳解【添加、刪除、更新、查詢】
這篇文章主要介紹了tp5.1 框架數(shù)據(jù)庫常見操作,結(jié)合實例形式詳細分析了thinkPHP5.1針對數(shù)據(jù)庫的添加、刪除、更新、查詢相關(guān)操作技巧與使用注意事項,需要的朋友可以參考下2020-05-05