检索 google sheet 值 google sheet api 公司限制点差 sheet

Retrieving google sheet values with google sheet api on company restricted spreadsheet

我希望能够阅读我工作的公司内部与我共享的电子表格。 我已经尝试从这个 改编脚本。 这是我使用的代码:

from apiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials
import httplib2

scope = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]

SERVICE_ACCOUNT_FILE = "gsheetread-293005-d7e75122e4c7.json"

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=scope)

# Use the create_delegated() method and authorize the delegated credentials
delegated_credentials = credentials.create_delegated('myemail@company.com')
delegated_http = delegated_credentials.authorize(httplib2.Http())

google_sheet = discovery.build('spreadsheet_id', 'v3', http=delegated_http)

我收到一个错误:

oauth2client.client.HttpAccessTokenRefreshError: unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.

您收到的错误意味着您没有添加部分或全部指定范围(https://www.googleapis.com/auth/spreadsheetshttps://www.googleapis.com/auth/drive) 在向您的服务帐户授予 domain-wide 权限时。请关注these steps:

在第 5 步中,您必须同时添加 https://www.googleapis.com/auth/spreadsheetshttps://www.googleapis.com/auth/drive(实际上,如果您只是访问电子表格,您只需要添加一个,但您应该从代码中删除另一个)。

补充说明:

  • 您正在使用的库 oauth2client,而不是 is deprecated. Use google-auth,它不依赖于 httplib2
  • 您没有使用有效的服务名称 (spreadsheet_id)。如果要使用 Sheets API,服务名称应为 sheets.
  • Sheets API V3 is deprecated and will be shut down in January 2021. Use V4 代替。
  • 正如我之前提到的,如果您正在访问电子表格,则无需使用 drive 范围。 spreadsheets 够了。

代码片段(使用 non-deprecated 库):

from googleapiclient.discovery import build
from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
SERVICE_ACCOUNT_FILE = "gsheetread-293005-d7e75122e4c7.json"

creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = creds.with_subject('myemail@company.com')
service = build('sheets', 'v4', credentials=delegated_credentials)
spreadsheet = service.spreadsheets().get(spreadsheetId="YOUR_SPREADSHEET_ID").execute()
print(spreadsheet)