在Databricks中使用Pandas读取需认证的受限Google Sheet方法咨询
解决方案:Databricks环境下带身份认证读取受限Google Sheet
报错原因说明
Error tokenizing data.C error: Expected 1 fields in line 6, saw 2报错的根因是无权限访问受限Google Sheet时,Google返回的响应不是请求的CSV格式数据,而是Google账号登录页的HTML内容,pandas将HTML内容按CSV规则解析时出现字段匹配错误。
前置操作
- 在Google Cloud Console创建服务账号,导出服务账号的JSON格式密钥文件
- 打开目标Google Sheet,将服务账号的邮箱添加为表格的共享成员,权限至少设置为查看者
步骤1:安装依赖库
在Databricks Notebook中执行如下命令安装所需依赖:
%pip install gspread oauth2client pandas dbutils.library.restartPython()
步骤2:配置身份认证
通过服务账号密钥完成Google API的身份校验,敏感密钥信息推荐通过Databricks Secrets功能存储,避免明文写在代码中:
import gspread from oauth2client.service_account import ServiceAccountCredentials import pandas as pd # 配置Google Sheet相关API的访问权限范围 scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] # 替换为你自己的服务账号密钥内容 service_account_key = { "type": "service_account", "project_id": "替换为你的项目ID", "private_key_id": "替换为你的私钥ID", "private_key": "替换为你的私钥内容", "client_email": "替换为你的服务账号邮箱", "client_id": "替换为你的客户端ID", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "替换为你的服务账号证书URL" } creds = ServiceAccountCredentials.from_json_keyfile_dict(service_account_key, scope) client = gspread.authorize(creds)
步骤3:读取Google Sheet并转换为DataFrame
# 替换为目标Google Sheet的ID sheet = client.open_by_key("<替换为你的Sheet ID>") # 若需读取指定gid的工作表,使用.get_worksheet_by_id()方法,示例读取gid=0的工作表 worksheet = sheet.get_worksheet_by_id(0) # 获取工作表全部数据 data = worksheet.get_all_records() # 转换为Pandas DataFrame df = pd.DataFrame(data) # 按需转换为Spark DataFrame spark_df = spark.createDataFrame(df)
注意事项
- 服务账号密钥属于敏感信息,禁止明文硬编码在Notebook中,推荐通过
dbutils.secrets.get(scope="你的密钥存储范围", key="你的密钥名称")调用 - 若只需读取第一个工作表,可直接使用
sheet.sheet1获取工作表实例
内容的提问来源于stack exchange,提问作者Bitanshu Das
相关产品推荐
相关产品推荐

