ThinkPHP5.1 Excel表格导入

1.使用composer安装phpexcel类库

打开项目根目录的composer.json文件
将以下写入到require下面

        "phpoffice/phpexcel": "^1.8"
image.png

2.在项目根目录执行

composer require phpoffice/phpexcel

安装成功后,会注意到项目的vendor目录下,多出了一个phpoffice文件夹

3.读取excel文件转换成数组

public function readExcel()
    {
       
        $impfile = '/uploads/20200107/test.xlsx';
        //取出文件后缀名
        $temp_arr = explode(".", $impfile);
        $file_ext = array_pop($temp_arr);
        $file_ext = trim($file_ext);
        $file_ext = strtolower($file_ext);
        $extension = $file_ext;s's
        if($extension!='xls' && $extension!='xlsx') {
            return resultArray(['error' => '请上传xls、xlsx文件格式']);
        }
        $objExcel = new \PHPExcel();
        $filename  = '.'.$impfile;
        if($extension == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');
        }else if($extension == 'xls'){
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');
        }
        $excel_array = $objPHPExcel->getsheet(0)->toArray();   //转换为数组格式
        unset($excel_array[0]);
        if(empty($excel_array)){
            return false;
        }
        return $excel_array;
    }

你可能感兴趣的:(ThinkPHP5.1 Excel表格导入)