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

使用Python gspread遍历谷歌表格行的问题及行数统计咨询

gspread 获取行数据与统计行数方案

获取行数据并遍历

直接使用get_all_values()方法,它会返回按行排列的二维列表,每个子列表对应表格中的一行,直接遍历即可:

import gspread
from google.oauth2.service_account import Credentials

# 完成认证(替换为你的密钥文件路径)
scope = ["https://www.googleapis.com/auth/spreadsheets"]
creds = Credentials.from_service_account_file("service_account_key.json", scopes=scope)
client = gspread.authorize(creds)

# 打开目标表格和工作表
spreadsheet = client.open("你的表格名称")
worksheet = spreadsheet.sheet1

# 获取所有行数据
all_row_data = worksheet.get_all_values()

# 遍历每一行
for row in all_row_data:
    print(row)  # row为当前行的所有单元格值组成的列表

如果只需遍历指定行,可使用row_values()方法单独获取某一行数据,再结合循环实现:

# 遍历第1到第10行
for row_num in range(1, 11):
    row_data = worksheet.row_values(row_num)
    print(row_data)

统计第一列的行数

使用col_values(1)获取第一列的所有值,再通过len()统计行数:

# 获取第一列所有单元格值
first_column = worksheet.col_values(1)

# 统计第一列总行数(包含空单元格)
total_count = len(first_column)

# 统计第一列非空行数(过滤空字符串)
non_empty_count = len([cell for cell in first_column if cell.strip()])

print(f"第一列总行数:{total_count}")
print(f"第一列非空行数:{non_empty_count}")

内容的提问来源于stack exchange,提问作者Steven Hardy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:25:21