Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read data in a named range?

I've been through the documentation of the Google Sheets API v4 and couldn't find a way to read data from a named range. I'm using Python, specifically, and looking for something along the lines of:

named_range = 'My Beautiful Range'
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=my_id,
                            namedRange=named_range).execute()
values = result.get('values', [])

Is there such an API?

like image 643
user2470305 Avatar asked Nov 02 '25 07:11

user2470305


1 Answers

Yes, both spreadsheets.values.get and spreadsheets.get accepts named ranges as their range parameter.

Just keep in mind that your named ranges should be valid and existing in the spreadsheet that you are trying to access.

NOTE:

Valid Range Names:

  • Can contain only letters, numbers, and underscores.
  • Can't start with a number, or the words "true" or "false."
  • Can't contain any spaces or punctuation.
  • Must be 1–250 characters.
  • Can't be in either A1 or R1C1 syntax. For example, you might get an error if you give your range a name like "A1:B2" or "R1C1:R2C2."

Sample Code:

named_range = 'MyBeautifulRange'
result = sheet.values().get(spreadsheetId=my_id,
                            range=named_range).execute()
values = result.get('values', [])

Sample Sheet:

enter image description here

Sample spreadsheets.values.get request using API explorer:

enter image description here

Sample Response Body:

{
  "range": "Sheet1!A1:B3",
  "majorDimension": "ROWS",
  "values": [
    [
      "A1",
      "B1"
    ],
    [
      "A2",
      "B2"
    ],
    [
      "A3",
      "B3"
    ]
  ]
}
like image 87
Kristkun Avatar answered Nov 04 '25 20:11

Kristkun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!