Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Google sheets 如何在GoogleSheetsAPI中使用工作表ID?_Google Sheets_Google Api_Google Sheets Api - Fatal编程技术网

Google sheets 如何在GoogleSheetsAPI中使用工作表ID?

Google sheets 如何在GoogleSheetsAPI中使用工作表ID?,google-sheets,google-api,google-sheets-api,Google Sheets,Google Api,Google Sheets Api,GoogleSheets文档可以包含一些表单。第一个是默认值和“0”。一般情况下,任何工作表都有如下地址: 同时使用电子表格ID和电子表格ID 但是在中没有提到如何使用sheetId。我只能读取和编辑给定电子表格ID的默认表格 如果在请求中来自示例性链接中显示的代码,我添加了sheetId属性,我得到错误: { message: 'Invalid JSON payload received. Unknown name "sheetId": Cannot bind query para

GoogleSheets文档可以包含一些表单。第一个是默认值和“0”。一般情况下,任何工作表都有如下地址:

同时使用
电子表格ID
电子表格ID

但是在中没有提到如何使用
sheetId
。我只能读取和编辑给定
电子表格ID
的默认表格

如果在
请求中
来自示例性链接中显示的代码,我添加了
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 sheets API中的默认工作表以外的其他工作表并读取或更新其中的字段?

如前所述,
范围
参数可以包括如下工作表名称:

Sheet1!A1

如果必须使用工作表id而不是工作表名称,则可以使用使用
dataFilter
的任何备选端点,如
spreadsheets.values.batchUpdateDataFilter
而不是
spreadsheets.values.batchUpdate
。然后,您可以在
data.dataFilter.gridRange.sheetId
的请求正文中使用sheetId


但是,是将对象(工作表/范围/列)永久关联到变量的首选方法,用户可以在这些对象上进行修改。

创建新Google工作表时始终存在的初始空白空白选项卡始终指定有sheetId 0

随后创建的图纸是随机的十位数。只有第一个选项卡具有图纸ID 0。即使重命名图纸,其ID也保持不变。ID永远不会被重用-它们在给定的工作表中保持唯一性

通过使用Google Drive API,可以使用工作表的Google Drive文件ID实例化对Google工作表的访问

一旦您实例化了对特定Google工作表文件的访问,您就可以引用工作表选项卡中的每个选项卡,并通过使用“sheetId”术语来操作工作表选项卡中的信息、格式等

下面是一个使用sheetId 0重命名Google工作表选项卡名称的PHP示例


以下是我的“按sheetId重命名电子表格中的工作表”功能的工作示例。 您可以用同样的方式使用谷歌电子表格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);
}

$sheets\u info\u数组将相等

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

因此,您可以将$your\u sheet\u id的标题作为$sheets\u info\u数组[$your\u sheet\u id]

基本上我们需要使用

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

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

const getValueFromCellB2=async()=>{
const SPREADSHEET_ID='INSERT_SPREADSHEET_ID';
施工图编号=0123456789;
//TODO:用实际ID替换上述值。
const google=wait googleConnection();
const sheetData=wait google.spreadsheets.values
.batchGetByDataFilter({
电子表格ID:spreadsheetId,
资源:{
数据过滤器:[
{
网格范围:{
sheetId:SHEET_ID,
startRowIndex:1,
endRowIndex:2,
startColumnIndex:1,
endColumnIndex:2,
},
},
],
},
})
.然后((res)=>res.data.valueRanges[0].valueRange.values);
返回数据[0][0];
}
//有很多方法可以与谷歌认证。。。这里有一个:
const googleConnection=async()=>{
const auth=wait google.auth.getClient({
keyFilename:path.join(_dirname,'../../secrets.json'),
范围:'https://www.googleapis.com/auth/spreadsheets',
});
返回google.sheets({version:'v4',auth});
}

为了简单地读取数据,我们使用的
dataFilters
是一个单独的过滤器对象数组。允许我们指定要返回的
图纸ID
和单元格范围。

@I'-'I,感谢您的提示,我解决了这个问题。请将此添加为答案,无需评论,我们将结束此主题。令人惊讶的是,文档在2020年仍然没有提及此主题,请查看downvoted,因为问题是关于工作表id的。通过重命名工作表,您可以在不知不觉中打破基于名称的范围。不相关的答案。@Rahul怎么会这样?尽管我认为卡林的否决票是不合理的,但我确实编辑了我的答案,以显示其他可能性。您对否决票的理由是什么?Sheet id可能不是常量,但可以从url轻松找到它。谷歌文档让regex也能做到这一点。这不是公认的答案。很好的答案!我喜欢用名字代替ID,也可以用ID。我投了赞成票
array (
    "sheet_id1(int)" => 'sheet_title1',
    "sheet_id2(int)" => 'sheet_title3',
)