
下面我們將使用Spreadsheet_Excel_Reader類將excel文件導(dǎo)入php數(shù)據(jù)庫,步驟如下:
1.下載類庫
2.創(chuàng)建db_config.php文件
3.創(chuàng)建index . php文件
4.創(chuàng)建excelUpload.php
5.創(chuàng)建上傳文件夾
步驟1:下載類庫
從GitHub下載PHP Excel Reader庫,下載地址:https://github.com/nuovo/spreadsheet-reader
下載后將其解壓縮到根目錄并將其重命名為“l(fā)ibrary”。
步驟2:創(chuàng)建db_config.php文件
為數(shù)據(jù)庫配置創(chuàng)建db_config.php文件,在這個文件中,你必須設(shè)置數(shù)據(jù)庫主機、數(shù)據(jù)庫用戶名、數(shù)據(jù)庫密碼、數(shù)據(jù)庫名稱。該文件將用于將數(shù)據(jù)存儲到數(shù)據(jù)庫中。
代碼如下:
db_config.php
?php $dbHost = localhost $dbDatabase = h_php $dbPasswrod = root $dbUser = root $mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);?
步驟3:創(chuàng)建index.php文件
在根目錄中創(chuàng)建index.php文件,在這個文件中,我使用bootstrap創(chuàng)建了一個簡單的表單,實現(xiàn)點擊按鈕后導(dǎo)入選擇excel文件的功能。
代碼如下:
index . php
!DOCTYPE html html head meta charset= UTF-8 title /title link rel= stylesheet type= text/css href= https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css /head body div >前臺樣式如下:
步驟4:創(chuàng)建excelUpload.php文件
創(chuàng)建excelUpload.php文件來管理導(dǎo)入數(shù)據(jù)庫的數(shù)據(jù),在這個步驟中,我們必須創(chuàng)建uploads文件夾來存儲excel文件到這個文件中,然后讀取該文件。
代碼如下:
excelUpload.php
?phprequire( library/php-excel-reader/excel_reader2.php require( library/SpreadsheetReader.php require( db_config.php if(isset($_POST[ Submit ])){ $mimes = [ application/vnd.ms-excel , text/xls , text/xlsx , application/vnd.oasis.opendocument.spreadsheet if(in_array($_FILES[ file ][ type ],$mimes)){ $uploadFilePath = uploads/ .basename($_FILES[ file ][ name move_uploaded_file($_FILES[ file ][ tmp_name ], $uploadFilePath); $Reader = new SpreadsheetReader($uploadFilePath); $totalSheet = count($Reader- sheets()); echo 你有 .$totalSheet. 張表 . $html= table border= 1 $html.= tr th 標題 /th th 描述 /th /tr for($i=0;$i $totalSheet;$i++){ $Reader- ChangeSheet($i); foreach ($Reader as $Row) $html.= tr $title = isset($Row[0]) ? $Row[0] : $description = isset($Row[1]) ? $Row[1] : $html.= td .$title. /td $html.= td .$description. /td $html.= /tr $query = insert into items(title,description) values( .$title. , .$description. ) $mysqli- query($query); $html.= /table echo $html; echo br / 添加到數(shù)據(jù)庫的數(shù)據(jù) }else { die( br/ sorry,不允許此文件類型上傳,只允許Excel文件。 ?相關(guān)視頻教程推薦:《PHP教程》《mysql教程》
本篇文章就是關(guān)于PHP將excel文件導(dǎo)入mysql數(shù)據(jù)庫的方法介紹,希望對需要的朋友有所幫助!
以上就是PHP如何將excel文件導(dǎo)入mysql數(shù)據(jù)庫?的詳細內(nèi)容,PHP教程
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。
新聞熱點
疑難解答