Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 694
yayitswei Avatar asked Apr 27 '17 20:04

yayitswei


People also ask

How do I find the sheet ID in Google Sheets API?

The spreadsheet ID can be discovered from the spreadsheet URL; the sheet ID can be obtained from the spreadsheet.

How do you dynamically reference a sheet in Google Sheets?

So, how do you dynamically reference another sheet in Google Sheets? The best option is to use the INDIRECT formula. This is great if you have multiple sheets that are identical but have different data. You can pull all of this information dynamically into one sheet using the INDIRECT function.


1 Answers

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);
}
like image 85
Tanaike Avatar answered Oct 18 '22 20:10

Tanaike