如何在 Google 工作表 API 中使用 sheet ID?

How to use sheet ID in Google Sheets API?

Google Sheets 文档可以包含一些 sheet。首先是默认值和“0”。通常对于任何 sheet 都有这样的地址:

https://docs.google.com/spreadsheets/d/(spreadsheetId)/edit#gid=(sheetId)

spreadsheetIdsheetId

但是在API documentation中并没有提到如何使用sheetId。我只能读取和编辑给定 spreadsheetId.

的默认值 sheet

如果在示例 link 中提供的代码中 request 我添加了 sheetId 属性 我得到了错误:

{ 
    message: 'Invalid JSON payload received. Unknown name "sheetId": Cannot bind query parameter. Field \'sheetId\' could not be found in request message.',
    domain: 'global',
    reason: 'badRequest' 
}

如何访问 Google 工作表 API 中默认值以外的其他 sheet 并读取或更新其中的字段?

Sheet 名称是访问特定 sheet 的最简单方法。正如所写 hererange 参数可以包括 sheet 名称,例如

Sheet1!A1

如果您必须使用 sheet id 而不是 sheet 名称,您可以使用任何使用 dataFilter 的备用端点,例如 spreadsheets.values.batchUpdateByDataFilter 而不是spreadsheets.values.batchUpdate。然后,您可以在 data.dataFilter.gridRange.sheetId 处的请求正文中使用 sheetId。 .

提供了使用带有 sheetId 的过滤器的示例

但是,developer metadata 是将对象 (sheets/ranges/columns) 永久关联到变量的首选方法,其中需要用户对此类对象进行修改。

创建新 Google Sheet 时始终存在的初始空白空选项卡始终分配有 sheetId 0。

随后创建的 sheetID 是随机的十位数字。只有第一个选项卡的 sheetId 为 0。即使您重命名 sheet,它的 ID 也保持不变。 ID 永远不会重复使用 - 它们在给定的 sheet.

中保持唯一

使用 Google 驱动器 API,使用 sheet 的 Google 驱动器文件实例化对 Google Sheet 的访问编号.

一旦您实例化了对特定 Google Sheet 文件的访问权限,您就可以在 sheet 选项卡中引用每个选项卡并在选项卡中操作信息、格式等sheet,通过使用 'sheetId' 命名法。

这是一个 PHP 使用 sheetId 0 重命名 Google Sheet 标签名称的示例。

<?php
/*
 *   Google Sheets API V4 / Drive API V3, rename existing sheet tab example
 *
 */
$fileID = '/* pass your Google Sheet Google Drive file ID here */';
$client = new Google_Client();
$client->useApplicationDefaultCredentials(); // the JSON service account key location as defined in $_SERVER
$client->setApplicationName('API Name');
$client->addScope(Google_Service_Drive::DRIVE);
$client->setAccessType('offline');
$client->setSubject('API Instance Subject');
$sheet = new Google_Service_Sheets($client);
$sheetList = $sheet->spreadsheets->get($fileID);

/*
 *   iterate through all Google Sheet tabs in this sheet
 */
 $homeFlag = FALSE;
 foreach($sheetList->getSheets() as $sheetRecord) {
        /*
         *   if match, save $sheetTabID from Google Sheet tab 
         */
         if ($sheetRecord['properties']['sheetId'] == 0) {
                 $sheetTabID = $sheetRecord['properties']['sheetId'];
                 $sheetTabTitle = $sheetRecord['properties']['title'];
                 $homeFlag = TRUE;
            }
    }

/*
 *   if $homeFlag is TRUE, you found your desired tab, so rename tab in Google Sheet
 */
 if ($homeFlag) {
         $newTabName = 'NotTabZero';
         $sheetRenameTab = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array('requests' => array('updateSheetProperties' => array('properties' => array('sheetId' => $sheetTabID, 'title' => $newTabName), 'fields' => 'title'))));
         $sheetResult = $sheet->spreadsheets->batchUpdate($sheetID,$sheetRenameTab);
    }
?>

