1.首先要下載phpexcel放到vendor文件夾下,我的路徑是:項目/vendor/phpexcel/,把下載的phpexcel文件放在這里
2.前端代碼
1
2
3
4
5
6
7
8
9
10
11
12
|
<!doctype html> <html> <head> <title>批量導入數據</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= "批量的導入" > </form> </body> </html> |
3.后臺代碼
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
|
/** * 導入表格數據 * 先把文件上傳到服務器,然后再讀取數據存到數據庫 */ 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類 vendor( 'phpexcel.phpexcel.reader.excel5' ); //獲取上傳后的文件名 $filename = $info ->getsavename(); //文件路徑 $filepath = 'public/uploads/excel/' . $filename ; //實例化phpexcel類 $phpreader = new phpexcel_reader_excel5(); //讀取excel文件 $objphpexcel = $phpreader ->load( $filepath ); //讀取excel文件中的第一個工作表 $sheet = $objphpexcel ->getsheet(0); $allrow = $sheet ->gethighestrow(); //取得總行數 //$allcolumn = $sheet->gethighestcolumn(); //取得總列數 //從第二行開始插入,第一行是列名 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 ); //保存數據,并返回主鍵id if ( $last_id ) { echo "第" . $j . "行導入成功,users表第:" . $last_id . "條!<br/>" ; } else { echo "第" . $j . "行導入失敗!<br/>" ; } } } else { echo "上傳文件失敗!" ; } } |
輸出結果:
注意:
引入第三方類庫使用vendor();是按照命名空間的形式。底層代碼會把“ . ”自動替換成" / ",所以使用“ / ”時要用“ . ”代替;
以上代碼可以直接復制使用,但是數據庫相關信息要改成你自己的!
總結
以上所述是小編給大家介紹的thinkphp5+phpexcel實現批量上傳表格數據功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會
原文鏈接:http://www.cnblogs.com/zxf100/archive/2017/11/28/7908659.html