如何在Google电子表格API中使用工作表ID?

时间:2018-10-22 17:15:36

标签: google-sheets google-api spreadsheet google-sheets-api

Google Spreadsheet文档可以包含一些工作表。首先是默认值,它等于0。

通常对于任何工作表都有这样的地址:

  

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

同时具有spreadsheetIdsheetId

但是在API文档中:

  

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update

未提及的热门sheetId 。我只能阅读和编辑给定spreadsheetId的默认工作表。

如果在示例链接中提供的代码的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中默认以外的其他工作表的访问权限,以及如何读取或更新其中的字段?

4 个答案:

答案 0 :(得分:1)

根据here的规定,range参数可以包含工作表名称,例如,

Sheet1!A1

答案 1 :(得分:0)

在创建新的Google表格时始终出现的初始空白空白标签始终为其分配了sheetId 0。

随后创建的sheetId是随机的十位数。只有第一个选项卡的sheetId为0。即使您重命名工作表,其ID也会保持不变。 ID从未被重复使用-在给定的工作表中ID保持唯一。

使用Google Drive API,使用工作表的Google Drive文件ID实例化对Google Sheet的访问。

一旦实例化了对特定Google表格文件的访问权限,便可以使用“ sheetId”命名法引用表格标签中的每个标签,并在表格的标签中操作信息,格式等。

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

<?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);
    }
?>

答案 2 :(得分:0)

这是我的“通过sheetId在电子表格中重命名工作表”功能的工作示例。 您可以通过相同的方式使用Google Spreadsheets API文档中的其他方法。希望对别人有帮助


    <?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获取工作表标题,可以使用以下功能

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]

答案 3 :(得分:0)

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

<块引用>

@TheMaster 为我指明了正确的方向,但我发现答案令人困惑,所以我只想分享我的 Node.js 工作示例。

以下是如何从 ID 为 B2 的工作表中获取单元格 0123456789 的值

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,其中 dataFilters 是一个单独的过滤器对象数组。 gridRange filter (one of many) 允许我们指定要返回的 sheetId 和单元格范围。