使用Python下载Google Sheet时XLS文件乱码问题排查
Google Sheet下载后XLS乱码问题排查与解决
问题根源分析
- 错误的请求URL:你使用的
google_docs_link是浏览器打开表格的网页链接,返回的是HTML页面内容,而非实际的XLS二进制文件。将HTML内容直接保存为.xls后缀的文件,打开时自然会出现乱码。 - 无效的认证方式:
requests.get的auth=(user,password)是HTTP基本认证,Google Sheets目前不支持这种认证方式,即使返回状态码200,也可能只是返回了未授权的HTML页面,而非目标表格数据。
解决方案
方案1:下载公开共享的Google Sheet(无需认证)
如果你的表格设置了公开可查看/导出,使用Google Sheets专属的导出URL即可:
- 从浏览器链接中提取表格ID:比如链接
https://docs.google.com/spreadsheets/d/abc123xyz/edit中的abc123xyz就是表格ID。 - 构造导出URL并请求:
import requests spreadsheet_id = "你的表格ID" # 指定导出格式为xls export_url = f"https://docs.google.com/spreadsheets/d/{spreadsheet_id}/export?format=xls" resp = requests.get(export_url) # 可验证响应内容类型是否正确(正常应为application/vnd.ms-excel) print(resp.headers.get('Content-Type')) with open('C:\\AAA\\exportdata.xls', "wb") as o: o.write(resp.content)
方案2:下载需要权限的Google Sheet(OAuth2认证)
对于需要登录权限的表格,推荐使用gspread库配合Google OAuth2认证,步骤如下:
- 安装依赖:
pip install gspread oauth2client pandas
- 在Google Cloud控制台创建服务账号并下载JSON密钥文件(流程:创建项目 → 启用Google Sheets API → 创建服务账号 → 下载密钥),并给该服务账号授予表格的访问权限(在表格共享中添加服务账号邮箱)。
- 编写代码导出:
import gspread from oauth2client.service_account import ServiceAccountCredentials import pandas as pd # 设置认证范围 scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] # 加载服务账号密钥文件 creds = ServiceAccountCredentials.from_json_keyfile_name('你的密钥文件.json', scope) client = gspread.authorize(creds) # 打开目标表格(可通过名称或ID) spreadsheet = client.open("表格名称") worksheet = spreadsheet.sheet1 # 选择第一个工作表 # 获取所有数据并保存为XLS data = worksheet.get_all_records() df = pd.DataFrame(data) df.to_excel('C:\\AAA\\exportdata.xls', index=False)
内容的提问来源于stack exchange,提问作者SumitGandhi
相关产品推荐
相关产品推荐

