php excel reader讀取excel內(nèi)容存入數(shù)據(jù)庫實(shí)現(xiàn)代碼
上一篇文章介紹了php-excel-reader讀取excel文件的方法,因?yàn)樾枰?,將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 '檔案編號(hào)',
`student_no` varchar(20) DEFAULT NULL COMMENT '學(xué)號(hào)',
`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)文章
Zend?Framework框架的校驗(yàn)器使用使用示例(自定義校驗(yàn)器和校驗(yàn)器鏈)
這篇文章主要介紹了Zend?Framework框架的校驗(yàn)器使用使用示例(自定義校驗(yàn)器和校驗(yàn)器鏈),需要的朋友可以參考下2014-03-03
php redis實(shí)現(xiàn)對(duì)200w用戶的即時(shí)推送
這篇文章主要為大家詳細(xì)介紹了php redis實(shí)現(xiàn)對(duì)200w用戶的即時(shí)推送,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03
淺談laravel框架sql中g(shù)roupBy之后排序的問題
今天小編就為大家分享一篇淺談laravel框架sql中g(shù)roupBy之后排序的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-10-10

