当前位置:网站首页>Tp5.1 upload excel file and read its contents

Tp5.1 upload excel file and read its contents

2022-06-22 23:22:00 Juqi

1. First set the PHPExcel Class to import , Use here composer

composer require phpoffice/phpexcel

Code :

// Need to introduce this   
use PHPExcel_IOFactory;

public function importExcel(){
        $filename = $_FILES['file_xls']['tmp_name'];
        // Set up excel Format 
        $reader = PHPExcel_IOFactory::createReader('Excel2007');
        // load ⼊excel⽂ Pieces of 
        $excel = $reader->load($filename);
        // Read the first ⼀ A watch 
        $sheet = $excel->getSheet(0);
        // Get the total ⾏ Count 
        $row_num = $sheet->getHighestRow();
        // Get total number of columns 
        $col_num = $sheet->getHighestColumn();
        $data = []; // Get table data in array form 
        for($col='A';$col<=$col_num;$col++)
        {
            // From ⼆⾏ Start , Remove the meter head ( if ⽆ The header starts from the ⼀⾏ Start )
            for($row=2;$row<=$row_num;$row++)
            {
                $data[$row-2][] = $sheet->getCell($col.$row)->getValue();
            }
        }
       //Array ( [0] => Array ( [0] => 77777 ) [1] => Array ( [0] => 88888 ) )
       $error_code = array();
       foreach($data as $item){
        foreach($item as $code){
            $ra = Db::table('apply_code')->field('*')->where('code',$code)->find();
            if (!empty($ra)){
                array_push($error_code,$code);
            }else{
                $arr = array(
                    'code'=>$code,
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                );
                Db::table('apply_code')->insert($arr);
            }   
        }
       }

       $error_msg = ' The following exchange code already exists :';
       if(!empty($error_code)){
        foreach($error_code as $item){
            $error_msg.= ''.$item.',';
        }
        $this->success($error_msg);
       }else{
        $this->success(' All imported successfully ');
       }

    }

原网站

版权声明
本文为[Juqi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222055328859.html