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

Ruby通过service account访问操作Google Spread Sheet的方法咨询

Ruby通过服务账号操作Google Spread Sheet写入实现方案

1. 依赖安装

首先在项目Gemfile中添加两个官方依赖库:

gem 'googleauth'
gem 'google-apis-sheets_v4'

执行bundle install完成安装。

2. 前置配置

  • 在Google Cloud Console创建对应服务账号,生成JSON格式的密钥文件,保存到项目目录下,建议命名为service_account_key.json
  • 打开目标Google Spread Sheet,点击右上角共享按钮,将密钥文件中client_email字段对应的服务账号邮箱添加为表格编辑者,完成权限授予

3. 写入操作代码示例

require 'googleauth'
require 'google/apis/sheets_v4'

# 配置API访问权限范围,读写权限适配写入需求
SCOPE = ['https://www.googleapis.com/auth/spreadsheets']
# 替换为你自己的表格ID,可从表格URL中提取
SPREADSHEET_ID = '你的表格ID'
# 替换为需要写入的表格区域,示例为第一个工作表的A1到C3范围
WRITE_RANGE = 'Sheet1!A1:C3'

# 加载服务账号凭证
credentials = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open('service_account_key.json'),
  scope: SCOPE
)

# 初始化Sheets API客户端
sheets_service = Google::Apis::SheetsV4::SheetsService.new
sheets_service.authorization = credentials

# 构造写入数据,每一个子数组对应表格的一行
write_data = Google::Apis::SheetsV4::ValueRange.new(
  values: [
    ['表头1', '表头2', '表头3'],
    ['行2列1', '行2列2', '行2列3'],
    ['行3列1', '行3列2', '行3列3']
  ]
)

# 执行写入,value_input_option设为RAW表示直接写入原始内容,不需要解析公式
response = sheets_service.update_spreadsheet_value(
  SPREADSHEET_ID,
  WRITE_RANGE,
  write_data,
  value_input_option: 'RAW'
)

puts "操作完成,共更新#{response.updated_cells}个单元格"

4. 实用提示

  • 密钥文件不要提交到代码仓库,生产环境建议通过环境变量加载密钥内容,避免凭证泄露
  • 如果需要在表格末尾追加数据,可以使用append_spreadsheet_value方法替代update_spreadsheet_value,不需要指定结束行号
  • 仅需要读取表格内容时可将权限范围替换为只读权限https://www.googleapis.com/auth/spreadsheets.readonly,降低权限风险

内容的提问来源于stack exchange,提问作者せんば

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:48:04