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

使用Python下载Google Sheet时XLS文件乱码问题排查

Google Sheet下载后XLS乱码问题排查与解决

问题根源分析

  1. 错误的请求URL:你使用的google_docs_link是浏览器打开表格的网页链接,返回的是HTML页面内容,而非实际的XLS二进制文件。将HTML内容直接保存为.xls后缀的文件,打开时自然会出现乱码。
  2. 无效的认证方式:requests.get的auth=(user,password)是HTTP基本认证,Google Sheets目前不支持这种认证方式,即使返回状态码200,也可能只是返回了未授权的HTML页面,而非目标表格数据。

解决方案

方案1:下载公开共享的Google Sheet(无需认证)

如果你的表格设置了公开可查看/导出,使用Google Sheets专属的导出URL即可:

  1. 从浏览器链接中提取表格ID:比如链接https://docs.google.com/spreadsheets/d/abc123xyz/edit中的abc123xyz就是表格ID。
  2. 构造导出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认证,步骤如下:

  1. 安装依赖:
pip install gspread oauth2client pandas
  1. 在Google Cloud控制台创建服务账号并下载JSON密钥文件(流程:创建项目 → 启用Google Sheets API → 创建服务账号 → 下载密钥),并给该服务账号授予表格的访问权限(在表格共享中添加服务账号邮箱)。
  2. 编写代码导出:
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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:58:20