Maison > php教程 > php手册 > le corps du texte

Thinkphp 用PHPExcel 导入Excel

PHP中文网
Libérer: 2016-08-29 08:36:48
original
1103 Les gens l'ont consulté

搞了个简单的Excel导入, 用的是PHPExcel(百科:用来操作Office Excel文档的一个PHP类库, 基于微软的OpenXML标准和PHP语言)

好, 不说了, 开始吧...

首先得有PHPExcel类库, 点这里下载 https://github.com/Zmwherein/PHPExcel.git

然后把它放在 \ThinkPHP\Library\Vendor(个人喜好, 能引入就行了)

如图:

PHPExcel.php 类似一个入口文件. 可以进去看看里面写的方法是怎个跑法..

这是界面:

首先来判断下有没有文件上传了(其实这里的应该还能优化写得更好的, 不过暂时个人能力有限)


 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             }
Copier après la connexion


接着跑下去 , 导入的是PHPExcel.php和PHPExcel/IOFactory.php这两个文件


1 //导入PHPExcel 和 IOFactory类
2 Vendor('PHPExcel.PHPExcel');
3 Vendor('PHPExcel.PHPExcel.IOFactory');
Copier après la connexion


因为是导入嘛,所以就调用createReader方法


$objReader = \PHPExcel_IOFactory::createReader('Excel5');
Copier après la connexion


设置路径, 上传的文件在哪, 也就是加载个文件出来


$objPHPExcel = $objReader -> load($file_path, $encode='utf-8');
Copier après la connexion


这里说的是遍历行数, 从A到E(自己定义的,要取哪就取哪) 这里i要从2开始, 因为第一行是表头, 不是数据


 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);
Copier après la connexion


测试表是这样的

现在打印个$allData出来看看

看, 数据出来了...

接下来要导入到数据库里面了->导入前得作个小判断. 比如我想如果数据库里的电话跟我想要导入的数据有相同的话, 就不要导入 类似这样的-> 大神们还有没有什么好一点的方法


 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             }
Copier après la connexion


导入时, 有两种方法 一是拼接sql 二是用foreach循环来导入

实测第一种要快得多!!!强烈建议拼接sql导入...不过如果导入的数据过大, 拼接起来的sql会很长, 因此数据会比较大...

有时会报执行文件超时的错误 或者是遇到1153 – Got a packet bigger than ‘max_allowed_packet’ bytes OR

服务器直接挂了 这样的报错

这样你就要需要修改my.ini 里的max_allowed_packet把它稍设大一点就可以了,重启MySql

OK..等待片刻, 差不多2W的数据就导进去了(^_^)

以上是我写的插入语句


 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             }
Copier après la connexion


 

 好了. 以上是利用PHPExcel导入Excel文件. 

还有很多不足且需要修改的地方, 还望恳请各位指出. 

 

以上就是Thinkphp 用PHPExcel 导入Excel的内容,更多相关内容请关注PHP中文网(www.php.cn)!



Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Recommandations populaires
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!