使用Google Drive API下载Excel文件无法获取最新版本问题
Google Drive下载含新工作表的Excel文件时获取旧版本的问题解决
问题描述
使用Google Drive API(通过build('drive', 'v3', credentials=creds))或基于requests的下载脚本时,下载得到的Excel文件是旧版本,无法获取刚在Google Sheets编辑器中添加的新工作表。
复现步骤:
- 在Google Sheets编辑器中打开目标文件
- 添加新工作表
- 执行API或脚本下载操作,多数情况下得到不含新工作表的旧文件
解决方案
1. 使用Google Drive API的导出接口
不要用普通文件下载接口,改用export_media接口,指定Excel格式的MIME类型,确保从Sheets实时数据生成文件:
from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseDownload import io # 替换为你的认证凭证 creds = 你的认证信息 drive_service = build('drive', 'v3', credentials=creds) file_id = '目标文件ID' # 发起导出请求,指定Excel格式的MIME类型 request = drive_service.files().export_media( fileId=file_id, mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) fh = io.FileIO('output.xlsx', 'wb') downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print(f"下载进度: {int(status.progress() * 100)}%")
2. 修改requests下载脚本
原脚本使用的是Drive通用下载接口,易命中缓存。改用Google Sheets专属导出接口,直接从实时数据生成Excel:
import os import requests def download_latest_sheet_as_excel(file_id, destination): # 调用Sheets专属导出接口,指定xlsx格式 URL = f"https://docs.google.com/spreadsheets/d/{file_id}/export?format=xlsx" session = requests.Session() response = session.get(URL, stream=True) # 处理可能的下载验证(公开文件通常无需此步骤,保留以兼容私有文件) token = None for key, value in response.cookies.items(): if key.startswith('download_warning'): token = value break if token: response = session.get(f"{URL}&confirm={token}", stream=True) # 分块保存文件 CHUNK_SIZE = 32768 with open(destination, "wb") as f: for chunk in response.iter_content(CHUNK_SIZE): if chunk: f.write(chunk) if __name__ == "__main__": file_id = '1JI17N-NFAIOxX_2Y88gmuKMlsuGhBPcB' home = os.getenv('HOME') destination = f'{home}/Downloads/test-drive-download/output.xlsx' download_latest_sheet_as_excel(file_id, destination)
问题原因
Google Sheets编辑器修改后,需要短暂时间同步到Drive底层存储。通用Drive下载接口会优先返回缓存的旧版本文件,而Sheets专属导出接口和Drive API的export接口会直接从Sheets的实时数据生成目标格式文件,绕过缓存,从而获取最新内容。
内容的提问来源于stack exchange,提问作者Mauricio
相关产品推荐
相关产品推荐

