能否通过Python批量编辑用户权限、批量访问数百个Google Sheets?
可行解决方案
以下两种方案都可以解决你无需逐个手动授权的需求:
方案1:批量给服务账号开通所有表格权限
利用你个人账号对所有表格的访问权限,调用Google Drive API批量添加权限,操作步骤如下:
- 在你现有的Google Developer Console项目中启用Google Drive API
- 用个人账号做OAuth2授权调用Drive API,不要使用服务账号密钥鉴权
- 调用
files.list接口筛选所有目标表格:如果600个表格都存放在同一个云盘文件夹下,可直接指定父文件夹ID做过滤,否则筛选MIME类型为application/vnd.google-apps.spreadsheet的文件即可 - 遍历所有匹配的表格ID,调用
permissions.create接口,给每个表格添加服务账号的访问权限,权限参数可选reader(只读)或writer(读写),根据你的实际需求设置即可 - 可添加简单的异常捕获逻辑,避免个别表格授权失败中断整体流程
示例Python代码片段:
from googleapiclient.discovery import build from google.oauth2.credentials import Credentials # 这里的creds是你个人账号OAuth授权得到的凭证 drive_service = build('drive', 'v3', credentials=creds) service_account_email = "你的服务账号邮箱" # 替换为你的目标文件夹ID,不限文件夹的话去掉q参数里的父文件夹过滤 response = drive_service.files().list(q="mimeType='application/vnd.google-apps.spreadsheet' and '你的文件夹ID' in parents", fields='files(id, name)').execute() spreadsheets = response.get('files', []) for sheet in spreadsheets: permission = { 'type': 'user', 'role': 'reader', 'emailAddress': service_account_email } drive_service.permissions().create(fileId=sheet['id'], body=permission, sendNotificationEmail=False).execute()
方案2:直接用个人账号OAuth授权访问,完全不需要服务账号
这个方案不需要给服务账号开任何权限,直接用你本人的谷歌账号鉴权调用Sheets API读取数据,操作更简单:
- 在Google Cloud项目中创建桌面应用类型的OAuth 2.0客户端ID,下载客户端密钥文件到本地
- Python端使用
google-auth-oauthlib库完成授权,首次运行时会弹出浏览器窗口,用你有权限的谷歌账号登录授权即可,授权后会在本地生成token缓存文件,后续运行不需要重复授权 - 直接调用Sheets API遍历所有表格ID,提取你需要的指定列数据即可,只要你个人账号有权限的表格都可以直接访问
示例Python代码片段:
from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import os.path import pickle # 如果只需要读表格,用这个scope就行 SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] creds = None # 本地缓存的token文件 if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # 没有有效凭证就重新授权 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) # 保存凭证到本地下次用 with open('token.pickle', 'wb') as token: pickle.dump(creds, token) sheets_service = build('sheets', 'v4', credentials=creds) # 替换为你要提取的列范围,比如'A:A'就是第一列 target_range = 'Sheet1!A:A' # 遍历所有表格ID读取数据 for sheet_id in 你的所有表格ID列表: result = sheets_service.spreadsheets().values().get(spreadsheetId=sheet_id, range=target_range).execute() values = result.get('values', []) # 这里处理你拿到的列数据
注意事项
- Google API默认有每分钟请求数配额,600个表格的请求量完全在默认配额范围内,如果触发限流可以在每次请求后加0.5秒左右的等待时间
- 如果后续会新增同类型的表格,方案2更适配,不需要额外处理权限,只要你个人账号能访问就可以直接读取
内容的提问来源于stack exchange,提问作者purpletube
相关产品推荐
相关产品推荐

