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

Python3如何在Google Sheets中根据单元格内容获取其坐标

基于Python3查询Google Sheets指定列内容的单元格坐标

前置依赖

  • 首先安装操作Google Sheets的常用库:
pip install gspread oauth2client
  • 提前在Google Cloud控制台开通Google Sheets API,下载服务账号的JSON密钥文件,将服务账号邮箱添加到目标Google Sheets的共享用户列表中。

核心实现代码

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# 认证配置
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('你的密钥文件路径.json', scope)
client = gspread.authorize(creds)

# 打开目标表格和工作表
sheet = client.open('你的表格名称').sheet1 # 可替换为你要操作的工作表对象

# 你需要的查询逻辑
target_content = "hello"
search_col = 4 # 第4列
col_values = sheet.col_values(search_col)

if target_content in col_values:
    # 列表索引从0开始,行号从1开始,所以索引+1为实际行号
    row_num = col_values.index(target_content) + 1
    # 转换为A1格式的坐标(比如第4列第3行就是D3)
    a1_coordinate = gspread.utils.rowcol_to_a1(row_num, search_col)
    print(f"匹配内容的单元格坐标(A1格式):{a1_coordinate}")
    print(f"匹配内容的单元格坐标(行号/列号格式):第{row_num}行,第{search_col}列")

补充说明

  • 如果列中存在多个匹配的内容,上述index()方法只会返回第一个匹配项的坐标,需要获取所有匹配项可改为遍历列表判断所有匹配索引。
  • 若需要全表搜索而非指定列搜索,可遍历工作表所有单元格值后匹配坐标。

内容的提问来源于stack exchange,提问作者54degree5

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:36:03