You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用Google Sheets API创建空白表格后无访问权限问题求助

问题解决方案

根因说明

你当前使用服务账号凭证调用Google Sheets API创建表格,服务账号是独立于个人谷歌账号的虚拟身份,新建表格默认所有权归该服务账号所有,你的个人谷歌账号未被授予访问权限,因此访问链接时会提示无权限。

修改代码步骤

你已经在权限范围中添加了Drive相关权限,只需要在创建表格完成后追加权限分配逻辑即可,完整修改后的代码如下:

"""
BEFORE RUNNING:
---------------
1. 提前启用Google Sheets API和Google Drive API
2. 运行`pip install --upgrade google-api-python-client`安装依赖
"""
from pprint import pprint
from googleapiclient import discovery
from google.oauth2 import service_account

SERVICE_ACCOUNT_FILE = 'client_secret.json'

SCOPES = ["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive"]

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

# 构建Sheets和Drive服务实例
sheets_service = discovery.build('sheets', 'v4', credentials=credentials)
drive_service = discovery.build('drive', 'v3', credentials=credentials)

spreadsheet_body = {}

# 创建空白表格
request = sheets_service.spreadsheets().create(body=spreadsheet_body)
response = request.execute()

# 给个人账号分配权限,替换为你自己的谷歌邮箱
personal_email = "你的谷歌邮箱地址@gmail.com"
permission_config = {
    "type": "user",
    "role": "owner", # 仅需要编辑权限的话可以改成writer
    "emailAddress": personal_email
}
# 执行授权,transferOwnership参数仅在设置role为owner时需要
drive_service.permissions().create(
    fileId=response["spreadsheetId"],
    body=permission_config,
    transferOwnership=True,
    sendNotificationEmail=False
).execute()

pprint(response)

注意事项

  • 若不需要将表格所有权转移到个人账号,仅需要编辑权限,将role改为writer,同时删除transferOwnership=True参数即可
  • 若需要生成公开可访问的表格,将permission_config修改为:
    permission_config = {
        "type": "anyone",
        "role": "reader"
    }
    
    该配置会让所有知道链接的用户都可以查看表格,按需使用。

内容的提问来源于stack exchange,提问作者Orestis D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:39:01