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

如何通过Google API与服务账号自动下载谷歌表格文件

解决方案

关键前提

必须将你的服务账号邮箱(id_1234@id_1234.iam.gserviceaccount.com)共享到目标Google表格中,赋予查看权限,否则服务账号无法访问该文件。

代码修正与完整实现

原代码的认证逻辑有误,且Google Sheets不能直接用Drive API的普通下载方法,需要指定导出格式。以下是完整可运行的代码:

import os
import io
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload
from google.oauth2 import service_account

# 1. 配置服务账号凭证路径
CRED_PATH = "./cred.json"
# 2. 目标Google Sheets文件ID(从表格URL中提取,比如https://docs.google.com/spreadsheets/d/XXX/edit中的XXX)
SPREADSHEET_ID = "你的表格ID"
# 3. 导出格式(支持xlsx、csv、pdf等,这里以xlsx为例)
EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
# 4. 保存的本地文件名
OUTPUT_FILE = "./daily_sheet.xlsx"

def download_google_sheet():
    try:
        # 加载服务账号凭证
        credentials = service_account.Credentials.from_service_account_file(
            CRED_PATH,
            scopes=["https://www.googleapis.com/auth/drive.readonly"]
        )

        # 构建Drive API服务
        with build("drive", "v3", credentials=credentials) as service:
            # 调用Drive API的导出接口,获取文件流
            request = service.files().export_media(
                fileId=SPREADSHEET_ID,
                mimeType=EXPORT_MIME_TYPE
            )
            fh = io.FileIO(OUTPUT_FILE, mode="wb")
            downloader = MediaIoBaseDownload(fh, request)

            # 执行下载
            done = False
            while done is False:
                status, done = downloader.next_chunk()
                print(f"下载进度: {int(status.progress() * 100)}%")

        print(f"文件已成功保存到 {OUTPUT_FILE}")

    except HttpError as error:
        print(f"API请求出错: {error}")
    except Exception as e:
        print(f"未知错误: {e}")

if __name__ == "__main__":
    download_google_sheet()

代码说明

  • 凭证加载:直接使用service_account.Credentials.from_service_account_file加载cred.json,比环境变量方式更直观。
  • 导出格式:可选的MIME类型包括:
    • CSV格式:text/csv
    • PDF格式:application/pdf
    • ODS格式:application/vnd.oasis.opendocument.spreadsheet
  • 文件ID获取:打开目标Google表格,URL中的d/和/edit之间的字符串就是文件ID。

每日自动执行设置

Linux/macOS(用crontab)

  1. 打开crontab配置:crontab -e
  2. 添加定时任务(比如每天凌晨3点执行):
0 3 * * * /usr/bin/python3 /path/to/your/script.py >> /path/to/logfile.log 2>&1

Windows(用任务计划程序)

  1. 创建新任务,设置触发时间为每日指定时段。
  2. 操作选择启动程序,指向你的Python解释器路径和脚本文件路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 16:27:30