【问题标题】:How to get google spread sheet data from Sheet ID (From gid) instead of Spread Sheet Id in php如何从工作表 ID(来自 gid)而不是 php 中的电子表格 ID 获取谷歌电子表格数据
【发布时间】:2019-02-08 04:35:04
【问题描述】:

我有一个电子表格,它包含多个选项卡格式的工作表。

我的代码只获取第一个电子表格数据,并且我有一个包含所有工作表 ID 的数组。

我的问题是如何获取所有工作表数据,因为我对所有人都有唯一的 gid。

这里所有工作表的电子表格 ID 都相同,只有工作表 ID (gid) 不同。

我搜索了很多,我只从 spreadSheet Id 中获取数据。

<?php
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Sheets API PHP Quickstart');
    $client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}


// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);



$spreadsheetId = 'xxxxxxx--tttttttttttL_ttthhdfhdhshshshshhshsh-84';///random spread sheet id
$range = 'A:G';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();//getting first sheet data only


    $sheet_id = array();    
    // Load Google API library and set up client
    // You need to know $spreadsheetID (can be seen in the URL)
    $sheetService = $service;  
    $spreadSheet = $sheetService->spreadsheets->get($spreadsheetId);
    $sheets = $spreadSheet->getSheets();

    foreach($sheets as $sheet) {

    $sheet_id[] = $sheet->properties->sheetId;


    }


 ///$sheet_id   -- it will give all the id of sheets, I have 36 sheets in a single spreadsheet, so it's giving 36 ids in an array format

任何建议将不胜感激..

【问题讨论】:

  • FWIW,我看不到 php 和/或 Excel 标签的相关性。

标签: php excel google-sheets


【解决方案1】:

经过大量研究,我得到了解决方案,我想发布我的解决方案。

$client = $this->getClient();
$service = new Google_Service_Sheets($client);

// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/xxxxxx--yyyyyyyyyyyyyy_zzzzzzzzzzzzzzzz/edit

 //

 $spreadsheetId = 'xxxxxx--yyyyyyyyyyyyyy_zzzzzzzzzzzzzzzz';
  $sheet_id = array();    
    // Load Google API library and set up client
    // You need to know $spreadsheetID (can be seen in the URL)
    $sheetService = $service;  
    $spreadSheet = $sheetService->spreadsheets->get($spreadsheetId);
    $sheets = $spreadSheet->getSheets();

    foreach($sheets  as  $key=>$sheet) {

    // $sheet_id[$key]['gid'] = $sheet->properties->sheetId;
    // $sheet_id[$key]['title'] = $sheet->properties->title;


$range = $sheet->properties->title.'!A:G';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values[$sheet->properties->title] = $response->getValues();


    }

这里我们只有 spreadSheet Id,我们可以从中获取所有工作表的标题,从标题中我们将获取所有详细信息:

$range = $sheet->properties->title.'!A:G'; /// 循环标题并获取整个工作表的值

【讨论】:

    【解决方案2】:

    我可以帮助您使用 javascript - 您必须自己编写任何 php。

    如果您有工作表 ID,那么很容易回溯到工作表名称,然后按名称“获取”工作表。

    1 - getSheets() - 获取当前电子表格中的所有工作表。从中,您可以找到工作表名称和每张工作表的 ID。

    2 - ID 是使用getSheetId() 获得的 - 返回工作表的 ID,您可以将其与列表进行比较。

    3 - 使用getSheetName() 获得工作表名称 - 返回可以在方法getSheetByName 中使用的工作表名称。

    4 - getSheetByName(name) - 使您能够返回具有给定名称的特定工作表。

    以下示例获取一个包含 ActiveSpreadsheet 的 sheetID 的对象。它遍历那些捕获相应 SheetName 和 SheetID 的工作表。它使用嵌套循环遍历我的 SheetID 列表并比较 SheetID。如果 SheetID 匹配,则代码使用 SheetName 按名称访问工作表。如果 SheetID 不匹配,它将继续下一个循环,然后以此类推。

    我在代码中留下了一些 Logger 命令,以便 OP 可以在脚本中方便的位置测试检查详细信息。

    function so54586032() {
    
      // set up the spreadsheet
      var ss = SpreadsheetApp.getActiveSpreadsheet();
    
      // this is the sheet where I listed my SheetIDs
      var mainsheet = ss.getSheetByName("54586032");
    
      // calculate the number of IDs 
      var Avals = mainsheet.getRange("A1:A").getValues();
      var Alast = Avals.filter(String).length;
      //Logger.log("DEBUG: Number of SheetIDs in my list: " + Alast); //DEBUG
    
      // get the list of all sheets in this spreadsheet
      var sheets = ss.getSheets();
      //calculate the number of sheets
      var sheetslength = sheets.length
      //Logger.log("DEBUG: Number of actual sheets in this spreadsheet: " + sheetslength); //DEBUG
    
      // LOOP through the actual sheets
      for (var i = 0; i < sheets.length; i++) {
        //Logger.log("DEBUG: i: " + i + ", sheet name: " + sheets[i].getName() + ", sheet ID: " + sheets[i].getSheetId()); // DEBUG
    
        // loop through the list of sheets 
        for (var z = 0; z < Alast; z++) {
          //Logger.log("DEBUG: z: " + z + ", sheet ID: " + Avals[z][0]); //DEBUG
    
          // test if this shhetID equals the next number in my list
          if (sheets[i].getSheetId() == Avals[z][0]) {
            //Logger.log("DEBUG: Match: " + sheets[i].getSheetId() + " to " + Avals[z][0]); //DEBUG
            // do something
          } else {
            //Logger.log("DEBUG: No Match"); //DEBUG
          };
        }
    
      }
    
    }
    

    我的列表包含相关的 SheetID

    【讨论】:

      【解决方案3】:

      要通过 GID 获取工作表名称,您可以使用相应的 Sheets Api:

      $spreadsheet_service=new Google_Service_Sheets($client);
      
      $body = new Google_Service_Sheets_GetSpreadsheetByDataFilterRequest([
          'data_filters'=>[
              "gridRange"=>[
                  "sheetId"=>SHEET_GID_HERE
              ]
          ]
      ]);
      
      $response = $spreadsheet_service->spreadsheets->getByDataFilter(SPREADSHEET_ID_HERE,$body,['fields'=>'sheets(properties.title)']);
      print_r($response->getSheets());
      

      【讨论】:

        猜你喜欢
        • 2018-12-20
        • 1970-01-01
        • 2020-07-20
        • 2014-06-29
        • 1970-01-01
        • 2013-04-20
        • 1970-01-01
        • 1970-01-01
        • 2016-07-31
        相关资源
        最近更新 更多