搞了個簡單的Excel導入, 用的是PHPExcel(百科:用來操作Office Excel文檔的一個PHP類庫, 基於微軟的OpenXML標準和PHP語言)
好, 不說了, 開始吧...
首先得有PHPExcel類庫, 點這裡下載 https://github.com/Zmwherein/PHPExcel.git
然後把它放在 ThinkPHPLibraryVendor(個人喜好, 能引入就行了)

PHPExcel.php 類似一個入口文件. 可以進去看看裡面寫的方法是怎個跑法..
這是界面:

首先來判斷下有沒有文件上傳了(其實這裡的應該還能優化寫得更好的, 不過暫時個人能力有限)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 1 public function import()
2 {
3
4 if ( ! empty ( $_FILES ))
5 {
6 $upload = new \Think\Upload();
7 $upload -> maxSize = 3145728 ;
8 $upload -> exts = array ( 'xlsx' , 'xls' );
9 $upload -> rootPath = './' ;
10 $upload -> savePath = '/Upload/excel/' ;
11 $upload -> subName = false;
12 $upload -> saveName = 'time' ;
13
14 $info = $upload -> uploadOne( $_FILES [ 'import' ]);
15
16 if ( ! $info )
17 {
18 $this ->error( $upload ->getError());
19 }
|
登入後複製
接著跑下去, 導入的是PHPExcel.php和PHPExcel/IOFactory.php這兩個檔案
因為是導入嘛,所以就呼叫createReader方法
1 2 3 | 1
2 Vendor( 'PHPExcel.PHPExcel' );
3 Vendor( 'PHPExcel.PHPExcel.IOFactory' );
|
登入後複製
這裡說的是遍歷行數, 從A到E(自己定義的,要取哪就取哪) 這裡i要從2開始, 因為第一行是表頭, 不是數據
1 | $objReader = \PHPExcel_IOFactory::createReader( 'Excel5' );
|
登入後複製
測試表是這樣的
現在印個$allData出來看看
>導入前得作個小判斷. 例如我想如果資料庫裡的電話跟我想要導入的資料有相同的話, 就不要導入 類似這樣的-> 大神們還有沒有什麼好一點的方法
1 | $objPHPExcel = $objReader -> load( $file_path , $encode ='utf-8');
|
登入後複製
導入時, 有兩種方法一是拼接sql 二是用foreach循環來導入
實測第一種要快得多!!!強烈建議拼接導入...不過如果導入的sql導入...不過如果導入的sql資料過大, 拼接起來的sql會很長, 因此資料會比較大...
有時會報執行檔逾時的錯誤或是遇到1153 – Got a packet bigger than 'max_allowed_packet' bytes OR
伺服器直接掛了 這樣的報錯
這樣你就要需要修改my.ini 裡的max_allowed_packet把它稍設大一點就可以了,重啟MySql
OK..等待片刻, 差不多2W的數據就導進去了(^ _^)
以上是我寫的插入語句

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 1 $sheet = $objPHPExcel -> getSheet(0);
2 $highestRow = $sheet -> getHighestRow();
3
4
5
6 for ( $i =2; $i <= $highestRow ; $i ++)
7 {
8 $data ['user_name'] = $objPHPExcel -> getActiveSheet() -> getCell( "A" . $i )->getValue();
9 $data ['company'] = $objPHPExcel -> getActiveSheet() -> getCell( "B" . $i )->getValue();
10 $data ['mobile'] = $objPHPExcel -> getActiveSheet() -> getCell( "C" . $i )->getValue();
11 $data ['category'] = $objPHPExcel -> getActiveSheet() -> getCell( "D" . $i )->getValue();
12 $data ['mark'] = $objPHPExcel -> getActiveSheet() -> getCell( "E" . $i )->getValue();
13
14 $allData [] = $data ;
15 }
16
|
登入後複製
, 也望懇請各位指出.

以上就是Thinkphp 用PHPExcel 導入Excel的內容,更多相關內容請關注PHP中文網(www.php.cn)!