使用Laravel通过API检索Google Spreadsheet中的所有行

时间:2018-08-31 05:57:14

标签: php laravel laravel-5 laravel-5.2 google-api-php-client

我正在尝试使用以下This tutorial库从Google电子表格中获取数据,并且按照本教程配置API的设置,并且没有任何错误,但是一旦我尝试实现以下任何一种他们在上面的链接中提供的示例,向我展示了一些错误:

示例1(在其链接上):

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PulkitJalan\Google\Facades\Google;
use Revolution\Google\Sheets\Sheets;

class SpreadController extends Controller
{
    function index()
    {
        $rows = Sheets::sheet('Sheet 1')->get();

        $header = $rows->pull(0);
        $values = Sheets::collection($header, $rows);
        dd($values);
    }

}

错误是:

  

无法解析的依赖项解析[参数#0 [数组   $ config]]在类PulkitJalan \ Google \ Client


示例2(在其链接上):

代码:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PulkitJalan\Google\Facades\Google;
use Revolution\Google\Sheets\Sheets;

class SpreadController extends Controller
{
    function index()
    {
        $user = $request->user();

        $token = [
            'access_token'  => $user->access_token,
            'refresh_token' => $user->refresh_token,
            'expires_in'    => $user->expires_in,
            'created'       => $user->updated_at->getTimestamp(),
        ];

// all() returns array
        $values = Sheets::setAccessToken($token)->spreadsheet('1n0nyJX9wYp-_frg7TzoyMu3WyuSwtCo21g')->sheet('Sheet 1')->all();

    }

}

错误是:

  

未定义变量:请求

     

这是库目录中的配置文件(“ vendor / pulkitjalan / google-apiclient / src / config / config.php”):

<?php

return [
    /*
    |----------------------------------------------------------------------------
    | Google application name
    |----------------------------------------------------------------------------
    */
    'application_name' => env('GOOGLE_APPLICATION_NAME', ''),

    /*
    |----------------------------------------------------------------------------
    | Google OAuth 2.0 access
    |----------------------------------------------------------------------------
    |
    | Keys for OAuth 2.0 access, see the API console at
    | https://developers.google.com/console
    |
    */
    'client_id'       => env('GOOGLE_CLIENT_ID', ''),
    'client_secret'   => env('GOOGLE_CLIENT_SECRET', ''),
    'redirect_uri'    => env('GOOGLE_REDIRECT', ''),
    'scopes'          => [],
    'access_type'     => 'online',
    'approval_prompt' => 'auto',

    /*
    |----------------------------------------------------------------------------
    | Google developer key
    |----------------------------------------------------------------------------
    |
    | Simple API access key, also from the API console. Ensure you get
    | a Server key, and not a Browser key.
    |
    */
    'developer_key' => env('GOOGLE_DEVELOPER_KEY', ''),

    /*
    |----------------------------------------------------------------------------
    | Google service account
    |----------------------------------------------------------------------------
    |
    | Set the credentials JSON's location to use assert credentials, otherwise
    | app engine or compute engine will be used.
    |
    */
    'service' => [
        /*
        | Enable service account auth or not.
        */
        'enable' => env('GOOGLE_SERVICE_ENABLED', false),

        /*
        | Path to service account json file
        */
        'file' => env('GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION', '')
    ],

    /*
    |----------------------------------------------------------------------------
    | Additional config for the Google Client
    |----------------------------------------------------------------------------
    |
    | Set any additional config variables supported by the Google Client
    | Details can be found here: 
    | https://github.com/google/google-api-php-client/blob/master/src/Google/Client.php
    | 
    | NOTE: If client id is specified here, it will get over written by the one above.
    |
    */
    'config' => [],
];

和.env文件包含为配置变量分配的以下值:

 GOOGLE_APPLICATION_NAME= Append Data
 GOOGLE_CLIENT_ID= 995576272219-q9t67ufvehsqoctcq7g.apps.googleusercontent.com
 GOOGLE_CLIENT_SECRET= ow1kEPcuSEGmGIXZtl
 GOOGLE_REDIRECT=
 GOOGLE_DEVELOPER_KEY=
 GOOGLE_SERVICE_ENABLED=
 GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION=

任何人都可以通过该解决方案指导我如何从电子表格中获取数据或解决此处考虑的问题。

2 个答案:

答案 0 :(得分:0)

您可以使用https://github.com/googleapis/google-api-php-client包来完成任务。

要安装此软件包,请添加

  

“ google / apiclient”:“ ^ 2.0”

到composer.json并运行composer update命令。

请按照https://www.fillup.io/post/read-and-write-google-sheets-from-php/教程获取更多信息

安装软件包后,需要在config文件夹中的.env文件和constants.php文件中设置值。

在这里,我使用了工作表名称变量。如果省略此选项,则它将使用电子表格中的第一张表(Tab)。

示例代码:

namespace App\Utilities;

    use App\Exceptions\LogExceptions;
    use AWS;
    use Illuminate\Http\File;
    use Illuminate\Support\Facades\Storage;
    use Config;

    class SpreadSheetManagemnt{
      private $CLIENT;
      private $SERVICE;
      private $SPREAD_SHEET;
      private $SPREAD_SHEET_ID;
    /**
     * Returns an authorized API client.
     * @return Google_Client the authorized client object
     */
      public function __construct() {

      $this->CLIENT = new \Google_Client();
      $this->CLIENT->setApplicationName("My Sample App");
      $this->CLIENT->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
      $this->CLIENT->setAccessType('offline');
      $this->CLIENT->setAuthConfig(Config::get('constants.SPREAD_SHEET_AUTH_FILE'));

      $this->SPREAD_SHEET_ID = Config::get('constants.SPREAD_SHEET_ID');

      $this->SERVICE = new \Google_Service_Sheets($this->CLIENT);
      $this->SPREAD_SHEET =  $this->SERVICE->spreadsheets->get($this->SPREAD_SHEET_ID);
   }

    /**
     * Function to show sheet datas
     * @param string sheet name
     * @return boolean
     */
    public function showDatas($sheetName)
    {
        try{
          // column ranges in spreadsheet
          $range = "'".$sheetName."'!A2:F3";
          $rows = $this->SERVICE->spreadsheets_values->get($this->SPREAD_SHEET_ID, $range, ['majorDimension' => 'ROWS']);
          dd($rows['values']);

        }catch( \Throwable $e){
            LogExceptions::writeLog($e);
        }
    }

}

答案 1 :(得分:0)

要从谷歌电子表格中检索所有行,只需从范围中删除单元格编号。

$getrange = 'A:E';
$data = $service->spreadsheets_values->get($spreadsheetId, $getrange);

$values = $data->getValues();

if (empty($values)) {
    print "No data found.\n";
} else {
    echo "<pre>";
    print_r($values);
}