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

如何使用服务账号授权Google Sheets,通过Python读取私有表格数据

Python读取私有Google Sheet转JSON解决方案

前置依赖安装

首先安装需要的Google API相关工具包:

pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client

方案1:使用已生成的桌面端OAuth client_secret文件

你提到的传入client_secret文件的方法是存在的,直接使用google-auth-oauthlib库的内置方法加载即可,完整实现逻辑如下:

  1. 将下载的client_secret_xxx.json文件放到你的Python脚本同级目录
  2. 编写认证和读表代码:
import os.path
import json
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# 定义API访问权限,只读的话用下面的范围即可
SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"]

# 替换为你自己的Google Sheet ID,以及要读取的工作表范围
SPREADSHEET_ID = "替换为你的表格ID"
RANGE_NAME = "Sheet1!A:Z" # 示例为读取Sheet1的所有行列,可按需修改

def main():
    creds = None
    # 首次授权后会生成token.json存储凭据,下次运行不用重复授权
    if os.path.exists("token.json"):
        creds = Credentials.from_authorized_user_file("token.json", SCOPES)
    # 没有有效凭据时走授权流程
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            # 这里直接传入你下载的client_secret文件路径即可
            flow = InstalledAppFlow.from_client_secrets_file(
                "client_secret.json", SCOPES
            )
            creds = flow.run_local_server(port=0)
        # 保存凭据供下次使用
        with open("token.json", "w") as token:
            token.write(creds.to_json())

    try:
        service = build("sheets", "v4", credentials=creds)
        # 调用API读取表格数据
        sheet = service.spreadsheets()
        result = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute()
        values = result.get("values", [])
        if not values:
            print("未读取到表格数据")
            return

        # 将表格数据转换为JSON格式,默认第一行为表头
        header = values[0]
        data_list = []
        for row in values[1:]:
            # 补全行长度和表头一致,避免数据错位
            while len(row) < len(header):
                row.append("")
            row_dict = dict(zip(header, row))
            data_list.append(row_dict)
        
        # 生成JSON对象
        json_data = json.dumps(data_list, ensure_ascii=False, indent=2)
        print(json_data)
        return json_data

    except HttpError as err:
        print(f"API请求错误: {err}")

if __name__ == "__main__":
    main()

首次运行代码会自动弹出浏览器,选择你拥有该Google Sheet访问权限的账号完成授权即可,后续运行会自动读取token.json的凭据,无需重复授权。

方案2:使用已创建的服务账号(更适合自动化场景)

如果你的脚本需要无人值守运行,用服务账号的方式更方便,不需要手动授权:

  1. 到Google Cloud后台服务账号页面下载对应服务账号的JSON密钥文件,放到脚本同级目录
  2. 实现代码如下:
import json
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"]
SPREADSHEET_ID = "替换为你的表格ID"
RANGE_NAME = "Sheet1!A:Z"
# 替换为你下载的服务账号密钥文件名
SERVICE_ACCOUNT_KEY = "service_account_key.json"

def main():
    creds = ServiceAccountCredentials.from_json_keyfile_name(SERVICE_ACCOUNT_KEY, SCOPES)
    try:
        service = build("sheets", "v4", credentials=creds)
        sheet = service.spreadsheets()
        result = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute()
        values = result.get("values", [])
        if not values:
            print("未读取到数据")
            return
        # 转JSON的逻辑和方案1一致
        header = values[0]
        data_list = [dict(zip(header, row + [""]*(len(header)-len(row)))) for row in values[1:]]
        json_data = json.dumps(data_list, ensure_ascii=False, indent=2)
        print(json_data)
        return json_data
    except HttpError as err:
        print(f"请求错误: {err}")

if __name__ == "__main__":
    main()

注意确保你已经将服务账号的邮箱地址添加到目标Google Sheet的共享用户列表中,且授予了至少查看权限。

内容的提问来源于stack exchange,提问作者kelsey-debug

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:27:02