Google sheet api python

Python Google Sheets – An easy way to use Google API

Google Sheets API is a robust RESTful Google Sheets API that allows us to interact with Google Sheets easily. It allows you to work with spreadsheets in various ways, including creating or modifying sheets, retrieving data from sheets, and much more without worrying about data size.

This can save you time if you regularly deal with vast data sets, such as importing data into spreadsheets or analyzing data models on Google Sheets. Additionally, you can automate various low-value tasks. This article describes how to use the Python Google Sheets API library “gspread” to start working with one of the most widely used services on the Google Cloud Platform – Google Sheets.

Table of contents

Advantages of Using Python with Google Sheets

Python is a powerful programming language widely used in many industries today. For beginners, Python is easy to learn and has many advanced features for experienced programmers. Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Python’s simple syntax, dynamic typing, and interpreted nature make it an ideal language for scripting and rapid application development in many areas on most platforms. Python’s ecosystem consists of many data analysis, visualization, and Machine Learning libraries.

Читайте также:  Link css asp net

One of the advantages of using Python with the sheets API is that it is easy to integrate your data with NumPy or Pandas for data analysis or Matplotlib, Bokeh, and Plotly for data visualization.

  1. Create, view, and edit: Google Sheets enables users to create, view, and edit spreadsheets, allowing for efficient collaboration and data management.
  2. Autosave: Google Sheets automatically saves your work as you edit, ensuring you never lose your progress.
  3. Real-time: Google Sheets supports real-time collaboration, allowing multiple users to work on a spreadsheet simultaneously, making sharing and updating information easier.
  4. Fast and responsive UI: Google Sheets is fast and responsive, thanks to Google’s powerful infrastructure, providing a seamless user experience.
  5. Multiple sheets support: You can easily create additional sheets within a Google Sheets document to better organize your data and make it easier to find information.
  6. Seamless Excel integration: Google Sheets allows users to work seamlessly across Sheets and Excel, making collaborating and managing data easier across different platforms.
  7. Part of Google Workspace: Google Sheets is part of the Google Workspace suite of productivity tools, which includes other applications such as Google Docs, Google Slides, and Google Forms.
  8. Maintain control with enterprise-grade security: Google Sheets offers enterprise-grade security features, ensuring your data remains secure and protected while collaborating with others.
  9. Powered by Google AI: Google Sheets leverages AI-powered features to provide smart suggestions, data analysis, and other advanced capabilities to enhance your spreadsheet experience.
  10. Build custom solutions: With the Google Sheets API, you can create custom solutions tailored to your specific needs, such as automating data entry, generating reports, and integrating with other applications.
  11. Google APIs Explorer: The Google APIs Explorer allows you to try Google API methods without writing code, making it easier to test and understand the capabilities of the Google Sheets API.
Читайте также:  Microsoft office 2010 html

Demo Google Sheet Document

First, we need to prepare a Google Sheet with some sample data. The Google Sheet that I will be using for this article contains the following datasets:

Источник

Быстрый старт Python, Быстрый старт Python

Оптимизируйте свои подборки Сохраняйте и классифицируйте контент в соответствии со своими настройками.

В кратких руководствах объясняется, как настроить и запустить приложение, которое вызывает API Google Workspace.

В кратких руководствах по Google Workspace используются клиентские библиотеки API для обработки некоторых деталей процесса аутентификации и авторизации. Мы рекомендуем вам использовать клиентские библиотеки для ваших собственных приложений. В этом кратком руководстве используется упрощенный подход к проверке подлинности, подходящий для среды тестирования. Для рабочей среды мы рекомендуем изучить аутентификацию и авторизацию, прежде чем выбирать учетные данные для доступа , подходящие для вашего приложения.

Создайте приложение командной строки Python, которое отправляет запросы к API Google Таблиц.

Цели

  • Настройте свою среду.
  • Установите клиентскую библиотеку.
  • Настройте образец.
  • Запустите образец.

Предпосылки

Для запуска этого краткого руководства необходимы следующие предварительные условия:

  • Python 3.10.7 или выше
  • Инструмент управления пакетами pip
  • Облачный проект Google .
  • Аккаунт Google.

Настройте свою среду

Для завершения этого краткого руководства настройте свою среду.

Включить API

Настройка экрана согласия OAuth

Если вы используете новый проект Google Cloud для выполнения этого краткого руководства, настройте экран согласия OAuth и добавьте себя в качестве тестового пользователя. Если вы уже выполнили этот шаг для своего облачного проекта, перейдите к следующему разделу.

  1. В консоли Google Cloud выберите menu >API и службы >Экран согласия OAuth . Перейти к экрану согласия OAuth
  2. Выберите тип пользователя для своего приложения, затем нажмите «Создать» .
  3. Заполните регистрационную форму приложения, затем нажмите «Сохранить и продолжить» .
  4. На данный момент вы можете пропустить добавление областей и нажать «Сохранить и продолжить» . В будущем, когда вы будете создавать приложение для использования за пределами вашей организации Google Workspace, вы должны будете добавить и проверить области авторизации, необходимые вашему приложению.
  5. Если вы выбрали Внешний для типа пользователя, добавьте тестовых пользователей:
    1. В разделе «Проверить пользователей» нажмите «Добавить пользователей» .
    2. Введите свой адрес электронной почты и любых других авторизованных тестовых пользователей, затем нажмите «Сохранить и продолжить» .

    Авторизация учетных данных для настольного приложения

    1. В консоли Google Cloud выберите menu >API и службы >Учетные данные . Перейти к учетным данным
    2. Нажмите «Создать учетные данные» >«Идентификатор клиента OAuth» .
    3. Нажмите Тип приложения >Приложение для ПК .
    4. В поле Имя введите имя учетных данных. Это имя отображается только в консоли Google Cloud.
    5. Щелкните Создать . Появится экран создания клиента OAuth, показывающий ваш новый идентификатор клиента и секрет клиента.
    6. Нажмите ОК . Вновь созданные учетные данные отображаются в разделе идентификаторов клиентов OAuth 2.0.
    7. Сохраните загруженный JSON-файл как credentials.json и переместите файл в свой рабочий каталог.

    Установите клиентскую библиотеку Google.

    pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib 

    Настроить образец

    1. В рабочем каталоге создайте файл с именем quickstart.py .
    2. Включите следующий код в 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()

    Запустите образец

    1. Если вы еще не вошли в свою учетную запись Google, вам будет предложено выполнить вход. Если вы вошли в несколько учетных записей, выберите одну учетную запись для авторизации.
    2. Нажмите Принять .

    Информация об авторизации хранится в файловой системе, поэтому при следующем запуске примера кода авторизация не запрашивается.

    Вы успешно создали свое первое приложение Python, которое отправляет запросы к API Google Таблиц.

    Следующие шаги

    Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons «С указанием авторства 4.0», а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.

    Последнее обновление: 2023-07-13 UTC.

    Источник

Оцените статью