- Examples of gspread Usage¶
- Creating a Spreadsheet¶
- Sharing a Spreadsheet¶
- Selecting a Worksheet¶
- Creating a Worksheet¶
- Deleting a Worksheet¶
- Getting a Cell Value¶
- Getting All Values From a Row or a Column¶
- Getting All Values From a Worksheet as a List of Lists¶
- Getting All Values From a Worksheet as a List of Dictionaries¶
- Finding a Cell¶
- Finding All Matched Cells¶
- Clear A Worksheet¶
- Cell Object¶
- Updating Cells¶
- Formatting¶
- Using gspread with pandas¶
- Using gspread with NumPy¶
- Быстрый старт Python, Быстрый старт Python
- Цели
- Предпосылки
- Настройте свою среду
- Включить API
- Настройка экрана согласия OAuth
- Авторизация учетных данных для настольного приложения
- Установите клиентскую библиотеку Google.
- Настроить образец
- Запустите образец
- Следующие шаги
Examples of gspread Usage¶
You can open a spreadsheet by its title as it appears in Google Docs:
sh = gc.open('My poor gym results')
If you have multiple Google Sheets with the same title, only the latest sheet will be opened by this method without throwing an error. It’s recommended to open the sheet using its unique ID instead (see below)
If you want to be specific, use a key (which can be extracted from the spreadsheet’s url):
sht1 = gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE')
Or, if you feel really lazy to extract that key, paste the entire spreadsheet’s url
sht2 = gc.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm. FE&hl')
Creating a Spreadsheet¶
Use create() to create a new blank spreadsheet:
sh = gc.create('A new spreadsheet')
If you’re using a service account , this new spreadsheet will be visible only to this account. To be able to access newly created spreadsheet from Google Sheets with your own Google account you must share it with your email. See how to share a spreadsheet in the section below.
Sharing a Spreadsheet¶
If your email is otto@example.com you can share the newly created spreadsheet with yourself:
sh.share('otto@example.com', perm_type='user', role='writer')
See share() documentation for a full list of accepted parameters.
Selecting a Worksheet¶
Select worksheet by index. Worksheet indexes start from zero:
worksheet = sh.get_worksheet(0)
worksheet = sh.worksheet("January")
Or the most common case: Sheet1:
To get a list of all worksheets:
worksheet_list = sh.worksheets()
Creating a Worksheet¶
worksheet = sh.add_worksheet(title="A worksheet", rows=100, cols=20)
Deleting a Worksheet¶
Getting a Cell Value¶
val = worksheet.acell('B1').value
Or row and column coordinates:
val = worksheet.cell(1, 2).value
If you want to get a cell formula:
cell = worksheet.acell('B1', value_render_option='FORMULA').value # or cell = worksheet.cell(1, 2, value_render_option='FORMULA').value
Getting All Values From a Row or a Column¶
Get all values from the first row:
values_list = worksheet.row_values(1)
Get all values from the first column:
values_list = worksheet.col_values(1)
So far we’ve been fetching a limited amount of data from a sheet. This works great until you need to get values from hundreds of cells or iterating over many rows or columns.
Under the hood, gspread uses Google Sheets API v4. Most of the time when you call a gspread method to fetch or update a sheet gspread produces one HTTP API call.
HTTP calls have performance costs. So if you find your app fetching values one by one in a loop or iterating over rows or columns you can improve the performance of the app by fetching data in one go.
What’s more, Sheets API v4 introduced Usage Limits (as of this writing, 300 requests per 60 seconds per project, and 60 requests per 60 seconds per user). When your application hits that limit, you get an APIError 429 RESOURCE_EXHAUSTED .
Here are the methods that may help you to reduce API calls:
- get_all_values() fetches values from all of the cells of the sheet.
- get() fetches all values from a range of cells.
- batch_get() can fetch values from multiple ranges of cells with one API call.
- update() lets you update a range of cells with a list of lists.
- batch_update() lets you update multiple ranges of cells with one API call.
Getting All Values From a Worksheet as a List of Lists¶
list_of_lists = worksheet.get_all_values()
Getting All Values From a Worksheet as a List of Dictionaries¶
list_of_dicts = worksheet.get_all_records()
Finding a Cell¶
Find a cell matching a string:
cell = worksheet.find("Dough") print("Found something at R%sC%s" % (cell.row, cell.col))
Find a cell matching a regular expression
amount_re = re.compile(r'(Big|Enormous) dough') cell = worksheet.find(amount_re)
find returns None if value is not Found
Finding All Matched Cells¶
Find all cells matching a string:
cell_list = worksheet.findall("Rug store")
Find all cells matching a regexp:
criteria_re = re.compile(r'(Small|Room-tiering) rug') cell_list = worksheet.findall(criteria_re)
Clear A Worksheet¶
Clear one or multiple cells ranges at once:
worksheet.batch_clear(["A1:B1", "C2:E2", "my_named_range"])
Clear the entire worksheet:
Cell Object¶
Each cell has a value and coordinates properties:
value = cell.value row_number = cell.row column_number = cell.col
Updating Cells¶
Or row and column coordinates:
worksheet.update_cell(1, 2, 'Bingo!')
worksheet.update('A1:B2', [[1, 2], [3, 4]])
Formatting¶
Here’s an example of basic formatting.
Set A1:B1 text format to bold:
worksheet.format('A1:B1', 'textFormat': 'bold': True>>)
Color the background of A2:B2 cell range in black, change horizontal alignment, text color and font size:
worksheet.format("A2:B2", "backgroundColor": "red": 0.0, "green": 0.0, "blue": 0.0 >, "horizontalAlignment": "CENTER", "textFormat": "foregroundColor": "red": 1.0, "green": 1.0, "blue": 1.0 >, "fontSize": 12, "bold": True > >)
The second argument to format() is a dictionary containing the fields to update. A full specification of format options is available at CellFormat in Sheet API Reference.
gspread-formatting offers extensive functionality to help you when you go beyond basics.
Using gspread with pandas¶
pandas is a popular library for data analysis. The simplest way to get data from a sheet to a pandas DataFrame is with get_all_records() :
import pandas as pd dataframe = pd.DataFrame(worksheet.get_all_records())
Here’s a basic example for writing a dataframe to a sheet. With update() we put the header of a dataframe into the first row of a sheet followed by the values of a dataframe:
import pandas as pd worksheet.update([dataframe.columns.values.tolist()] + dataframe.values.tolist())
For advanced pandas use cases check out these libraries:
Using gspread with NumPy¶
NumPy is a library for scientific computing in Python. It provides tools for working with high performance multi-dimensional arrays.
Read contents of a sheet into a NumPy array:
import numpy as np array = np.array(worksheet.get_all_values())
The code above assumes that your data starts from the first row of the sheet. If you have a header row in the first row, you need replace worksheet.get_all_values() with worksheet.get_all_values()[1:] .
Write a NumPy array to a sheet:
import numpy as np array = np.array([[1, 2, 3], [4, 5, 6]]) # Write the array to worksheet starting from the A2 cell worksheet.update('A2', array.tolist())
© Copyright 2023, Anton Burnashev Revision e0fbbe88 .
Быстрый старт Python, Быстрый старт Python
Оптимизируйте свои подборки Сохраняйте и классифицируйте контент в соответствии со своими настройками.
В кратких руководствах объясняется, как настроить и запустить приложение, которое вызывает API Google Workspace.
В кратких руководствах по Google Workspace используются клиентские библиотеки API для обработки некоторых деталей процесса аутентификации и авторизации. Мы рекомендуем вам использовать клиентские библиотеки для ваших собственных приложений. В этом кратком руководстве используется упрощенный подход к проверке подлинности, подходящий для среды тестирования. Для рабочей среды мы рекомендуем изучить аутентификацию и авторизацию, прежде чем выбирать учетные данные для доступа , подходящие для вашего приложения.
Создайте приложение командной строки Python, которое отправляет запросы к API Google Таблиц.
Цели
- Настройте свою среду.
- Установите клиентскую библиотеку.
- Настройте образец.
- Запустите образец.
Предпосылки
Для запуска этого краткого руководства необходимы следующие предварительные условия:
- Python 3.10.7 или выше
- Инструмент управления пакетами pip
- Облачный проект Google .
- Аккаунт Google.
Настройте свою среду
Для завершения этого краткого руководства настройте свою среду.
Включить API
Настройка экрана согласия OAuth
Если вы используете новый проект Google Cloud для выполнения этого краткого руководства, настройте экран согласия OAuth и добавьте себя в качестве тестового пользователя. Если вы уже выполнили этот шаг для своего облачного проекта, перейдите к следующему разделу.
- В консоли Google Cloud выберите menu >API и службы >Экран согласия OAuth . Перейти к экрану согласия OAuth
- Выберите тип пользователя для своего приложения, затем нажмите «Создать» .
- Заполните регистрационную форму приложения, затем нажмите «Сохранить и продолжить» .
- На данный момент вы можете пропустить добавление областей и нажать «Сохранить и продолжить» . В будущем, когда вы будете создавать приложение для использования за пределами вашей организации Google Workspace, вы должны будете добавить и проверить области авторизации, необходимые вашему приложению.
- Если вы выбрали Внешний для типа пользователя, добавьте тестовых пользователей:
- В разделе «Проверить пользователей» нажмите «Добавить пользователей» .
- Введите свой адрес электронной почты и любых других авторизованных тестовых пользователей, затем нажмите «Сохранить и продолжить» .
Авторизация учетных данных для настольного приложения
- В консоли Google Cloud выберите menu >API и службы >Учетные данные . Перейти к учетным данным
- Нажмите «Создать учетные данные» >«Идентификатор клиента OAuth» .
- Нажмите Тип приложения >Приложение для ПК .
- В поле Имя введите имя учетных данных. Это имя отображается только в консоли Google Cloud.
- Щелкните Создать . Появится экран создания клиента OAuth, показывающий ваш новый идентификатор клиента и секрет клиента.
- Нажмите ОК . Вновь созданные учетные данные отображаются в разделе идентификаторов клиентов OAuth 2.0.
- Сохраните загруженный JSON-файл как credentials.json и переместите файл в свой рабочий каталог.
Установите клиентскую библиотеку Google.
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
Настроить образец
- В рабочем каталоге создайте файл с именем quickstart.py .
- Включите следующий код в quickstart.py :
from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] # The ID and range of a sample spreadsheet. SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' SAMPLE_RANGE_NAME = 'Class Data!A2:E' def main(): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) try: service = build('sheets', 'v4', credentials=creds) # Call the Sheets API sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME).execute() values = result.get('values', []) if not values: print('No data found.') return print('Name, Major:') for row in values: # Print columns A and E, which correspond to indices 0 and 4. print('%s, %s' % (row[0], row[4])) except HttpError as err: print(err) if __name__ == '__main__': main()
Запустите образец
- Если вы еще не вошли в свою учетную запись Google, вам будет предложено выполнить вход. Если вы вошли в несколько учетных записей, выберите одну учетную запись для авторизации.
- Нажмите Принять .
Информация об авторизации хранится в файловой системе, поэтому при следующем запуске примера кода авторизация не запрашивается.
Вы успешно создали свое первое приложение Python, которое отправляет запросы к API Google Таблиц.
Следующие шаги
Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons «С указанием авторства 4.0», а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2023-07-25 UTC.