tp5之 Excel文件导入数据库

参考地址,参考下面,引入phpexcel 包

https://blog.csdn.net/weixin_42122979/article/details/80804460

html 页面

Excel导入数据库

php代码

public function addexcel()
{
	vendor("PHPExcel.PHPExcel");   //获取PHPExcel类 
    $excel = new \PHPExcel();  

    $file = request()->file('file');  

    // var_dump($file);
    // die;

    // $info = $file->validate(['size'=>15678,'ext'=>'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'excel');

    $info = $file->validate(['ext'=>'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'excel');

    //  ["pathName":"SplFileInfo":private]=>
		  // string(105) "E:\phpstudy2018\PHPTutorial\WWW\gaoxie\h_layui\public\excel\20190827\cf76bbbc649be41f65c2bc9406dc4c8f.xls"
		  // ["fileName":"SplFileInfo":private]=>
		  // string(36) "cf76bbbc649be41f65c2bc9406dc4c8f.xls"

    if($info){
    	$exclePath = $info->getSaveName();  //获取文件名  
        $file_name = ROOT_PATH . 'public' . DS . 'excel' . DS . $exclePath;   //上传文件的地址  

        $na = explode('.',$exclePath);
      
        if($na['1'] =='xlsx' ){
		    $objReader = \PHPExcel_IOFactory::createReader('Excel2007'); 
		}else{
		    $objReader = \PHPExcel_IOFactory::createReader('Excel5'); 
		}


        $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8  
        
        $excel_array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式  
        // array_shift($excel_array);  //删除第一个数组(标题);  
        $arr  = reset($excel_array);
        unset($excel_array[0]);
        $data = [];  
        $i=0;  
        // 下面有几个字段名就得有几个语句
        foreach($excel_array as $k=>$v) {  
            // $data[$k][$arr[0]] = $v[0];  
            // $data[$k][$arr[1]] = $v[1];  
            // $data[$k][$arr[2]] = $v[2];  
        	$count = count($v);

        	for($n = 0;$n < $count; $n++){

            	$data[$k][$arr[$n]] = $v[$n]; 
            }
            $i++;  
        }

        $table = $_POST['table'];
        
        // $res = Db::table('sp_excel')->insertAll($data);
        $res = Db::table($table)->insertAll($data);

        echo "
"; 
        var_dump($res);
        echo '导入数据库成功';
        // var_dump($data);
        die;

    }
}

你可能感兴趣的:(tp5)