php獲取 Excel文件內的數據,可以是xls結尾的文件,也可以是xlsx結尾的文件

  public function Import($file = '')
    {
        $suffixName=explode('.', $file)[1];//後綴名
        // 取得文件基礎數據
        if($suffixName=='xls'){
            $reader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        if($suffixName=='xlsx'){
            $reader = new \PHPExcel_Reader_Excel2007();
        }
        $excel = $reader->load($file);
        // 取得總行數
        $worksheet = $excel->getActiveSheet();
        // 取得總列數
        $highest_row = $worksheet->getHighestRow();
        // 取得最高的列
        $highest_column = $worksheet->getHighestColumn();
        // 總列數
        $highest_column_index = \PHPExcel_Cell::columnIndexFromString($highest_column);
        // 定義變量
        $result = [];
        // 讀取數據
        for($row=1; $row<=$highest_row; $row++)
        {
            $info = [];
            for($col = 0; $col < $highest_column_index; $col++)
            {
                $value = $worksheet->getCellByColumnAndRow($col, $row)->getFormattedValue();
                if($row == 1)
                {
                    $this->title[]=$value;

                } else {
                    echo $col;
                    $index = $col%count($this->title);
                    $info[$this->title[$index]]=trim($value);
                }
            }
            if($row > 1)
            {
                $result[] = $info;
            }
        }
        return $result;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章