使用 python3 在 Google 个工作表上访问电子表格

Accessing a spreadsheet on Google Sheets using python3


我正在尝试使用电子表格的 google api (v4) 从个人电子表格中读取。
我从示例 google 复制了代码,同时更改了电子表格 ID、范围名称和范围。
无论我做什么(制作电子表格 public 等),我都会收到 HttpError: 404 Requested entity was not found.

我的代码:

import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly',
        'https://www.googleapis.com/auth/spreadsheets',
        'https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/drive.readonly']
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'python'

def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
            'sheets.googleapis.com-python.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = tools.run_flow(flow, store, None)
    return credentials

def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
            'version=v4')
    service = discovery.build('sheets', 'v4', http = http,
            discoveryServiceUrl = discoveryUrl)
    spreadsheetId = 'ID'
    rangeName = 'RANGE'
    result = service.spreadsheets().values().get(
            spreadsheetId = spreadsheetId, range = rangeName).execute()

您尚未设置 file/spreadsheet ID 或有效的单元格范围。您还有很多额外的代码,可能包括比您需要的更多的范围。这是您可以借用的更短的一个,它只转储 Sheet 的内容,只需要 RO-scope:

from pprint import pprint

from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools

SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
SHEETS = discovery.build('sheets', 'v4', http=creds.authorize(Http()))

SHEET_ID = 'YOUR_SHEET_DRIVE_FILE_ID'
rows = SHEETS.spreadsheets().values().get(spreadsheetId=SHEET_ID,
    range='Sheet1', fields='values').execute().get('values', [])
pprint(rows)

在你 运行 它之前(它将 运行 在 Python 2 和 3 上未经修改),确保你已经...

如果您仍然遇到任何类型的错误,请post将其作为对上述 OP 的更新。 FWIW,我制作了几个视频来演示 Sheets API 的其他用途,以防其他代码示例有所帮助。

(所有较新的视频都将成为 this video series 的一部分,后者侧重于各种 G Suite API。)

看到问题中的大量样板代码和之前看似简单任务的答案,我想使用 pygsheets.

分享我的秘诀

为了能够从 Python 脚本访问 Google 工作表 API,我已经在 Google API 仪表板上注册并选择了 Signed Credentials 选项在 Authorizing pygsheets.

中描述

我已经从 Google API 下载了一个带有凭据的 json 文件,并将其保存在与我的 Python 脚本相同的目录中。 json 文件包含一个看起来像

的专用电子邮件地址

x-...updater@x...updater.iam.gserviceaccount.com

为了脚本能够访问我的 Google sheet 我已经将我的 sheet(使用默认设置 'Can edit')与包含在json 文件。

然后 Python 访问 Google sheet 的代码可能如下所示:

import pygsheets
import pandas as pd

gc = pygsheets.authorize(service_file='service_creds.json')
sh = gc.open('Export Data')
wks_export = sh.worksheet(property='title', value='Export by Month')

# Google worksheet as Pandas dataframe.   
export_df = wks_export.get_as_df()

# Here can be done some local operations on the dataframe.

# Updating the worksheet with the values from the modified dataframe.
wks_export.set_dataframe(export_df, start='A1', fit=True)