tp3.2中读取excel数据函数封装,且解决wps读取不到内容和当excel中大于Z列时(AA,AB列),无法读取数据的问题

此函数在tp3.2中可直接使用。

    public function readExcel($file)
    {
        header("Content-Type:text/html; charset=utf-8");
        if ( !file_exists($file) ) {
            $this->ajaxReturn([
                'code' => 500,
                'msg'  => 'Excel文件不存在'
            ]);
        }
        $info = pathinfo($file);
        import('Vendor.Classes.PHPExcel');
        if ( $info['extension'] == 'xls' ) {
            import("Vendor.Classes.PHPExcel.Reader.Excel5");
            $PHPReader = new \PHPExcel_Reader_Excel5();
        } else if ( $info['extension'] == 'xlsx' ) {
            import("Vendor.Classes.PHPExcel.Reader.Excel2007");
            $PHPReader = new \PHPExcel_Reader_Excel2007();
        } else {
            $this->ajaxReturn([
                'code' => 500,
                'msg'  => '不支持的文件格式,只支持xls,xlsx文件'
            ]);
        }
        //定义数组arr用于存储excel中数据
        $arr = array();
        //读取excel
        $PHPReader->setReadDataOnly(true); //使用文件流读取文件
        $PHPExcel = $PHPReader->load($file);
        //$PHPExcel = $PHPReader->load($file);    //使用wps编辑保存过的文件,不能直接load读取
        //获取表中的第一个工作表,如果要获取第二个,把0改为1,依次类推
        $currentSheet = $PHPExcel->getSheet(0);
        //获取总列数
        $allColumn = $currentSheet->getHighestColumn();
        //解决当excel中大于Z列时(AA,AB列),无法读取数据的问题
        $allColumn = \PHPExcel_Cell::columnIndexFromString($allColumn);
        //获取总行数
        $allRow = $currentSheet->getHighestRow();
        //循环获取表中的数据,$currentRow表示当前行,从哪行开始读取数据,索引值从0开始
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            //从哪列开始,A表示第一列  修改为0表示第一列
            for ($currentColumn = 0; $currentColumn <= $allColumn; $currentColumn++) {
                //数据坐标
                //$address = $currentColumn . $currentRow;
                //读取到的数据,保存到数组$arr中
                //$arr[$currentRow - 2][$currentColumn] = $currentSheet->getCell($address)->getValue();

                //解决当excel中大于Z列时(AA,AB列),无法读取数据的问题
                $arr[$currentRow - 2][$currentColumn] = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
            }
        }
        return $arr;
    }

你可能感兴趣的:(php)