1.首先要下載phpexcel放到vendor文件夾下,我的路徑是:項(xiàng)目/vendor/phpexcel/,把下載的phpexcel文件放在這里
2.前端代碼
1
2
3
4
5
6
7
8
9
10
11
12
|
<!doctype html> <html> <head> <title>批量導(dǎo)入數(shù)據(jù)</title> </head> <body> <form action= "{:url('/index/index/importexcel')}" method= "post" enctype= "multipart/form-data" > <input type= "file" name= "myfile" ><br/> <input type= "submit" value= "批量的導(dǎo)入" > </form> </body> </html> |
3.后臺(tái)代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
/** * 導(dǎo)入表格數(shù)據(jù) * 先把文件上傳到服務(wù)器,然后再讀取數(shù)據(jù)存到數(shù)據(jù)庫(kù) */ public function importexcel(){ header( "content-type:text/html;charset=utf-8" ); //上傳excel文件 $file = request()->file( 'myfile' ); //移到/public/uploads/excel/下 $info = $file ->move(root_path. 'public' .ds. 'uploads' .ds. 'excel' ); //上傳文件成功 if ( $info ) { //引入phpexcel類(lèi) vendor( 'phpexcel.phpexcel.reader.excel5' ); //獲取上傳后的文件名 $filename = $info ->getsavename(); //文件路徑 $filepath = 'public/uploads/excel/' . $filename ; //實(shí)例化phpexcel類(lèi) $phpreader = new phpexcel_reader_excel5(); //讀取excel文件 $objphpexcel = $phpreader ->load( $filepath ); //讀取excel文件中的第一個(gè)工作表 $sheet = $objphpexcel ->getsheet(0); $allrow = $sheet ->gethighestrow(); //取得總行數(shù) //$allcolumn = $sheet->gethighestcolumn(); //取得總列數(shù) //從第二行開(kāi)始插入,第一行是列名 for ( $j =2; $j <= $allrow ; $j ++) { $data [ 'name' ] = $objphpexcel ->getactivesheet()->getcell( "a" . $j )->getvalue(); $data [ 'tel' ] = $objphpexcel ->getactivesheet()->getcell( "b" . $j )->getvalue(); $data [ 'addr' ] = $objphpexcel ->getactivesheet()->getcell( "c" . $j )->getvalue(); $last_id = db::table( 'users' )->insertgetid( $data ); //保存數(shù)據(jù),并返回主鍵id if ( $last_id ) { echo "第" . $j . "行導(dǎo)入成功,users表第:" . $last_id . "條!<br/>" ; } else { echo "第" . $j . "行導(dǎo)入失敗!<br/>" ; } } } else { echo "上傳文件失敗!" ; } } |
輸出結(jié)果:
注意:
引入第三方類(lèi)庫(kù)使用vendor();是按照命名空間的形式。底層代碼會(huì)把“ . ”自動(dòng)替換成" / ",所以使用“ / ”時(shí)要用“ . ”代替;
以上代碼可以直接復(fù)制使用,但是數(shù)據(jù)庫(kù)相關(guān)信息要改成你自己的!
總結(jié)
以上所述是小編給大家介紹的thinkphp5+phpexcel實(shí)現(xiàn)批量上傳表格數(shù)據(jù)功能,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)
原文鏈接:http://www.cnblogs.com/zxf100/archive/2017/11/28/7908659.html