phpexcel导入excel数据使用方法实例


Posted in PHP onDecember 24, 2013

将Excel文件数据进行读取,并且返回错误的信息

/**
     * 导入商品基本信息
     */
    public function importProductBasicInfo($data){
        include_once 'PHPExcel.php';
        include_once 'PHPExcel/IOFactory.php';
        include_once 'PHPExcel/Reader/Excel5.php';
        // 定义一个错误集合.
        $error = array();
        $resultInfo = null;
        $needNext = true;
        //上传文件到服务器指定位置
        $fileName = $_FILES["productinfo"]['name'];
        $filePath = CBase_Common_UploadPicture::uploadFile($data["productinfo"], 'product');
        //如果上传文件成功,就执行导入excel操作
        if($filePath == 1) {
            $error[1] = "上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值";
        }else if($filePath == 4){
            $error[4] = "没有文件被上传";
        }else{
            $objReader = PHPExcel_IOFactory::createReader('Excel5');
            $objReader->setReadDataOnly(true);
            $objPHPExcel = $objReader->load($filePath);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
            $highestColumn = $objWorksheet->getHighestColumn();
            $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
            $colums = array();
            $data = array();
            $excelAllId = array();
            $excelIdRow = array();
            $execlAllShopLinkedId = array();
            for($i=0;$i<$highestColumnIndex;$i++){
                $cValue = trim($objWorksheet->getCellByColumnAndRow($i,1)->getValue());
                switch ($cValue) {
                    case self::PRODUCT_SAP_CODE : $colums[$i] = "sap_code"; break;
                    case self::PRODUCT_NAME : $colums[$i] = "pname"; break;
                    case self::PRODUCT_GROUP : $colums[$i] = "product_group"; break;
                    case self::PRODUCT_BRAND : $colums[$i] = 'product_brand'; break;
                    case self::PRODUCT_PROXY_FLAG : $colums[$i] = "product_proxy_flag"; break;
                    case self::PRODUCT_BINNING : $colums[$i] = "product_binning"; break;
                    case self::PRODUCT_SELL_PICK : $colums[$i] = "product_sell_pick"; break;
                    case self::PRODUCT_ATTRIBUTE : $colums[$i] = "product_attribute"; break;
                    case self::PRODUCT_SUPPLIER_CODE : $colums[$i] = "vendor_code"; break;
                    case self::PRODUCT_SUPPLY_ADDRESS : $colums[$i] = "zzwerk_code"; break;
                    case self::PRODUCT_BATCH : $colums[$i] = "zzlgort_code"; break;
                    default : $error[3][] = $cValue; break;
                }
            }
            //检测Excel中的基本信息是否存在
            $dataCount = $highestRow - 1;
            if(count($colums) == 0) {
                $error[5] = "没有表头";
            }
            else if(!in_array('sap_code',$colums)){
                $error[2] = "表头中商品SAP编码不存在";
            }
            else if($dataCount <= 0){
                $error[6] = "Excel文件中没有数据";
            }
            else if(count($error)==0){
                for ($i=2;$i<=$highestRow;$i++){
                    $colkey = array_search('sap_code');
                    $shopLinkedIdValue = trim($objWorksheet->getCellByColumnAndRow($colkey,$i)->getValue());
                    if(!$shopLinkedIdValue) {
                        continue;
                    }
                    if(in_array($shopLinkedIdValue,$execlAllShopLinkedId)){
                        $error[7][$shopLinkedIdValue]['duplicate'] = true;
                        $error[7][$shopLinkedIdValue]['excelRow'][] = $i;
                        $execlAllShopLinkedId[$i] = $shopLinkedIdValue;
                        $error[7][$shopLinkedIdValue]['noId'] = true;
                    }else {
                        $excelIdRow[$shopLinkedIdValue] = $i;
                        $execlAllShopLinkedId[$i] = $shopLinkedIdValue;
                    }
                }
                $dealMultiple = ceil($dataCount / 1000);
                $allProduct = array();
                for($i=0;$i<$dealMultiple;$i++){
                    $offset = $i*1000+2;
                    $max = ($i+1)*1000+1;
                    $max = ($max > $dataCount) ? $highestRow : $max;
                    $allShopLinkedId = array();
                    for($j=$offset;$j<=$max;$j++){
                        if($execlAllShopLinkedId[$j]){
                            $allShopLinkedId[] = $execlAllShopLinkedId[$j];
                        }
                    }
                    // 根据SAP商品编码查询在库中的记录数.
                    $dbShopProducts = $this->getShopLinkedByIds($allShopLinkedId);                    for($j=$offset;$j<=$max;$j++){
                        $product = array();
                        for($k=0;$k<$highestColumnIndex;$k++){
                            $tempV = trim($objWorksheet->getCellByColumnAndRow($k,$j)->getValue());
                            if($tempV && $tempV != '') {
                                $product[$colums[$k]] = $tempV;
                            }
                        }
                        //获取文件中的SAP编码
                        $id = $product['sap_code'];
                        if(!$id){
                            continue;
                        }
                        //检测商品SAP编码是否已经存在
                        if(!in_array($id,$dbShopProducts)){
                            $allProduct[$id] = $product;
                        }else{
                            $error[7][$id]['hasId'] = true;
                        }
                        //商品名是否为空
                        if(!isset($product['pname'])){
                            $error[7][$id]['emptyName'] = true;
                        }
                        //商品类目(商品组)是否为空
                        if(!isset($product['product_group'])){
                            $error[7][$id]['emptyProductGroup'] = true;
                        }
                        //产品层次(品牌)是否为空
                        if(!isset($product['product_brand'])){
                            $error[7][$id]['emptyProductBrand'] = true;
                        }
                        //经代销标志是否为空
                        if(!isset($product['product_proxy_flag'])){
                            $error[7][$id]['emptyProductProxyFlag'] = true;
                        }
                        //装箱清单是否为空
                        if(!isset($product['product_binning'])){
                            $error[7][$id]['emptyProductBinning'] = true;
                        }
                        //先销后采标识是否为空
                        if(!isset($product['product_sell_pick'])){
                            $error[7][$id]['emptyProductSellPick'] = true;
                        }
                        //商品属性是否为空
                        if(!isset($product['product_attribute'])){
                            $error[7][$id]['emptyProductAttribute'] = true;
                        }
                        //供应商编码是否为空
                        if(!isset($product['vendor_code'])){
                            $error[7][$id]['emptyVendorCode'] = true;
                        }
                        //供应地点是否为空
                        if(!isset($product['zzwerk_code'])){
                            $error[7][$id]['emptyZzwerkCode'] = true;
                        }
                        //库区是否为空
                        if(!isset($product['zzlgort_code'])){
                            $error[7][$id]['emptyZzlgortCode'] = true;
                        }
                        if(isset($error[7][$id])){
                            $error[7][$id]['excelRow'] = $j;
                        }
                    }
                }
            }
        }
        $resultInfo['fileName'] = $fileName;
        //返回错误信息
        if(count($error)>0){
            if(isset($error[1])){
                $resultInfo['type'] = 1;
                $resultInfo['msg'] = $error[1];
            }else if(isset($error[2])){
                $resultInfo['type'] = 2;
                $resultInfo['msg'] = $error[2];
            }else if(isset($error[3])){
                $resultInfo['type'] = 3;
                $resultInfo['msg'] = '表头【'.implode(',',$error[3]).'】不存在';
            }else if(isset($error[4])){
                $resultInfo['type'] = 4;
                $resultInfo['msg'] = $error[4];
            }else if(isset($error[6])){
                $resultInfo['type'] = 6;
                $resultInfo['msg'] = $error[6];
            }else if(isset($error[7])){
                $excelName = null;
                $objPHPWriteExcel = new PHPExcel();
                $objPHPWriteExcel->getProperties()->setCreator("yuer")
                ->setLastModifiedBy("yuer")->setTitle("")->setSubject("")
                ->setDescription("")->setKeywords("")->setCategory("");
                $prefix = substr($fileName,0,strrpos($fileName,'.'));
                $suffix = substr($fileName,strrpos($fileName,'.'));
                $excelName = date("Y_m_d_H_i_s").'_'.mt_rand(1,99).'_'.$prefix.'ErrorReport'.$suffix;
                $excelName = Base_Tool_Pinyin::getPinyin($excelName);
                $objPHPWriteExcel->setActiveSheetIndex(0);
                $activeSheet = $objPHPWriteExcel->getActiveSheet();
                $activeSheet->setTitle('错误报告');
                $activeSheet->setCellValueByColumnAndRow(0,1,self::PRODUCT_SAP_CODE);
                $activeSheet->setCellValueByColumnAndRow(1,1,'原excel行号');
                $activeSheet->setCellValueByColumnAndRow(2,1,'第几行编码存在重复');
                $activeSheet->setCellValueByColumnAndRow(3,1,self::PRODUCT_NAME);
                $activeSheet->setCellValueByColumnAndRow(4,1,self::PRODUCT_GROUP);
                $activeSheet->setCellValueByColumnAndRow(5,1,self::PRODUCT_BRAND);
                $activeSheet->setCellValueByColumnAndRow(6,1,self::PRODUCT_PROXY_FLAG);
                $activeSheet->setCellValueByColumnAndRow(7,1,self::PRODUCT_BINNING);
                $activeSheet->setCellValueByColumnAndRow(8,1,self::PRODUCT_SELL_PICK);
                $activeSheet->setCellValueByColumnAndRow(9,1,self::PRODUCT_ATTRIBUTE);
                $activeSheet->setCellValueByColumnAndRow(10,1,self::PRODUCT_SUPPLIER_CODE);
                $activeSheet->setCellValueByColumnAndRow(11,1,self::PRODUCT_SUPPLY_ADDRESS);
                $activeSheet->setCellValueByColumnAndRow(12,1,self::PRODUCT_BATCH);
                $activeSheet->setCellValueByColumnAndRow(13,1,'其他原因');
                $activeSheet->getColumnDimensionByColumn(0)->setWidth(15);
                $activeSheet->getColumnDimensionByColumn(1)->setWidth(20);
                $activeSheet->getColumnDimensionByColumn(2)->setWidth(20);
                $activeSheet->getColumnDimensionByColumn(3)->setWidth(20);
                $activeSheet->getColumnDimensionByColumn(4)->setWidth(20);
                $activeSheet->getColumnDimensionByColumn(5)->setWidth(20);
                $activeSheet->getColumnDimensionByColumn(6)->setWidth(20);
                $activeSheet->getColumnDimensionByColumn(7)->setWidth(20);
                $activeSheet->getColumnDimensionByColumn(8)->setWidth(20);
                $activeSheet->getColumnDimensionByColumn(9)->setWidth(20);
                $activeSheet->getColumnDimensionByColumn(10)->setWidth(20);
                $activeSheet->getColumnDimensionByColumn(11)->setWidth(20);
                $activeSheet->getColumnDimensionByColumn(12)->setWidth(20);
                $activeSheet->getColumnDimensionByColumn(13)->setWidth(20);
                $writeExcelIndex = 2;
                foreach ($error[7] as $pId=>$pInfo){
                    if(isset($pInfo['hasId'])){
                        $activeSheet->setCellValueByColumnAndRow(0,$writeExcelIndex,$pId.'-此供应商编码已经存在');
                    } else {
                        $activeSheet->setCellValueByColumnAndRow(0,$writeExcelIndex,$pId);
                    }
                    $activeSheet->setCellValueByColumnAndRow(1,$writeExcelIndex,$pInfo['excelRow']);
                    if(isset($pInfo['duplicate'])){
                        $activeSheet->setCellValueByColumnAndRow(2,$writeExcelIndex,$excelIdRow[$pId]);
                    }
                    if(isset($pInfo['emptyName'])){
                        $activeSheet->setCellValueByColumnAndRow(3,$writeExcelIndex,'-为空');
                    }
                    if(isset($pInfo['emptyProductGroup'])){
                        $activeSheet->setCellValueByColumnAndRow(4,$writeExcelIndex,'-为空');
                    }
                    if(isset($pInfo['emptyProductBrand'])){
                        $activeSheet->setCellValueByColumnAndRow(5,$writeExcelIndex,'-为空');
                    }
                    if(isset($pInfo['emptyProductProxyFlag'])){
                        $activeSheet->setCellValueByColumnAndRow(6,$writeExcelIndex,'-为空');
                    }
                    if(isset($pInfo['emptyProductBinning'])){
                        $activeSheet->setCellValueByColumnAndRow(7,$writeExcelIndex,'-为空');
                    }
                    if(isset($pInfo['emptyProductSellPick'])){
                        $activeSheet->setCellValueByColumnAndRow(8,$writeExcelIndex,'-为空');
                    }
                    if(isset($pInfo['emptyProductAttribute'])){
                        $activeSheet->setCellValueByColumnAndRow(9,$writeExcelIndex,'-为空');
                    }
                    if(isset($pInfo['emptyVendorCode'])){
                        $activeSheet->setCellValueByColumnAndRow(10,$writeExcelIndex,'-为空');
                    }
                    if(isset($pInfo['emptyZzwerkCode'])){
                        $activeSheet->setCellValueByColumnAndRow(11,$writeExcelIndex,'-为空');
                    }
                    if(isset($pInfo['emptyZzlgortCode'])){
                        $activeSheet->setCellValueByColumnAndRow(12,$writeExcelIndex,'-为空');
                    }
                    if(isset($pInfo['other'])){
                        $activeSheet->setCellValueByColumnAndRow(13,$writeExcelIndex,$pInfp['other']);
                    }
                    $writeExcelIndex++;
                }
                $objWriter = PHPExcel_IOFactory::createWriter($objPHPWriteExcel, 'Excel5');
                $excelPath = FILE_PATH.DS.'feedback'.DS.$excelName;
                $objWriter->save($excelPath);
                $resultInfo['type'] = 7;
                $resultInfo['msg'] = $fileName."文件中存在错误";
                $resultInfo['errorReport'] = $excelName;
                // 日志操作,暂时空着
            }
        }else{
            //导入数据
            $logIds = '';
            $i = 0;
            foreach ($allProduct as $pId => $pInfo){
                $updateProductSql = 'insert into yr_product set ';
                if(isset($pInfo['pname']) && trim($pInfo['pname'])){
                    $updateProductSql = $updateProductSql.'pname=\''.str_replace('\'','\'\'',$pInfo['pname']).'\',';
                }
                //如果SAP编码不足18位,则用0从左开始补全
                if(isset($pInfo['sap_code'])){
                    if(strlen($pInfo['sap_code'])<18){
                        $pInfo['sap_code'] = str_pad($pInfo['sap_code'], 18, "0", STR_PAD_LEFT);
                        $updateProductSql = $updateProductSql.'sap_code=\''.str_replace('\'','\'\'',$pInfo['sap_code']).'\',';
                    }
                }
                if(isset($pInfo['product_group'])){
                    $updateProductSql = $updateProductSql.'product_group=\''.$pInfo['product_group'].'\',';
                }
                if(isset($pInfo['product_brand'])){
                    $updateProductSql = $updateProductSql.'product_brand=\''.$pInfo['product_brand'].'\',';
                }
                if(isset($pInfo['product_proxy_flag'])){
                    $updateProductSql = $updateProductSql.'product_proxy_flag=\''.$pInfo['product_proxy_flag'].'\',';
                }
                if(isset($pInfo['product_binning'])){
                    $updateProductSql = $updateProductSql.'product_binning=\''.$pInfo['product_binning'].'\',';
                }
                if(isset($pInfo['product_sell_pick'])){
                    $updateProductSql = $updateProductSql.'product_sell_pick=\''.$pInfo['product_sell_pick'].'\',';
                }
                if(isset($pInfo['product_attribute'])){
                    $updateProductSql = $updateProductSql.'product_attribute=\''.$pInfo['product_attribute'].'\',';
                }
                if(isset($pInfo['vendor_code'])){
                    $updateProductSql = $updateProductSql.'vendor_code=\''.$pInfo['vendor_code'].'\',';
                }
                if(isset($pInfo['zzwerk_code'])){
                    $updateProductSql = $updateProductSql.'zzwerk_code=\''.$pInfo['zzwerk_code'].'\',';
                }
                if(isset($pInfo['zzlgort_code'])){
                    $updateProductSql = $updateProductSql.'zzlgort_code=\''.$pInfo['zzlgort_code'].'\'';
                }
                //最终的SQL语句
                $result = $this->excuteMultiInsertSql($updateProductSql);
            }
            $resultInfo['type'] = 8;
            $resultInfo['msg'] = "导入商品基本信息成功";
            /*
             * // 日志操作.
             * $content = '批量新建商品导入操作成功:导入的供应商品编码有->';
             * $logData['content'] = $content.$logIds;
             */
        }
        return $resultInfo;
    }
