記一次yii2 上傳文件


1 view渲染

 

<form action="../src/website/import/report-flow" method="post" enctype="multipart/form-data">
    </br>
    type<input type="text" name="type"  />
    year<input type="text" name="year"  />
    month<input type="text" name="month"  />
<input type="file" name="fileExcel" id="fileExcel" />

<br />
<input type="submit" name="submit" value="Submit" />
</form>

 

 

2 上傳接口

 src/modules/website/controllers/ImportController.php

    /**
     * @author Anana
     * 上傳商銷/盒 文件 異步處理
     */
    public  function actionReportFlow()
    {
        $uploadFile = UploadedFile::getInstanceByName ('fileExcel');
        $type  = intval(parent::getPostParam ('type')); // 文件上傳類型
        $year  = intval(parent::getPostParam('year'));//
        $month = intval(parent::getPostParam('month'));//
        if($month<10){
            $month = '0'.$month;
        }
        $accountRoleId= \Yii::$app->session['accountRoleRow']['account_role_id'];

        if(!in_array($type,array('1','2'))){
            parent::apiReturn ( 1, [ ], '請先選擇要上傳的文件類型' );
        }else if(!$year){
            parent::apiReturn ( 1, [ ], '請選擇年' );
        }else if(!$month || $month > 12 ){
            parent::apiReturn ( 1, [ ], '請選擇月' );
        }else if($uploadFile){
            $fileExt = $uploadFile->getExtension (); // 文件后綴
            $size = $uploadFile->size;//文件大小
            if (! in_array ( $fileExt, array('xlsx','xls','csv') )) {
                $reason [] = '上傳的文件后綴名必須為xlsx、xls、csv';
            }else if($size > 20*1024*1024){
                $reason [] = '文件大小不能超過20M';
            }else{
                $fileName = date('Ymdhis').'_'.$accountRoleId;
                if($type==1){
                    //商銷/盒數據
                    $dir = 'report_flow_month';
                }else {
                    //終端開戶明細
                    $dir = 'open_accounts_month';
                }
                $fileName = $fileName.'.'.$fileExt;
                $companyCode = \Yii::$app->session['companyRow']['code'];
                $updateMonth =date('Y-m-00',strtotime("{$year}-{$month}"));
                $buildsDir = dirname(\yii::$app->basePath)."/builds/{$companyCode}/{$dir}/$updateMonth";
                //創建生成目錄文件夾
                if(!file_exists($buildsDir)){
                    mkdir($buildsDir,0777,true);
                }
                $csvPath = $buildsDir.'/'.$fileName;
                $rs = $uploadFile->saveAs($csvPath);//文件另存為
                if($rs){
                    $reportDaySalesFlowUploadLogModel =  new ReportDaySalesFlowUploadLogModel();
                    $reportDaySalesFlowUploadLogModel->file_type    = $type;
                    $reportDaySalesFlowUploadLogModel->role_id      = $accountRoleId;
                    $reportDaySalesFlowUploadLogModel->new_file_name= $fileName;
                    $reportDaySalesFlowUploadLogModel->create_time  = date("Y-m-d H:i:s");
                    $reportDaySalesFlowUploadLogModel->company      = $companyCode;
                    $reportDaySalesFlowUploadLogModel->update_month = $updateMonth;
                    $rs = $reportDaySalesFlowUploadLogModel->insert();
                    if(!$rs){
                        parent::apiReturn ( 1, $jsonData, '上傳日志更新失敗' );
                    }
                    parent::apiReturn ( 0, [ ], '上傳成功' );
                }else{
                    $reason []  = '上傳文件失敗' . $uploadFile->error;
                }
            }
            $jsonData = [ ];
            if ($reason) {
                $jsonData ['errorList'] =  implode ( ' ', $reason );
                parent::apiReturn ( 1, $jsonData, '錯誤信息提示' );
            }
        }else{
            parent::apiReturn ( 1, [ ], '上傳失敗' );
        }
    }

 3 上傳以后處理數據

 /**
     * 1 刪除report_day_sales_flow_month表當月的老數據
     * 2 插入report_day_sales_flow_month表當月新數據
     *
     *
     * $fileName    文件名
     * $fileLogId   文件id
     */
    private  function  _updateReportDaySalesFlowMonth($fileName,$fileLogId,$updateMonth)
    {
        $connection = $this->_selectDb();

        $buildsDir = dirname(\yii::$app->basePath)."/builds/yiling/xlsx/report_flow_month/$fileName";
        if(!file_exists($buildsDir)){
            echo  "FILE NOT FOUND 找不到文件 \n ";
            return;
        }
        $objReader = \PHPExcel_IOFactory::createReader('CSV');
        $objReader->setReadDataOnly(true);// //只讀去數據,忽略里面各種格式等(對於Excel讀去,有很大優化)
        $phpExcel = \PHPExcel_IOFactory::load ($buildsDir); // 自動判斷Excel版本解析讀取


        $sheet = $phpExcel->getSheet ( 0 );
        $collectionList = [ ]; // 初始化數據集合
        $errorData = [ ]; // 導入的錯誤信息數據 有錯誤數據無法導入
        $errorArray = [ ];
        // 讀取Excel數據行記錄
        $totalRow = $sheet->getHighestRow(); // 取得總行數

        $thisTime = date("Y-m-d H:i:s");
        for($i = 2; $i <= $totalRow; ++$i) {
            $year = $sheet->getCellByColumnAndRow(0, $i)->getValue();
            $month = $sheet->getCellByColumnAndRow(1, $i)->getValue();
            $row['year_str'] = $year;
            $row['month_str'] = $month;
            $year_and_month = date("Y-m-00",strtotime(intval($year).'-'.intval($month)));
            $row['update_month'] = $year_and_month;
            $row['dept'] =$sheet->getCellByColumnAndRow(2, $i)->getValue();//部門
            $row['business_dept'] =$sheet->getCellByColumnAndRow(3, $i)->getValue();//業務部門
            $row['business_type'] =$sheet->getCellByColumnAndRow(4, $i)->getValue();//業務類型
            $row['region_description'] =$sheet->getCellByColumnAndRow(5, $i)->getValue();//省區
            $row['bussiness_region_description'] =$sheet->getCellByColumnAndRow(6, $i)->getValue();//業務省區
            $row['region_named_code'] =$sheet->getCellByColumnAndRow(7, $i)->getValue();//區辦代碼
            $row['region_named'] =$sheet->getCellByColumnAndRow(8, $i)->getValue();//區辦
            $row['parent_role_number'] =$sheet->getCellByColumnAndRow(9, $i)->getValue();//主管工號
            $row['parent_role_name'] =$sheet->getCellByColumnAndRow(10, $i)->getValue();//主管姓名
            $row['role_number'] =$sheet->getCellByColumnAndRow(11, $i)->getValue();//代表工號
            $row['role_name'] =$sheet->getCellByColumnAndRow(12, $i)->getValue();//代表姓名
            $row['client_number'] =$sheet->getCellByColumnAndRow(13, $i)->getValue();//終端代碼
            $row['client_name'] =$sheet->getCellByColumnAndRow(14, $i)->getValue();//終端名稱
            $row['province'] =$sheet->getCellByColumnAndRow(15, $i)->getValue();//省份
            $row['city'] =$sheet->getCellByColumnAndRow(16, $i)->getValue();//城市
            $row['district'] =$sheet->getCellByColumnAndRow(17, $i)->getValue();//區縣
            $row['hospital_type'] =$sheet->getCellByColumnAndRow(18, $i)->getValue();//醫院類型
            $row['custom_field_1'] =$sheet->getCellByColumnAndRow(19, $i)->getValue();//以嶺級別
            $row['nation_level'] =$sheet->getCellByColumnAndRow(20, $i)->getValue();//國家等級
            $row['contract_type'] =$sheet->getCellByColumnAndRow(21, $i)->getValue();//承包類型
            $row['custom_field_2'] =$sheet->getCellByColumnAndRow(22, $i)->getValue();//管理級別1
            $row['group_name'] =$sheet->getCellByColumnAndRow(23, $i)->getValue();//品種
            $row['goods_number'] =$sheet->getCellByColumnAndRow(24, $i)->getValue();//產品代碼
            $row['goods_name_spec'] =$sheet->getCellByColumnAndRow(25, $i)->getValue();//產品名稱與品規
            $row['purchase'] =$sheet->getCellByColumnAndRow(26, $i)->getValue();//商銷/盒
            $row['create_time'] =$thisTime;//導入時間
            $row['file_log_id'] =$fileLogId;
            $data[] = $row;
        }
        //釋放內存
        $sheet = $phpExcel =$phpExcel= null;
        $fields = [
            'year_str',
            'month_str',
            'update_month',
            'dept',
            'business_dept',
            'business_type',
            'region_description',
            'bussiness_region_description',
            'region_named_code',
            'region_named',
            'parent_role_number',
            'parent_role_name',
            'role_number',
            'role_name',
            'client_number',
            'client_name',
            'province',
            'city',
            'district',
            'hospital_type',
            'custom_field_1',
            'nation_level',
            'contract_type',
            'custom_field_2',
            'group_name',
            'goods_number',
            'goods_name_spec',
            'purchase',
            'create_time',
            'file_log_id'
        ];
        $rs = $connection->createCommand()->batchInsert('report_day_sales_flow_month',$fields,$data)->execute();
        return $rs;
    }

 4 同步上傳

    /**
     * @author Anana
     * http://localhost/src/website/import/region-named
     * 上傳以嶺區辦
     */
    public  function  actionRegionNamed()
    {
        $uploadFile = UploadedFile::getInstanceByName ('fileExcel');
        if(!$uploadFile){
            parent::apiReturn ( 1, [ ], '上傳失敗' );
        }
        $fileExt = $uploadFile->getExtension (); // 文件后綴
        $size = $uploadFile->size;//文件大小
        if (! in_array ( $fileExt, array('xlsx','xls','csv') )) {
            parent::apiReturn ( 1, [ ], '上傳的文件后綴名必須為xlsx、xls、csv' );
        }
        if($size > 20*1024*1024){
            parent::apiReturn ( 1, [ ], '文件大小不能超過20M' );
        }
        $objReader = \PHPExcel_IOFactory::createReader('CSV');
        $objReader->setReadDataOnly(true);// //只讀去數據,忽略里面各種格式等(對於Excel讀去,有很大優化)
        $phpExcel = \PHPExcel_IOFactory::load ( $uploadFile->tempName ); // 自動判斷Excel版本解析讀取
        $sheet = $phpExcel->getSheet ( 0 );
        $collectionList = [ ]; // 初始化數據集合

        // 讀取Excel數據行記錄
        $totalRow = $sheet->getHighestRow (); // 取得總行數

        //所有部門
        $deptArr = array(
            1 => '醫院一部',
            2 => '醫院二部',
            3 => '社區部',
            4 => '城鄉部'
        );
        $deptFlipArr = array_flip($deptArr);
        //所有業務部門
        $bussinessDeptArr = array(
            1=>'醫院一部',
            2=>'腫瘤產品部',
            3=>'醫院二部',
            4 =>'社區部',
            5 =>'城鄉部',
            6=>'城鄉二部'
        );
        $bussinessDeptFlipArr = array_flip($bussinessDeptArr);

        //所有省區
        $regionArea = RegionAreaModel::find()->select(['region_area_id','name'])->where(['is_valid'=>VALID])->asArray()->all();
        foreach ($regionArea as $v){
            $regionAreaArr[$v['region_area_id']] = $v['name'];
        }
        $regionAreaFlipArr = array_flip($regionAreaArr);

        //所有業務省區
        $bussinessProvince = BussinessProvinceModel::find()->select(['bussiness_province_id','bussiness_province'])->where(['is_valid'=>VALID])->asArray()->all();
        foreach ($bussinessProvince as $v){
            $bussinessProvinceArr[$v['bussiness_province_id']] = $v['bussiness_province'];
        }
        $bussinessProvinceFlipArr = array_flip($bussinessProvinceArr);

        $hasError = False;
        $roleId = \Yii::$app->session['accountRoleRow']['account_role_id'];
        $thisTime = date("Y-m-d H:i:s");




        // 跳過標題行
        for($i = 2; $i <= $totalRow; ++ $i) {
            $error = array();
            $dept = trim ( $sheet->getCellByColumnAndRow ( 0, $i )->getValue () ); // 部門
            $bussinessDept = trim ( $sheet->getCellByColumnAndRow ( 1, $i )->getValue () ); //業務部門
            $regionArea = trim ( $sheet->getCellByColumnAndRow ( 2, $i )->getValue () ); //省區
            $bussinessProvince = trim ( $sheet->getCellByColumnAndRow ( 3, $i )->getValue () ); //業務省區
            $regionNamedCode = trim ( $sheet->getCellByColumnAndRow ( 4, $i )->getValue () ); //區辦代碼
            $regionNamed = trim ( $sheet->getCellByColumnAndRow ( 5, $i )->getValue () ); //區辦


            if(!in_array($dept,$deptArr)){
                $hasError = $hasError | true;
                $error[] = '【部門】不存在 ';
            }else{
                $row['dept_id'] = $deptFlipArr[$dept];
            }
            if(!in_array($bussinessDept,$bussinessDeptArr)){
                $hasError = $hasError | true;
                $error[] = '【業務部門】不存在 ';
            }else{
                $row['bussiness_dept_id'] = $bussinessDeptFlipArr[$bussinessDept];
            }
            if(!in_array($regionArea,$regionAreaArr)){
                $hasError = $hasError | true;
                $error[] = '【省區】不存在 ';
            }else{
                $row['region_area_id'] = $regionAreaFlipArr[$regionArea];
            }

            if(!in_array($bussinessProvince,$bussinessProvinceArr)){
                $hasError = $hasError | true;
                $error[] = '【業務省區】不存在 ';
            }else{
                $row['bussiness_province_id'] = $bussinessProvinceFlipArr[$bussinessProvince];
            }

            if(mb_strlen($regionNamedCode)>20){
                $hasError = $hasError | true;
                $error[] = '【區辦代碼】太長了';
            }
            if(!$regionNamed || mb_strlen($regionNamed)>20){
                $hasError = $hasError | true;
                $error[] = '【區辦】未填或太長了';
            }else{
                $regionNamedOne = RegionNamedModel::find()->select(['region_named_id'])->where(['region_named'=>$regionNamed, 'is_valid'=>VALID])->one();
                if($regionNamedOne){
                    $hasError = $hasError | true;
                    $error[] = '此【區辦】已存在,不可重復添加';
                }
            }
            //$row['dept'] =$dept;
            //$row['bussiness_dept']=$bussinessDept;
            //$row['region_area'] = $regionArea;
            //$row['bussiness_province'] = $bussinessProvince;
            $row['region_named_code'] =$regionNamedCode;
            $row['region_named'] = $regionNamed;

            $row['role_id'] = $roleId;
            $row['create_time'] = $thisTime;

            if(isset($error) && $error ){
                $row['error'] = implode(':',$error);
                $sheet->setCellValueExplicitByColumnAndRow ( 6, $i,$row['error']);
            }
            $collectionList[] = $row;
        }


        $fileName = 'region_named_error';
        $fileName = $fileName.'.xlsx';
        $companyCode = \Yii::$app->session['companyRow']['code'];
        $buildsDir = dirname(\yii::$app->basePath)."/builds/{$companyCode}/region_named_error";
        //創建生成目錄文件夾
        if(!file_exists($buildsDir)){
            mkdir($buildsDir,0777,true);
        }
        $csvPath = $buildsDir.'/'.$fileName;

        //釋放內存
        $bussinessDeptFlipArr = $bussinessDeptArr = $bussinessProvinceFlipArr=$bussinessProvinceArr = null;

        //上傳數據正確 插入數據表
        if($hasError){
            //釋放內存
            $collectionList = null;
            //上傳數據錯誤,寫入文件
            $phpExcelWriter = \PHPExcel_IOFactory::createWriter ( $phpExcel, 'Excel5' );
            $rs = $phpExcelWriter->save ( $csvPath );
            //$rs = $uploadFile->saveAs($csvPath);//文件另存為
            parent::apiReturn ( 1, [ ], '上傳數據有錯誤,已生成錯誤數據文件,請下載並按提示修改' );
        }else{

            //釋放內存
            $phpExcel = null;
            \Yii::$app->params ['dbSelect'] = 'company'; // 切換到 company 數據庫
            \Yii::$app->params ['dsnSelect'] = 51;//yiling
            $connection = \Yii::$app->companydb;
            //$queryBuilder = $connection->queryBuilder;
            $fields = ['dept_id','bussiness_dept_id','region_area_id','bussiness_province_id','region_named_code','region_named','role_id','create_time'];
            $rs = $connection ->createCommand()->batchInsert(RegionNamedModel::tableName(),$fields, $collectionList)->execute();
            if($rs){
                //刪除錯誤文件
                unlink($csvPath);
                parent::apiReturn ( 0, [ ], '導入數據成功' );
            }
            parent::apiReturn ( 1, [ ], '導入數據失敗,請聯系程序員');
        }
    }
    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM