在Python项目中操作Google Sheets是很多自动化数据处理场景的常见需求,gspread库封装了Google Sheets API的复杂调用逻辑,让开发者可以用简单的代码完成表格的各类操作。

环境准备与依赖安装
首先需要安装gspread库以及Google认证相关的依赖包,执行以下命令完成安装:
pip install gspread gspread_dataframe google_auth_oauthlib
Google Cloud平台配置
使用gspread操作Google Sheets需要先获取服务账号的认证凭证,具体步骤如下:
- 登录Google Cloud控制台,创建新的项目
- 开启Google Sheets API和Google Drive API服务
- 创建服务账号,生成JSON格式的密钥文件,保存到本地目录
- 将服务账号的邮箱地址添加为目标Google Sheets表格的编辑权限
基础认证与表格连接
完成配置后,就可以在Python代码中通过服务账号密钥完成认证,连接到目标表格:
import gspread
from google.oauth2.service_account import Credentials
# 定义需要使用的API作用域
scope = [
"https://spreadsheets.google.com/feeds",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive"
]
# 加载服务账号密钥文件
creds = Credentials.from_service_account_file("your_key_file.json", scopes=scope)
client = gspread.authorize(creds)
# 打开指定表格,支持表格名称或者表格ID
sheet = client.open("测试表格").sheet1
常见数据操作示例
读取表格数据
gspread提供了多种读取数据的方法,可以根据需求选择:
# 获取所有数据,返回二维列表 all_data = sheet.get_all_values() print(all_data) # 获取指定单元格的值 cell_value = sheet.cell(1, 1).value print(cell_value) # 获取某一行的数据 row_data = sheet.row_values(1) print(row_data) # 获取某一列的数据 col_data = sheet.col_values(1) print(col_data)
写入表格数据
写入数据支持单个单元格更新、批量更新、按行按列插入等多种方式:
# 更新单个单元格
sheet.update_cell(1, 1, "更新后的内容")
# 批量更新多个单元格,传入二维列表
data = [["姓名", "年龄"], ["张三", 20], ["李四", 22]]
sheet.update("A1:B3", data)
# 在表格末尾追加一行数据
sheet.append_row(["王五", 25])
表格与单元格管理
除了数据读写,还可以对表格结构和单元格格式进行操作:
# 创建新的工作表
new_sheet = sheet.spreadsheet.add_worksheet(title="新工作表", rows=100, cols=20)
# 删除指定工作表
sheet.spreadsheet.del_worksheet(new_sheet)
# 设置单元格背景色,需要传入RGB颜色值
sheet.format("A1:B1", {
"backgroundColor": {
"red": 0.9,
"green": 0.9,
"blue": 0.9
}
})
常见问题排查
- 如果出现权限报错,检查服务账号邮箱是否已经添加到表格的共享列表中,且权限为编辑者
- 密钥文件路径错误会导致认证失败,需要确认代码中填写的JSON文件路径和实际保存路径一致
- API未开启会返回调用失败的错误,需要在Google Cloud控制台确认Sheets API和Drive API已经启用
PythongspreadGoogle_SheetsAPI集成修改时间:2026-07-14 00:48:26