Search code examples
google-apps-scriptgoogle-drive-apigoogle-workspace

Looking up Google Sheets values using sheet id instead of sheet title (Google Drive Rest API V4)


Using the Google Sheets REST API V4, and would prefer to use the sheet id instead of sheet title to look up values in a cell. It seems like you can specify the sheet within the spreadsheet using the range, e.g. Sheet4!A1:Z500, but not a sheet ID such as 1310487470!A1:Z500. This is so the query doesn't have to change if someone renames the sheet. Does the Google API support querying by ID?

Current query:

https://sheets.googleapis.com/v4/spreadsheets/1SR0DJ4nV5-05EWxjz1OYOWkKFObClmsC0rOowPnMwNE/values/Sheet4!A1:Z500

Ideal query:

https://sheets.googleapis.com/v4/spreadsheets/1SR0DJ4nV5-05EWxjz1OYOWkKFObClmsC0rOowPnMwNE/values/1310487470!A1:Z500


Solution

  • How about following sample? I prepared it as a GAS sample. If you use this, please enable Sheet API v4 at API console.

    This retrieves data of a sheet in spreadsheet using GID.

    1. Retrieves information of sheets in spreadsheet. A JSON data which has keys of GID and values of sheet name is created.

    2. Retrieves data from sheet using the JSON.

    Sample script:

    function fetch(url){
      return UrlFetchApp.fetch(url, {
        headers: {
          'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken()
        }
      });
    }
    
    function main(){
      // Retrieves information of sheets in spreadsheet. 
      var spreadsheet = "#####";
      var url = "https://sheets.googleapis.com/v4/spreadsheets/" + spreadsheet + "?fields=sheets(properties(sheetId%2Ctitle))";
      var sheetdic = {};
      JSON.parse(fetch(url)).sheets.forEach(function(e){
        sheetdic[e.properties.sheetId] = e.properties.title;
      });
    
      // Retrieves data from sheet using GID.
      var sheet = sheetdic["#####"]; // Imports sheet name using GID.
      var url = "https://sheets.googleapis.com/v4/spreadsheets/" + spreadsheet + "/values/" + sheet + "!A1:Z500";
      var results = fetch(url);
    }