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

如何用Python读取谷歌表格单元格值批量生成自定义语句?

用Python批量处理谷歌表格生成指定句式内容

准备工作

  • 安装依赖库,打开终端执行:
    pip install gspread oauth2client
    
  • 配置谷歌API访问权限:
    1. 登录谷歌云平台,创建新项目,启用Google Sheets API和Google Drive API
    2. 创建服务账号,下载JSON格式的密钥文件,保存到项目目录(命名比如service_account.json)
    3. 打开目标谷歌表格,点击右上角「共享」,将服务账号的邮箱(JSON密钥里的client_email字段)添加为协作者,授予编辑权限

核心代码实现

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# 配置API访问范围
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']

# 加载认证密钥
creds = ServiceAccountCredentials.from_json_keyfile_name('service_account.json', scope)
client = gspread.authorize(creds)

# 打开目标表格(替换成你的表格名称)
spreadsheet = client.open('你的谷歌表格名称')
worksheet = spreadsheet.sheet1  # 操作第一个工作表,可根据需求修改

# 获取表格所有数据(自动识别表头,返回字典列表)
data_rows = worksheet.get_all_records()

# 定义语句模板,占位符要和表格表头完全匹配
sentence_template = "我的名字是‘{姓名}’。我的出生日期是‘{出生日期}’。我来自‘{班级}’。我喜欢‘{喜好}’。"

# 批量生成语句
generated_sentences = []
for row in data_rows:
    # 用行数据填充模板
    sentence = sentence_template.format(**row)
    generated_sentences.append(sentence)

# 选项1:将结果写入表格的新列(比如第5列,表头设为「生成语句」)
worksheet.update_cell(1, 5, '生成语句')
for idx, sent in enumerate(generated_sentences, start=2):
    worksheet.update_cell(idx, 5, sent)

# 选项2:保存结果到本地文本文件
with open('批量生成语句.txt', 'w', encoding='utf-8') as f:
    for sent in generated_sentences:
        f.write(f"{sent}\n")

print("批量处理完成!")

关键注意事项

  • 表格表头必须和模板中的占位符完全一致(包括名称、大小写、空格),否则会报错
  • 如果表格有更多列,直接在sentence_template中添加对应占位符即可,比如"我的学号是‘{学号}’。"
  • 若只需读取数据无需写入,可将服务账号的权限改为「查看者」,同时去掉代码中写入表格的部分

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:10:51