遇到 "Google Sheets API has not been used in project" 的 403 错误通常是因为项目没有启用 Google Sheets API 或者没有正确设置 API 密钥。下面是解决这个问题的步骤:
打开 Google Cloud Platform 控制台:https://console.developers.google.com/
创建一个新的项目,或者选择现有的项目。
在左上角的搜索框中搜索 "Google Sheets API" 并选择该 API。
点击 "启用" 来启用 Google Sheets API。
在左侧菜单中,点击 "凭据"。
点击 "创建凭据",选择 "API 密钥"。
在弹出窗口中,复制生成的 API 密钥。
运行 Python 示例代码之前,请确保已经安装了 google-auth
和 google-auth-oauthlib
库。你可以使用以下命令安装它们:
pip install google-auth google-auth-oauthlib
在 Python 代码中,导入所需的库:
from google.oauth2 import service_account
import gspread
使用刚才复制的 API 密钥创建一个服务帐号凭据:
credentials = service_account.Credentials.from_service_account_file('path/to/service_account_key.json')
将 'path/to/service_account_key.json'
替换为你下载的服务帐号密钥的路径。
使用凭据打开 Google Sheets:
gc = gspread.authorize(credentials)
现在你可以按照示例代码进行操作了,例如读取或写入数据。
如果你仍然遇到问题,请确保你的 Google Sheets API 已正确启用,并且你正在使用正确的 API 密钥。
上一篇:按照Python格式输出进行分组
下一篇:按照PYTHON列的索引设置索引