这是我的“通过 sheetId 在 spreadsheet 中重命名 sheet”函数的工作示例。 您可以以相同的方式使用 Google Spreadsheets API Docs 中的其他方法。希望对大家有帮助


    <?php
function getClient()   //standard auth function for google sheets API
{
    $clientConfigPath = __DIR__ . '/google_credentials/client_secret.json';
    $client = new Google_Client();
    $client->setApplicationName('Google Sheets API PHP Quickstart');
    $client->setScopes(Google_Service_Sheets::SPREADSHEETS);
    $client->setAuthConfig($clientConfigPath);
    $client->setAccessType('offline');

    // Load previously authorized credentials from a file.
    $credentialsPath = (__DIR__ . '/google_credentials/credentials.json');
    if (file_exists($credentialsPath)) {
        $accessToken = json_decode(file_get_contents($credentialsPath), true);
    } 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);

        // Store the credentials to disk.
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, json_encode($accessToken));
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }
    return $client;
}


function renameSheet(string $sheetId, string $newTitle, string $spreadsheetId)
{
    // Get the API client and construct the service object.
    $client = getClient();
    $service = new Google_Service_Sheets($client);

    $requests = [
        new Google_Service_Sheets_Request([
            'updateSheetProperties' => [
                'properties' => [
                    'sheetId' => $sheetId,
                    'title' => $newTitle,
                ],
                'fields' => 'title'
            ]
        ])
    ];

    $batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
        'requests' => $requests
    ]);

    return $service->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest);
}

更新 如果你想通过sheetId获取sheet标题,你可以使用下面的函数

function getSpreadsheetInfo($spreadsheetId)  
{
    $client = getClient();
    $service = new Google_Service_Sheets($client);

    $response = $service->spreadsheets->get($spreadsheetId);
    return $response;
}

function getSheets($spreadsheetId)  
{
    $spreadsheet_info = getSpreadsheetInfo($spreadsheetId);
    $sheets_info = [];
    foreach ($spreadsheet_info as $item) {
        $sheet_id = $item['properties']['sheetId'];
        $sheet_title = $item['properties']['title'];
        $sheets_info[$sheet_id] = $sheet_title;
    }
    return $sheets_info;
}

$sheets_info_array = getSheets($YOUR_SPREADSHEET_ID_HERE);

$sheets_info_array 将等于

array (
    "sheet_id1(int)" => 'sheet_title1',
    "sheet_id2(int)" => 'sheet_title3',
)

所以你可以得到 $your_sheet_id 的标题 $sheets_info_array[$your_sheet_id]

本质上我们需要使用dataFilters to target a specific sheet by ID.

@TheMaster pointed me in the right direction but I found the answers confusing so I just want to share my working example for Node.js.

以下是如何从具有 ID 0123456789

的 sheet 中获取单元格 B2 的值的方法
const getValueFromCellB2 = async () => {
  const SPREADSHEET_ID = 'INSERT_SPREADSHEET_ID';
  const SHEET_ID = 0123456789;
  // TODO: replace above values with real IDs.
  const google = await googleConnection();
  const sheetData = await google.spreadsheets.values
    .batchGetByDataFilter({
      spreadsheetId: SPREADSHEET_ID,
      resource: {
        dataFilters: [
          {
            gridRange: {
              sheetId: SHEET_ID,
              startRowIndex: 1,
              endRowIndex: 2,
              startColumnIndex: 1,
              endColumnIndex: 2,
            },
          },
        ],
      },
    })
    .then((res) => res.data.valueRanges[0].valueRange.values);

  return sheetData[0][0];
}

// There are many ways to auth with Google... Here's one:
const googleConnection = async () => {
  const auth = await google.auth.getClient({
    keyFilename: path.join(__dirname, '../../secrets.json'),
    scopes: 'https://www.googleapis.com/auth/spreadsheets',
  });

  return google.sheets({version: 'v4', auth});
}

简单地读取数据,我们使用batchGetByDataFilter where dataFilters is an array of separate filter objects. The gridRange filter (one of many)允许我们指定sheetId和return的单元格范围。