使用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
相关产品推荐
相关产品推荐

