Home > php教程 > php手册 > body text

Thinkphp uses PHPExcel to import Excel

PHP中文网
Release: 2016-08-29 08:36:48
Original
1129 people have browsed it

I made a simple Excel import, using PHPExcel (Encyclopedia: a PHP class library used to operate Office Excel documents, based on Microsoft's OpenXML standard and PHP language)

Okay, no more, let's get started...

First you must have the PHPExcel class library, click here to download https://github.com/Zmwherein/PHPExcel.git

Then put it in ThinkPHPLibraryVendor (personal preference, just import it)

As shown:

PHPExcel.php is similar to an entry file. You can go in and see how the method written in it is run...

This is the interface:

First of all, let’s judge whether any files have been uploaded (actually, the ones here should still work) Optimize and write better, but my personal ability is limited for the time being)


 1 public function import() 
 2     { 
 3         // p($data_in_db); 
 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             }
Copy after login


Then I ran on and imported the two files PHPExcel.php and PHPExcel/IOFactory.php


1 //导入PHPExcel 和 IOFactory类
2 Vendor('PHPExcel.PHPExcel');
3 Vendor('PHPExcel.PHPExcel.IOFactory');
Copy after login


Because it is an import, so we call the createReader method


$objReader = \PHPExcel_IOFactory::createReader('Excel5');
Copy after login


Set the path, where is the uploaded file, that is, load a file


$objPHPExcel = $objReader -> load($file_path, $encode='utf-8');
Copy after login


What we are talking about here is the number of rows traversed, from A to E (you define it yourself, take whichever you want) i here starts from 2, because the first row is the header, not the data


 1 $sheet = $objPHPExcel -> getSheet(0);
 2             $highestRow = $sheet -> getHighestRow(); // 取得总行数 
 3             // p($highestRow); 
 4             // $highestColumn = $sheet->getHighestColumn(); // 取得总列数 
 5              
 6             for($i=2;$i<=$highestRow;$i++) 
 7             { 
 8     $data[&#39;user_name&#39;] = $objPHPExcel -> getActiveSheet() -> getCell("A".$i)->getValue(); 
 9     $data[&#39;company&#39;]   = $objPHPExcel -> getActiveSheet() -> getCell("B".$i)->getValue();
 10    $data[&#39;mobile&#39;]    = $objPHPExcel -> getActiveSheet() -> getCell("C".$i)->getValue();
 11     $data[&#39;category&#39;]  = $objPHPExcel -> getActiveSheet() -> getCell("D".$i)->getValue();
 12    $data[&#39;mark&#39;]      = $objPHPExcel -> getActiveSheet() -> getCell("E".$i)->getValue();
 13                 
 14                 $allData[] = $data;
 15             }
 16             // p($allData);
Copy after login


The test table looks like this

Now print out $allData to see

Look, the data is out...

The next step is to import it into the database - >You have to make a small judgment before importing. For example, if the phone number in the database is the same as the data I want to import, I don’t want to import something like this-> Does anyone have any better methods


 1  if (empty($allData)) 
 2             { 
 3                 $this -> error(C(&#39;MESSAGE.ERROR_NODATA&#39;)); 
 4             } 
 5             $data_in_db = M(&#39;Excel&#39;) -> field(&#39;mobile&#39;) -> select();//表Excel里所有数据 
 6             foreach ($data_in_db as $key => $val) 
 7             { 
 8                 foreach ($allData as $k => $v) 
 9                 {
 10                     if ($val[&#39;mobile&#39;] == $v[&#39;mobile&#39;])
 11                     {
 12                         unset($allData[$k]);
 13                     }
 14                 }
 15             }
Copy after login


When importing, there are two methods: one is to splice sql, the other is to use a foreach loop to import

The first method is much faster!!! It is strongly recommended to splice sql to import...but if The imported data is too large, and the spliced ​​sql will be very long, so the data will be relatively large...

Sometimes an execution file timeout error will be reported or 1153 – Got a packet bigger than ‘max_allowed_packet’ bytes OR

The server hangs up directly. Such an error is reported

In this case, you need to modify the max_allowed_packet in my.ini and set it slightly larger. Restart MySql

OK.. Wait for a moment, and almost 2W of data will be imported. In (^_^)

The above is the insertion statement I wrote


 1 $sql = "INSERT INTO `db_excel` (". implode(&#39;,&#39;,array_keys($allData[0])) .") VALUES "; 
 2             foreach ($allData as $key => $val) 
 3             { 
 4                 $sql .= "("; 
 5                 $sql .= "&#39;".implode("&#39;,&#39;", $val)."&#39;"; 
 6                 $sql .= "),"; 
 7             } 
 8             $sql = rtrim($sql,&#39;,&#39;); 
 9             // 出错返回false 否则返回成功行数
 10             $res = D(&#39;Excel&#39;) -> execute($sql);
 11             if ($res === false)
 12             {
 13                 $this -> error(C(&#39;MESSAGE.ERROR_IMPORT&#39;));
 14             }
 15             else if ($res > 0)
 16             {
 17                 $this -> success(C(&#39;MESSAGE.SUCCESS_IMPORT&#39;), U(&#39;Excel/index&#39;));
 18             }
 19             else if ($res === 0)
 20             {
 21                 $this -> success(C(&#39;MESSAGE.SUCCESS_IMPORT_0&#39;), U(&#39;Excel/index&#39;));
 22             }
Copy after login


Okay. The above is the use of PHPExcel to import Excel files.

There are still many shortcomings and I kindly ask you to point out the areas that need to be modified.

The above is the content of Thinkphp using PHPExcel to import Excel. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template