Google Sheets API -- Automatically get max range of sheet

it's known that in order to get the values from rows-columns in the Google sheets API, the format is something like this:

gapi.client.sheets.spreadsheets.values.get({
  spreadsheetId: id,
  range: "myData!A1:E" 
}).then(res => {
  console.log(res.result);
}, err => console.log(err));

Notice the "range" has to be within specific parameters, but how do I simply get the values in the max range? Is there some shorthand like "myData!Min:Max" ? I know that you can make another request to get the max row and column length:

sheets.spreadsheets.get({
    spreadsheetId: id,
    ranges: [],
    auth: something
}, (err, resp) => {
    var sheetOne = resp.data.sheets[0];
    console.log(sheetOne.properties.gridProperties); // { rowCount: 1024, columnCount: 7 } (for example)
})

and then once I have that I can theoretically automatically generate the range string with a number-to-letter switching-system to get the column letter names or something like that, and make another request to get the max columns, but first of all:

  1. It might be complicated to make a function that returns a letter-format range from just number maxes
  2. even so, I would like to get only the range that have non-empty values in it; if I have a 1000 row spreadsheet but only using the first 20 rows and columns, then I Want to automatically limit the range to the actual values.

Any way to do this with the API???

Upvotes: 4

Views: 9672

Answers (1)

Mark Longhurst
Mark Longhurst

Reputation: 179

To return all the cells in the sheet named myData, you can use myData, rather than myData!A1:E:

gapi.client.sheets.spreadsheets.values.get({
    spreadsheetId: id,
    range: "myData" 
}).then(res => {
    console.log(res.result);
}, err => console.log(err));

With regard to your second question, as far as I know, there is no way to get only the range that has non-empty values in it using A1 notation.

However, you could iterate through the values once the api has returned them to determine which have values.

From https://developers.google.com/sheets/api/guides/concepts

A1 notation:

Some API methods require a range in A1 notation. This is a string like Sheet1!A1:B2, that refers to a group of cells in the spreadsheet, and is typically used in formulas. For example, valid ranges are:

  • Sheet1!A1:B2 refers to the first two cells in the top two rows of Sheet1.
  • Sheet1!A:A refers to all the cells in the first column of Sheet1.
  • Sheet1!1:2 refers to the all the cells in the first two rows of Sheet1.
  • Sheet1!A5:A refers to all the cells of the first column of Sheet 1, from row 5 onward.
  • A1:B2 refers to the first two cells in the top two rows of the first visible sheet.
  • Sheet1 refers to all the cells in Sheet1.

Upvotes: 15

Related Questions