zoukankan      html  css  js  c++  java
  • tp 使用phpexcel导入表格并将表格图片上传数据库

    声明:phpexcel 的坑,上传文件必须是  xls 格式的,走的是excel5的类,如果是别的格式则报错,图片处理方法不存在

    xls模板内容:

     以下是代码:

     <div class="layui-inline">
           <button type="button" class="layui-btn layui-btn-normal" id="test3"><i class="layui-icon"></i>上传文件</button>
     </div>
    
    
    <script>
        layui.use(['upload', 'element'], function(){
            var $ = layui.jquery
                ,upload = layui.upload
                ,element = layui.element;
    
            upload.render({
                elem: '#test3'
                ,url: "{:url('/Nqishare/import')}"
                ,accept: 'file'
                ,before: function(obj){
                    console.log(this.item);
                }
                ,done: function(res){
                    if(res.status==1){
                        layer.msg(res.msg, {
                            time: 3000, //6s后自动关闭
                            icon:1
                        });
                    }else{
                        layer.msg(res.msg, {
                            time: 3000, //6s后自动关闭
                            icon:2
                        });
                    }
                    console.log(res)
                }
            });
    
        });
    </script>
    

      

    后端:

    tp6  将phpexce放到vendor下

    require_once(root_path() . '/vendor/phpexcel/PHPExcel.php');
    require_once(root_path() . '/vendor/phpexcel/PHPExcel/IOFactory.php');

    //表格导入
        public function import()
        {
            set_time_limit(0);
            if (!empty($_FILES)) {
                //获取表单上传文件
                if (!empty($_FILES['file']['error'])) {
                    return array('status' => 0, 'msg' => '文件上传失败');
                }
                $tmp_file = $_FILES ['file'] ['tmp_name'];
                $file_types = explode(".", $_FILES ['file'] ['name']);
                $file_type = $file_types [count($file_types) - 1];
                /*判别是不是.xls文件,判别是不是excel文件*/
                if (strtolower($file_type) != "xlsx" && strtolower($file_type) != "xls") {
                    return array('status' => 0, 'msg' => '不是Excel文件,重新上传');
                }
                /*设置上传路径*/
                /*百度有些文章写的上传路径经过编译之后斜杠不对。不对的时候用大写的DS代替,然后用连接符链接就可以拼凑路径了。*/
                $savePath = root_path() . 'public/uploads/';/*以时间来命名上传的文件*/
                $str = date('Ymdhis');
                $file_name = $str . "." . $file_type;
                /*是否上传成功*/
                if (!copy($tmp_file, $savePath . $file_name)) {
                    return array('status' => 0, 'msg' => '上传失败');
                }
                /*
                *注意:这里调用执行了第三步类里面的read函数,把Excel转化为数组并返回给$res,再进行数据库写入
                */
                $res = $this->read($savePath . $file_name, "UTF-8", $file_type);//传参,判断office2007还是office2003
    
                Db::startTrans();
                try {
                    /*对生成的数组进行数据库的写入*/
                    foreach ($res as $k => $v) {
                        //如果导入数据为空,跳过
                        if (empty(array_filter($v))) continue;
                        if ($k > 1) {
                            $isspe = $v[13] == "是"?1:0;
                           // $res = DB::name('nqi_company')->field('company_id')->where(['company_contact_phone' => $v[7]])->find();
                             $res = DB::name('nqi_company')->field('company_id,company_contact_phone')
                             ->where('company_name','like','%'.$v[32].'%')
                             ->where('company_contact_phone','=',$v[7])
                             ->find();
                            //pp($res);die;
                            if(empty($res)){
                                throw new \Exception('手机号:'.$v[32].'未查到公司信息');
                            }
    
                            //$butime = $v[11];
                            $butime = date("Y-m-d H:i:s",strtotime($v[11]));
                            //pp($butime);die;
                            $company_id = $res['company_id'];
                            $mblength = mb_strlen($v[0], 'UTF8');
                            $data[$k]['equipment_id'] = uuid();
                            $data[$k]['company_id'] = $company_id;
                            $data[$k]['equipment_status'] = 1;
                            $data[$k]['equipment_name'] = $v[1];
                            $data[$k]['scope_of_application'] = $v[2];
                            $data[$k]['equipment_modle'] = $v[3];
                            $data[$k]['equipment_image'] = $v[4];//这里就是图片地址
                            $data[$k]['manufacturer'] = $v[5];
                            $data[$k]['contact'] = $v[6];
                           。。。。。。。。。。。。。。。。。。。。。。。。。。
                        }
                    }//pp($data);die;pp($coord);pp($maintance);die;
                    $result = Db::name('*****')->insertAll($data);
                    $coordres = Db::name('******')->insertAll($coord);
                    $maintanceres = Db::name('**********')->insertAll($maintance);
                    if (!$result) {
                        throw new \Exception('*****:'.$v[1].'***表添加错误');
                    }
                    if (!$coordres) {
                        throw new \Exception('****:'.$v[1].'*****表添加错误');
                    }
                    if (!$maintanceres) {
                        throw new \Exception('******:'.$v[1].'*****添加错误');
                    }
                    Db::commit();
                    return array('status' => 1, 'msg' => "导入成功");
                } catch (\Exception $e) {
                    Db::rollback();
                    return array('status' => 0, 'msg' => $e->getMessage());
                }
            }
        }
    
        /**
         * 导入方法附属方法
         * @param
         * @param
         * @return
         */
        public function read($filename, $encode, $file_type)
        {
            if (strtolower($file_type) == 'xls')//判断excel表类型为2003还是2007//如果要上传表格中的图片,必须为xls格式表格,用excel5 得类,excel2007会报错
            {
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            } elseif (strtolower($file_type) == 'xlsx') {
                $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            }
            
            $objReader->setReadDataOnly(false);
            $objPHPExcel = $objReader->load($filename);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
            $highestColumn = $objWorksheet->getHighestColumn();
            $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
            $excelData = array();//返回excel表中数据
            for ($row = 1; $row <= $highestRow; $row++) {
                for ($col = 0; $col < $highestColumnIndex; $col++) {
                    $excelData[$row][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                }
            }
    
            if (strtolower($file_type) == 'xls'){
    
                //单独处理excel中的图片,格式必须是xls的才可以,
                $imgData = array();
                $imageFilePath = '/uploads/excel/';//图片保存目录
                if (! file_exists ( $imageFilePath )) {
                    mkdir("$imageFilePath", 0777, true);
                }
    
                foreach($objWorksheet->getDrawingCollection() as $img){
                    list ($startColumn, $startRow) = \PHPExcel_Cell::coordinateFromString($img->getCoordinates());//获取列与行号
                    $imageFileName=date('YmdHis').$startRow.time().mt_rand(100,9999);
                    /*表格解析后图片会以资源形式保存在对象中,可以通过getImageResource函数直接获取图片资源然后写入本地文件中*/
                    switch ($img->getMimeType()){//处理图片格式
                        case 'image/jpg':
                        case 'image/jpeg':
                            $imageFileName.='.jpg';
                            imagejpeg($img->getImageResource(),$imageFilePath.$imageFileName);
                            break;
                        case 'image/gif':
                            $imageFileName.='.gif';
                            imagegif($img->getImageResource(),$imageFilePath.$imageFileName);
                            break;
                        case 'image/png':
                            $imageFileName.='.png';
                            imagepng($img->getImageResource(),$imageFilePath.$imageFileName);
                            break;
                    }
                    $imgData[$startRow][$startColumn]= $imageFilePath.$imageFileName;//追加到数组中去
                    /*[2] => Array
                    (
                        [E] => /uploads/excel/20211221150435216400702751912.png
                    )*/
                }
    
    
                /*foreach ($objWorksheet->getDrawingCollection() as $key=>$img ){
                    list ($startColumn, $startRow ) = \PHPExcel_Cell::coordinateFromString($img->getCoordinates()); //获取列与行号
                    $imageFileName = $img ->getCoordinates().mt_rand(100,999);
                    $filename = $img->getIndexedFilename(); //文件名
                    ob_start();
                    call_user_func(
                    $img->getRenderingFunction(),
                    $img->getImageResource()
                    );
                    $imageContents = ob_get_contents();
                    file_put_contents($imageFilePath.$filename,$imageContents); //把文件保存到本地
                    ob_end_clean();
                    $imgData [ $startRow ][ $startColumn ]= '/'.$imageFilePath.$filename ; //追加到数组中去
                }*/
                // 处理图片数组与excelData 结合
                if(!empty($imgData)){
                    foreach ($imgData as $key => $value) {
                        //$excelData[$key][4] 是导入模板的代表图片的哪一行
                        $excelData[$key][4] = $value['E'];
                    }
                }
            }
    
            return $excelData;
        }
    
        //导出excel
        public function outexcel()
        {
    
        }
  • 相关阅读:
    【杭电】[2071]Max Num
    【POJ】[1679]The Unique MST
    【POJ】[1679]The Unique MST
    Mac 系统引导过程概述 & BootCamp 的秘密
    Mac 系统引导过程概述 & BootCamp 的秘密
    在Eclipse中参看项目中的所有文件
    在Eclipse中参看项目中的所有文件
    让Eclipse不仅仅只是通过点号来激活代码提示功能
    让Eclipse不仅仅只是通过点号来激活代码提示功能
    Eclipse汉化包的下载和安装
  • 原文地址:https://www.cnblogs.com/yszr/p/15715444.html
Copyright © 2011-2022 走看看