How to do I locate a Google SpreadSheet ID?
When using the Google Execution Api for Java, the ID of the spreadsheet isn’t very easy to understand. Here is the code snippet:
Any Ideas on how to locate this. I run the Sheets api to return the id of a SpreadSheet but it returns a link, and when I use the https://spreadsheets.google.com/feeds/spreadsheets/STRING or just the STRING itself I still get: «code» : 404, «errors» : [ < "domain" : "global", "message" : "Requested entity was not found.", "reason" : "notFound"
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Found this deep inside the Apps Script API reference.
A spreadsheet ID can be extracted from its URL. For example, the spreadsheet ID in the URL https://docs.google.com/spreadsheets/d/abc1234567/edit#gid=0 is «abc1234567».
Every API method requires a spreadsheetId parameter which is used to identify which spreadsheet is to be accessed or altered. This ID is the value between the «/d/» and the «/edit» in the URL of your spreadsheet. For example, consider the following URL that references a Google Sheets spreadsheet:
The ID of this spreadsheet is 1qpyC0XzvTcKT6EISywvqESX3A0MwQoFDE8p-Bll4hps.
So I just pulled up my spreadsheet and looked at the URL to find my ID.
Hope this helps!
I just created a hyperlink to the sheets and then copied that hyperlink to a text file and the link line shows the GID.
Then I created a pull down list in A52 and then made =IF() logic to go to the GIDs to go to those sheets.
Not the answer you're looking for? Browse other questions tagged java google-apps-script google-sheets or ask your own question.
-
The Overflow Blog
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2022.9.1.42957
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Google Sheets API Overview
The Google Sheets API is a RESTful interface that lets you read and modify a spreadsheet's data. The most common uses of this API include the following tasks:
- Create spreadsheets
- Read and write spreadsheet cell values
- Update spreadsheet formatting
- Manage Connected Sheets
Below is a list of common terms used in the Sheets API:
The primary object in Google Sheets that can contain multiple sheets, each with structured information contained in cells. A Spreadsheet resource represents every spreadsheet and has a unique spreadsheetId value, containing letters, numbers, hyphens, or underscores. You can find the spreadsheet ID in a Google Sheets URL:
https://docs.google.com/spreadsheets/d/ spreadsheetId /edit#gid=0
A page or tab within a spreadsheet. A Sheet resource represents each sheet and has a unique title and numeric sheetId value. You can find the sheet ID in a Google Sheets URL:
An individual field of text or data within a sheet. Cells are arranged in rows and columns, and can be grouped as a range of cells. A CellData resource represents each cell, but it doesn't have a unique ID value. Instead, row and column coordinates identify the cells.
A syntax used to define a cell or range of cells with a string that contains the sheet name plus the starting and ending cell coordinates using column letters and row numbers. This method is the most common and useful when referencing an absolute range of cells.
Show examples
- 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 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.
- ‘My Custom Sheet’!A:A refers to all the cells in the first column of a sheet named «My Custom Sheet.» Single quotes are required for sheet names with spaces, special characters, or an alphanumeric combination.
- ‘My Custom Sheet’ refers to all the cells in ‘My Custom Sheet’.
Tip: Where possible, use distinct names for the objects within your spreadsheets. For example, A1 refers to the cell A1 in the first visible sheet, whereas ‘A1’ refers to all the cells in a sheet named A1. Similarly, Sheet1 refers to all the cells in Sheet1. However, if there’s a named range titled «Sheet1», then Sheet1 refers to the named range and ‘Sheet1’ refers to the sheet.
A syntax used to define a cell or range of cells with a string that contains the sheet name plus the starting and ending cell coordinates using row numbers and column numbers. This method is less common than A1 notation, but can be useful when referencing a range of cells relative to a given cell's position.
Show examples
- Sheet1!R1C1:R2C2 refers to the first two cells in the top two rows of Sheet1.
- R1C1:R2C2 refers to the first two cells in the top two rows of the first visible sheet.
- Sheet1!R[3]C[1] refers to the cell that is three rows below and one column to the right of the current cell.
A defined cell or range of cells with a custom name to simplify references throughout an application. A FilterView resource represents a named range.
A defined cell or range of cells that cannot be modified. A ProtectedRange resource represents a protected range.
Next steps
Get started with Sheets API:
To learn about developing with Google Workspace APIs, including handling authentication and authorization, refer to Develop on Google Workspace.
To learn how to configure and run a simple Sheets API app, read the Quickstarts overview.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Google Sheets API + Python. Чтение и запись с Сервисным Аккаунтом Google Cloud
Google Sheet и Sheets API — классный (простой, бесплатный и универсальный) способ организовать хранение и анализ данных получаемых от своего сервиса. При условии что этих данных не то чтобы очень много и поступают они не то чтобы очень часто.
У меня таких задач хватает и решаю я их либо на Python, либо на PHP. Сегодня возьму в руки Python.
Доступ к Google API
Чтобы писать из кода в Google Sheet нам нужен доступ к Google Sheets API, которое входит в библиотеку API Google Cloud Platform. Для этого нужно:
подключить к проекту в Google Cloud Platform Sheets API
заполнить OAuth consent screen ( пользовательское соглашение )
создать либо OAuth Client ID, либо Service Account
я использую Сервисный Аккаунт, следовательно мне нужно дать сервисному аккаунту доступ к Google Sheet (электронной таблице) с уровнем Редактор, тогда я смогу писать из кода в эту таблицу
получить JSON файл с токеном доступа к сервисному аккаунту и положить его куда-то откуда код сможет его читать
В тексте это выглядит просто, однако в первый раз интерфейс Google Cloud Console выглядит как рубка звездолета. Куда жать не понятно, иные операции нельзя отменить, а некоторые важные данные можно получить только сразу после нажатия на кнопку и никак после (например json файл токена доступа сервисного доступа). Поэтому страаашно.
В первый раз мне пришлось закрыть ЭТО и пойти подышать.
Но разобраться можно, попробуйте. А если не получится, то вот Пост только про токены Google Cloud.
Как дать доступ к таблице Сервисному Аккаунту
Просто беру емейл сервисного аккаунта и расшариваю доступ к электронной таблице Google Sheets, как если бы это был емейл гуглоаккаунта любого другого живого человека. И этому доступу нужно выдать права Редактора, чтобы с Сервисным аккаунтом писать в этот Google Sheet. На стороне Google Cloud ничего дополнительно делать не надо.
Уведомлять Сервисный Аккаунт тоже не обязательно — он же робот, вы чего 😉
Лимиты Google Sheets API
Google почти ко всем своим API доступ выдает БЕСПЛАТНО и без премодерации (в тестовом режиме). Однако ограничивает. К некоторым апи ограничения сильные, а к Sheets API вполне приемлемые.
Read requests per minute 300
Read requests per minute per user 60
Read requests per day UnlimitedWrite requests per minute 300
Write requests per minute per user 60
Write requests per day Unlimited
Каждый execute() тратит эти лимиты, даже если запрос не успешный. Остатки лимитов нельзя узнать программно, из кода. Только посмотреть в браузере в https://console.cloud.google.com/apis/api/sheets.googleapis.com/quotas?project=<id проекта> .
Зависимости для доступа к Sheets API из Python
Мой req.txt выглядит вот так:
Для Python есть пакеты специально для работы с Google Sheets API. Говорят они даже удобные и это, наверняка, так. Но я работаю не только с Sheets API, поэтому предпочитаю использовать большой и не очень удобный google-api-python-client
build ресурса для доступа к Google Sheets API на Python
В google-api-python-client есть универсальный метод googleapiclient.discovery.build , который создает ресурс для работы с любым API Google и с Sheets API в частности. Но сначала нужно куда то в проекте сложить json файл токена доступа сервисного аккаунта.
build у меня в проекте выглядит вот так:
scopes — это уровень доступа, который хочет наше приложение от Google API. Для задач чтения/записи/форматирования в Google Sheet с Сервисным Аккаунтом https://www.googleapis.com/auth/spreadsheets достаточно.
Такое приложение (с Сервисным Аккаунтом) не будет ничего просить от пользователя через браузер, как было бы с OAuth авторизацией. Удобно.
Как узнать spreadsheet_id Google Sheet
Чтобы писать в электронную таблицу, нужно знать её идентификатор. Также нам может понадобиться (при форматировании уж точно) идентификатор листа в электронной таблице. В браузере это все выглядит просто:
Как читать из Google Sheet с API на Python?
Для чтения у нас есть два метода spreadsheets().values().get() и spreadsheets().values().batchGet() . В аргументы им передается идентификатор электронной таблицы Google Sheet и диапазон для чтения.
Диапазон для чтения — это строка вида «Лист!A1:Z999» . Диапазоны, как видно, могут быть на разных листах электронной таблицы.
batchGet в отличии от get может запросить сразу, за один execute() , несколько диапазонов данных, что экономит квоты. Рекомендую сразу и везде использовать только батчевые методы.
Запрос отправляется (и расходуются квоты) только по методу execute().
В ответ мы получаем json (dict), где все очевидно. В поле values двумерный массив с нужными данными.
Как писать в Google Sheet с API на Python?
Для записи есть 3 метода:
append — пытается писать в заданный диапазон, если ячейки в заданном диапазоне заняты данными (не пусты), то пишет в ближайшую пустую ячейку ниже,
update — пишет в заданный диапазон, если ячейки заняты данными — он эти данные перезапишет новыми,
batchUpdate — действует как update, но может за один запрос записать несколько пачек данных в разные диапазоны и сэкономить квоты.
Данные для всех этих методов передаются в аргументе body. Для append / update структура одинакова:
Т.е. values — это простой двумерный массив. А запись выглядит вот так:
range — диапазон для записи, а valueInputOption : ‘RAW’ — значит данные буду писать в ячейку «как есть», не пытаясь, например, в строке разглядеть дату.
Со структурой body для batchUpdate посложнее, но не сильно:
Нужно ли тут что-то объяснять? Напишите в комментарий, если все таки надо.
Ну а метод даже проще чем у update / append :
Конечно есть, особенно при записи, некоторые тонкости. Особенно когда речь заходит про форматирование — все эти строки которые вдруг становятся датами, когда не надо. Числа которые стали строками. Но что-то и так много текста вышло, поэтому пока закругляюсь.
Полезные ссылки
Документация Google Sheets API. Доки, кстати, очень хорошие. Не все API Google так хорошо задокументированы.
На Хабре есть хорошая статья, жаль мне поздно попалась.
Все что в статье — есть в оформленном виде на GitHub ( темы разбросаны по веткам репозитория, просто переключайтесь ).
Как найти идентификатор электронной таблицы Google?
при использовании Api выполнения Google для Java идентификатор электронной таблицы не очень легко понять. Вот фрагмент кода:
любые идеи о том, как найти это. Я запускаю API листов, чтобы вернуть идентификатор электронной таблицы, но он возвращает ссылку, и когда я использую https://spreadsheets.google.com/feeds/spreadsheets/строка или просто строка сам я все равно получаю: «код» : 404, «ошибки» : [ < "домен" : "глобальный", "сообщение" : "запрошенный объект, не найден.", "разум":"не найден"
2 ответов
нашел это глубоко внутри ссылки API скрипта приложений.
идентификатор электронной таблицы можно извлечь из URL-адреса. Например, идентификатор таблицы в URL https://docs.google.com/spreadsheets/d/abc1234567/edit#gid=0 это «abc1234567».
для каждого метода API требуется параметр spreadsheetId, который используется для определения электронной таблицы, к которой необходимо получить доступ или изменить. Этот идентификатор является значением между «/d / » и «/ edit » в URL-адресе электронной таблицы. Например, рассмотрим следующий URL-адрес, который ссылается на таблицу Google Таблицы:
идентификатор этой таблицы 1qpyC0XzvTcKT6EISywvqESX3A0MwQoFde8p-Bll4hps.
поэтому я просто вытащил свою электронную таблицу и посмотрел на URL, чтобы найти свой идентификатор.