PHP 相关文章推荐
PHP5中MVC结构学习
Oct 09 PHP
桌面中心(三)修改数据库
Oct 09 PHP
用Flash图形化数据(二)
Oct 09 PHP
一个PHP模板,主要想体现一下思路
Dec 25 PHP
PHP不用第三变量交换2个变量的值的解决方法
Jun 02 PHP
配置php网页显示各种语法错误
Sep 23 PHP
PHP中的按位与和按位或操作示例
Jan 27 PHP
php ci框架中加载css和js文件失败的解决方法
Mar 03 PHP
递归删除一个节点以及该节点下的所有节点示例
Mar 19 PHP
必须收藏的php实用代码片段
Feb 02 PHP
php 读取输出其他文件的实现方法
Jul 26 PHP
PHP延迟静态绑定使用方法实例解析
Sep 05 PHP
php生成excel列序号代码实例
Dec 24 #PHP
php jquery 多文件上传简单实例
Dec 23 #PHP
php安装xdebug/php安装pear/phpunit详解步骤(图)
Dec 22 #PHP
PHP变量的定义、可变变量、变量引用、销毁方法
Dec 20 #PHP
部署PHP项目应该注意的几点事项分享
Dec 20 #PHP
php对二维数组进行排序的简单实例
Dec 19 #PHP
thinkphp的CURD和查询方式介绍
Dec 19 #PHP
You might like
PHP 存储文本换行实现方法
2010/01/05 PHP
如何利用PHP执行.SQL文件
2013/07/05 PHP
PHP实现简单的协程任务调度demo示例
2020/02/01 PHP
JavaScript中this关键字使用方法详解
2007/03/08 Javascript
javascript 写类方式之一
2009/07/05 Javascript
jquery 1.4.2发布!主要是性能与API
2010/02/25 Javascript
用jquery实现的模拟QQ邮箱里的收件人选取及其他效果(一)
2011/01/06 Javascript
JavaScript 函数replace深入了解
2013/03/14 Javascript
onkeypress字符按键兼容所有浏览器使用介绍
2013/04/24 Javascript
ExtJS实现文件下载的方法实例
2013/11/09 Javascript
根据表格中的某一列进行排序的javascript代码
2013/11/29 Javascript
jQuery增加自定义函数的方法
2015/07/18 Javascript
Vue.js 父子组件通讯开发实例
2016/09/06 Javascript
jQuery中fadein与fadeout方法用法示例
2016/09/16 Javascript
使用JavaScriptCore实现OC和JS交互详解
2017/03/28 Javascript
[01:10]DOTA2亚洲邀请赛 征战号角响彻全场
2015/01/06 DOTA
[02:08]2018年度CS GO枪械皮肤设计大赛优秀作者-完美盛典
2018/12/16 DOTA
Ubuntu 14.04+Django 1.7.1+Nginx+uwsgi部署教程
2014/11/18 Python
Python操作MongoDB数据库PyMongo库使用方法
2015/04/27 Python
运用TensorFlow进行简单实现线性回归、梯度下降示例
2018/03/05 Python
基于Python新建用户并产生随机密码过程解析
2019/10/08 Python
python 动态调用函数实例解析
2019/10/21 Python
pytorch 实现在预训练模型的 input上增减通道
2020/01/06 Python
Python Selenium参数配置方法解析
2020/01/19 Python
Python super()方法原理详解
2020/03/31 Python
Eastbay官网:美国最大的运动鞋网络零售商
2016/07/27 全球购物
S’well Bottle保温杯官网:绝缘不锈钢水瓶
2018/05/09 全球购物
super()与this()的区别
2016/01/17 面试题
介绍一下Transact-SQL中SPACE函数的用法
2015/09/01 面试题
打架检讨书400字
2014/01/17 职场文书
店面销售职位的职责
2014/03/09 职场文书
工伤赔偿协议书
2014/04/15 职场文书
2016新教师岗前培训心得体会
2016/01/08 职场文书
教你用Python写一个植物大战僵尸小游戏
2021/04/25 Python
Vue vee-validate插件的简单使用
2021/06/22 Vue.js
mysql使用instr达到in(字符串)的效果
2022/04/03 MySQL