phpexcel 导入、导出

 /**
     * @return array
     * 导入excel
     */
    public function excel(){
        $file = request()->file('file');
        $info = $file->validate(['ext' => 'xlsx,xls,csv'])->move('../public/uploads');
        //数据为空返回错误
        if(empty($info)){
            $output['status'] = false;
            $output['info'] = '导入数据失败~';
            return ['code'=>200,'msg'=>$output];
        }
        //获取文件名
        $exclePath = $info->getSaveName();
        //上传文件的地址
        $filename = $_SERVER['DOCUMENT_ROOT']. '/uploads/' . $exclePath;
        //判断截取文件
        $extension = strtolower( pathinfo($filename, PATHINFO_EXTENSION) );
        include_once '../extend/PHPExcel/PHPExcel.php';
        include_once '../extend/PHPExcel/PHPExcel/IOFactory.php';
        //区分上传文件格式
        if($extension == 'xlsx') {
            //引入PHPExcel类
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
//            $objReader =  new \PHPExcel_Reader_Excel2007();
            $objPHPExcel = $objReader->load($filename);
        }else if($extension == 'xls'){
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
//            $objReader = new \PHPExcel_Reader_Excel5();
            $objPHPExcel = $objReader->load($filename);
        }else if($extension == 'csv'){
            $objReader = \PHPExcel_IOFactory::createReader('CSV')
                ->setDelimiter(',')
                ->setInputEncoding('GBK')
                ->setEnclosure('"')
//                ->setLineEnding("\r\n")
                ->setSheetIndex(0);
//            $objReader = new \PHPExcel_Reader_Excel5();
            $objPHPExcel = $objReader->load($filename);
        }
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $highestColumn = $sheet->getHighestColumn(); // 取得总列数*/
//        $excel_array = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
        $excel_array = $objPHPExcel->getsheet(0)->toArray();   //转换为数组格式
        array_shift($excel_array);  //删除第一个数组(标题);
        $city = [];
        foreach($excel_array as $k=>$v) {
//            $city[$k]['access_no'] = $v[0];
//            $city[$k]['access_name'] = $v[1];
//            $city[$k]['access_mobile'] = $v[2];
//            $city[$k]['access_address'] = $v[3];
//            $city[$k]['access_zip_code'] = $v[4];
//            $city[$k]['access_weight'] = $v[5];
            $city[$k]['access_no'] = $v[0];
            $city[$k]['access_name'] = $v[14];
            $city[$k]['access_mobile'] = $v[18];
            $city[$k]['access_address'] = $v[15];
        }
        if ($city){
            return json(['code'=>200,'msg'=>'成功','data'=>$city]);
        }else{
            return json(['code' => 400,'msg'=>'失败']);
        }
    }

/**
     * 导出excel表格
     * @param   array    $columName    第一行的列名称
     * @param   array    $list         二维数组
     * @param   string   $setTitle    sheet名称
     * @return
     * @author  Tggui 
     */
    public function exportExcel($columName, $list, $setTitle='Sheet1', $fileName='demo'){
        include_once '../extend/PHPExcel/PHPExcel.php';
        include_once '../extend/PHPExcel/PHPExcel/IOFactory.php';
        if ( empty($columName) || empty($list) ) {
            return '列名或者内容不能为空';
        }
        if ( count($list[0]) != count($columName) ) {

            return '列名跟数据的列不一致' . count($list[0]) .'-'. count($columName);
        }

        //实例化PHPExcel类
        $PHPExcel    =    new \PHPExcel();
        //获得当前sheet对象
        $PHPSheet    =    $PHPExcel    ->    getActiveSheet();
        //定义sheet名称
        $PHPSheet    ->    setTitle($setTitle);

        //excel的列 这么多够用了吧?不够自个加 AA AB AC ……
        $letter        =    [
            'A','B','C','D','E','F','G','H','I','J','K','L','M',
            'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
        ];
        //把列名写入第1行 A1 B1 C1 ...
        for ($i=0; $i < count($list[0]); $i++) {
            //$letter[$i]1 = A1 B1 C1  $letter[$i] = 列1 列2 列3
            $PHPSheet->setCellValue("$letter[$i]1","$columName[$i]");
        }
        //内容第2行开始
        foreach ($list as $key => $val) {
            //array_values 把一维数组的键转为0 1 2 3 ..
            foreach (array_values($val) as $key2 => $val2) {
                //$letter[$key2].($key+2) = A2 B2 C2 ……
                $PHPSheet->setCellValue($letter[$key2].($key+2),$val2);
            }
        }
        //生成2007版本的xlsx
//        $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');
        $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,'Excel5');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename='.$fileName.'.xlsx');
        header('Cache-Control: max-age=0');
        $PHPWriter->save("php://output");
    }
    public function file_export_excel(){
        $order_id = input('get.order_id');
        $titlname    =    ['订单号','运单号','收件人姓名','收件人手机号','收件人地址'];
        $this->exportExcel($titlname,$or);
    }

你可能感兴趣的:(phpexcel 导入、导出)