google-sheets
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGoogle Sheets API
Google Sheets API
Use the Google Sheets API via direct calls to read, write, and manage spreadsheet data.
curlOfficial docs:https://developers.google.com/sheets/api
通过直接调用来使用Google Sheets API,以读取、写入和管理电子表格数据。
curl官方文档:https://developers.google.com/sheets/api
When to Use
使用场景
Use this skill when you need to:
- Read data from Google Sheets
- Write or update cell values
- Append rows to existing sheets
- Create new spreadsheets
- Get spreadsheet metadata (sheet names, properties)
- Batch update multiple ranges at once
当你需要以下操作时使用该技能:
- 从Google Sheets中读取数据
- 写入或更新单元格值
- 向现有表格追加行
- 创建新电子表格
- 获取电子表格元数据(工作表名称、属性)
- 一次性批量更新多个范围
Prerequisites
前置条件
Option 1: OAuth Playground (Recommended for testing)
选项1:OAuth测试平台(推荐用于测试)
-
Create Google Cloud Project
- Go to https://console.cloud.google.com
- Create a new project or select existing
- Enable Google Sheets API: https://console.cloud.google.com/apis/library/sheets.googleapis.com
-
Configure OAuth Consent Screen
- Go to https://console.cloud.google.com/apis/credentials/consent
- Select External → Create
- Fill required fields (app name, support email, developer email)
- Click Save and Continue through Scopes (skip adding scopes)
- In Audience section, click Add Users and add your Gmail address as test user
- Save and continue to finish
-
Create OAuth Client ID
- Go to https://console.cloud.google.com/apis/credentials
- Click Create Credentials → OAuth client ID
- Choose Web application (not Desktop)
- Add Authorized redirect URI:
https://developers.google.com/oauthplayground - Click Create and note the Client ID and Client Secret
-
Get Refresh Token
- Go to https://developers.google.com/oauthplayground/
- Click Settings (gear icon ⚙️) → Check Use your own OAuth credentials
- Enter your Client ID and Client Secret
- In the left panel, enter scope:
https://www.googleapis.com/auth/spreadsheets - Click Authorize APIs → Sign in with your test user account
- Click Exchange authorization code for tokens
- Copy the Refresh token
-
Set Environment Variables
bash
export GOOGLE_SHEETS_CLIENT_ID="your-client-id"
export GOOGLE_SHEETS_CLIENT_SECRET="your-client-secret"
export GOOGLE_SHEETS_REFRESH_TOKEN="your-refresh-token"- Get Access Token (before making API calls)
bash
bash -c 'curl -s -X POST "https://oauth2.googleapis.com/token" -d "client_id=$GOOGLE_SHEETS_CLIENT_ID" -d "client_secret=$GOOGLE_SHEETS_CLIENT_SECRET" -d "refresh_token=$GOOGLE_SHEETS_REFRESH_TOKEN" -d "grant_type=refresh_token"' | jq -r '.access_token' > /tmp/sheets_token.txt-
创建Google Cloud项目
- 访问https://console.cloud.google.com
- 创建新项目或选择现有项目
- 启用Google Sheets API:https://console.cloud.google.com/apis/library/sheets.googleapis.com
-
配置OAuth同意屏幕
- 访问https://console.cloud.google.com/apis/credentials/consent
- 选择外部 → 创建
- 填写必填字段(应用名称、支持邮箱、开发者邮箱)
- 点击保存并继续跳过范围设置(无需添加范围)
- 在受众部分,点击添加用户并将你的Gmail地址添加为测试用户
- 保存并继续完成配置
-
创建OAuth客户端ID
- 访问https://console.cloud.google.com/apis/credentials
- 点击创建凭据 → OAuth客户端ID
- 选择Web应用(不要选桌面应用)
- 添加授权重定向URI:
https://developers.google.com/oauthplayground - 点击创建并记录客户端ID和客户端密钥
-
获取刷新令牌
- 访问https://developers.google.com/oauthplayground/
- 点击设置(齿轮图标⚙️)→ 勾选使用你自己的OAuth凭据
- 输入你的客户端ID和客户端密钥
- 在左侧面板中,输入范围:
https://www.googleapis.com/auth/spreadsheets - 点击授权API → 使用测试用户账户登录
- 点击交换授权码以获取令牌
- 复制刷新令牌
-
设置环境变量
bash
export GOOGLE_SHEETS_CLIENT_ID="your-client-id"
export GOOGLE_SHEETS_CLIENT_SECRET="your-client-secret"
export GOOGLE_SHEETS_REFRESH_TOKEN="your-refresh-token"- 获取访问令牌(在发起API调用前执行)
bash
bash -c 'curl -s -X POST "https://oauth2.googleapis.com/token" -d "client_id=$GOOGLE_SHEETS_CLIENT_ID" -d "client_secret=$GOOGLE_SHEETS_CLIENT_SECRET" -d "refresh_token=$GOOGLE_SHEETS_REFRESH_TOKEN" -d "grant_type=refresh_token"' | jq -r '.access_token' > /tmp/sheets_token.txtVerify token was obtained
验证令牌是否获取成功
head -c 20 /tmp/sheets_token.txt && echo "..."
Then use `$(cat /tmp/sheets_token.txt)` inside `bash -c` wrappers for API calls.head -c 20 /tmp/sheets_token.txt && echo "..."
然后在`bash -c`包装器中使用`$(cat /tmp/sheets_token.txt)`来进行API调用。Option 2: Service Account
选项2:服务账号
- Go to Google Cloud Console
- Create a project and enable the Google Sheets API
- Create a Service Account and download JSON key
- Share your spreadsheet with the service account email
- Generate access token:
bash
gcloud auth activate-service-account --key-file=service-account.json
export GOOGLE_ACCESS_TOKEN=$(gcloud auth print-access-token)- 访问Google Cloud控制台
- 创建项目并启用Google Sheets API
- 创建服务账号并下载JSON密钥
- 与服务账号邮箱共享你的电子表格
- 生成访问令牌:
bash
gcloud auth activate-service-account --key-file=service-account.json
export GOOGLE_ACCESS_TOKEN=$(gcloud auth print-access-token)Option 3: API Key (Read-only, Public Sheets)
选项3:API密钥(仅可读,适用于公开表格)
For publicly accessible sheets, you can use an API key:
bash
export GOOGLE_API_KEY="your-api-key"Important: When usingin a command that pipes to another command, wrap the command containing$VARin$VAR. Due to a Claude Code bug, environment variables are silently cleared when pipes are used directly.bash -c '...'bashbash -c 'curl -s "https://api.example.com" -H "Authorization: Bearer $API_KEY"'
对于公开可访问的表格,你可以使用API密钥:
bash
export GOOGLE_API_KEY="your-api-key"重要提示: 当在包含管道的命令中使用时,请将包含$VAR的命令用$VAR包裹。由于Claude Code的bug,直接使用管道时环境变量会被静默清除。bash -c '...'bashbash -c 'curl -s "https://api.example.com" -H "Authorization: Bearer $API_KEY"'
How to Use
使用方法
All examples below use . Before running, either:
${GOOGLE_ACCESS_TOKEN}- Set manually: , or
GOOGLE_ACCESS_TOKEN="ya29.xxx..." - Replace with
${GOOGLE_ACCESS_TOKEN}in each command$(cat /tmp/sheets_token.txt)
Important: In range notation like, theSheet1!A1:D10must be URL encoded as!in the URL path (e.g.,%21). All examples below use this encoding.Sheet1%21A1:D10
Base URL:
https://sheets.googleapis.com/v4/spreadsheetsFinding your Spreadsheet ID:
The spreadsheet ID is in the URL:
https://docs.google.com/spreadsheets/d/{SPREADSHEET_ID}/edit以下所有示例均使用。运行前,请选择以下方式之一:
${GOOGLE_ACCESS_TOKEN}- 手动设置:,或者
GOOGLE_ACCESS_TOKEN="ya29.xxx..." - 在每个命令中用替换
$(cat /tmp/sheets_token.txt)${GOOGLE_ACCESS_TOKEN}
重要提示: 在类似的范围表示法中,Sheet1!A1:D10必须在URL路径中进行URL编码为!(例如%21)。以下所有示例均使用该编码方式。Sheet1%21A1:D10
基础URL:
https://sheets.googleapis.com/v4/spreadsheets查找你的电子表格ID:
电子表格ID位于URL中:
https://docs.google.com/spreadsheets/d/{SPREADSHEET_ID}/edit1. Get Spreadsheet Metadata
1. 获取电子表格元数据
Get information about a spreadsheet (sheets, properties). Replace with your actual spreadsheet ID:
<your-spreadsheet-id>bash
bash -c 'curl -s "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}"' | jq '{title: .properties.title, sheets: [.sheets[].properties | {sheetId, title}]}''获取电子表格的相关信息(工作表、属性)。将替换为你的实际电子表格ID:
<your-spreadsheet-id>bash
bash -c 'curl -s "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}"' | jq '{title: .properties.title, sheets: [.sheets[].properties | {sheetId, title}]}''2. Read Cell Values
2. 读取单元格值
Read a range of cells. Replace with your actual spreadsheet ID:
<your-spreadsheet-id>bash
bash -c 'curl -s "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1%21A1:D10" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}"' | jq '.values'读取指定范围的单元格。将替换为你的实际电子表格ID:
<your-spreadsheet-id>bash
bash -c 'curl -s "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1%21A1:D10" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}"' | jq '.values'3. Read Entire Sheet
3. 读取整个工作表
Read all data from a sheet. Replace with your actual spreadsheet ID:
<your-spreadsheet-id>bash
bash -c 'curl -s "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}"' | jq '.values'读取某工作表的所有数据。将替换为你的实际电子表格ID:
<your-spreadsheet-id>bash
bash -c 'curl -s "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}"' | jq '.values'4. Read with API Key (Public Sheets)
4. 使用API密钥读取(公开表格)
For publicly accessible sheets. Replace with your actual spreadsheet ID:
<your-spreadsheet-id>bash
bash -c 'curl -s "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1%21A1:D10?key=${GOOGLE_API_KEY}"' | jq '.values'适用于公开可访问的表格。将替换为你的实际电子表格ID:
<your-spreadsheet-id>bash
bash -c 'curl -s "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1%21A1:D10?key=${GOOGLE_API_KEY}"' | jq '.values'5. Write Cell Values
5. 写入单元格值
Update a range of cells. Replace with your actual spreadsheet ID.
<your-spreadsheet-id>Write to :
/tmp/gsheets_request.jsonjson
{
"values": [
["Name", "Email", "Status"]
]
}Then run:
bash
bash -c 'curl -s -X PUT "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1%21A1:C1?valueInputOption=USER_ENTERED" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json' | jq '.updatedCells'valueInputOption:
- : Values are stored as-is
RAW - : Values are parsed as if typed by user (formulas evaluated)
USER_ENTERED
更新指定范围的单元格。将替换为你的实际电子表格ID。
<your-spreadsheet-id>将以下内容写入:
/tmp/gsheets_request.jsonjson
{
"values": [
["Name", "Email", "Status"]
]
}然后运行:
bash
bash -c 'curl -s -X PUT "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1%21A1:C1?valueInputOption=USER_ENTERED" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json' | jq '.updatedCells'valueInputOption说明:
- :值按原样存储
RAW - :值会像用户输入一样被解析(公式会被计算)
USER_ENTERED
6. Append Rows
6. 追加行
Add new rows to the end of a sheet. Replace with your actual spreadsheet ID.
<your-spreadsheet-id>Write to :
/tmp/gsheets_request.jsonjson
{
"values": [
["John Doe", "john@example.com", "Active"]
]
}Then run:
bash
bash -c 'curl -s -X POST "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1%21A:C:append?valueInputOption=USER_ENTERED&insertDataOption=INSERT_ROWS" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json' | jq '.updates | {updatedRange, updatedRows}'在工作表末尾添加新行。将替换为你的实际电子表格ID。
<your-spreadsheet-id>将以下内容写入:
/tmp/gsheets_request.jsonjson
{
"values": [
["John Doe", "john@example.com", "Active"]
]
}然后运行:
bash
bash -c 'curl -s -X POST "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1%21A:C:append?valueInputOption=USER_ENTERED&insertDataOption=INSERT_ROWS" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json' | jq '.updates | {updatedRange, updatedRows}'7. Batch Read Multiple Ranges
7. 批量读取多个范围
Read multiple ranges in one request. Replace with your actual spreadsheet ID:
<your-spreadsheet-id>bash
bash -c 'curl -s "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values:batchGet?ranges=Sheet1%21A1:B5&ranges=Sheet1%21D1:E5" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}"' | jq '.valueRanges'在一次请求中读取多个范围的数据。将替换为你的实际电子表格ID:
<your-spreadsheet-id>bash
bash -c 'curl -s "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values:batchGet?ranges=Sheet1%21A1:B5&ranges=Sheet1%21D1:E5" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}"' | jq '.valueRanges'8. Batch Update Multiple Ranges
8. 批量更新多个范围
Update multiple ranges in one request. Replace with your actual spreadsheet ID.
<your-spreadsheet-id>Write to :
/tmp/gsheets_request.jsonjson
{
"valueInputOption": "USER_ENTERED",
"data": [
{
"range": "Sheet1!A1",
"values": [["Header 1"]]
},
{
"range": "Sheet1!B1",
"values": [["Header 2"]]
}
]
}Then run:
bash
bash -c 'curl -s -X POST "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values:batchUpdate" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json' | jq '.totalUpdatedCells'在一次请求中更新多个范围的数据。将替换为你的实际电子表格ID。
<your-spreadsheet-id>将以下内容写入:
/tmp/gsheets_request.jsonjson
{
"valueInputOption": "USER_ENTERED",
"data": [
{
"range": "Sheet1!A1",
"values": [["Header 1"]]
},
{
"range": "Sheet1!B1",
"values": [["Header 2"]]
}
]
}然后运行:
bash
bash -c 'curl -s -X POST "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values:batchUpdate" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json' | jq '.totalUpdatedCells'9. Clear Cell Values
9. 清除单元格值
Clear a range of cells. Replace with your actual spreadsheet ID.
<your-spreadsheet-id>Write to :
/tmp/gsheets_request.jsonjson
{}Then run:
bash
bash -c 'curl -s -X POST "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1%21A2:C100:clear" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json' | jq '.clearedRange'清除指定范围的单元格内容。将替换为你的实际电子表格ID。
<your-spreadsheet-id>将以下内容写入:
/tmp/gsheets_request.jsonjson
{}然后运行:
bash
bash -c 'curl -s -X POST "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1%21A2:C100:clear" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json' | jq '.clearedRange'10. Create New Spreadsheet
10. 创建新电子表格
Create a new spreadsheet:
Write to :
/tmp/gsheets_request.jsonjson
{
"properties": {
"title": "My New Spreadsheet"
},
"sheets": [
{
"properties": {
"title": "Data"
}
}
]
}Then run:
bash
bash -c 'curl -s -X POST "https://sheets.googleapis.com/v4/spreadsheets" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json' | jq '.spreadsheetId, .spreadsheetUrl'创建一个新的电子表格:
将以下内容写入:
/tmp/gsheets_request.jsonjson
{
"properties": {
"title": "My New Spreadsheet"
},
"sheets": [
{
"properties": {
"title": "Data"
}
}
]
}然后运行:
bash
bash -c 'curl -s -X POST "https://sheets.googleapis.com/v4/spreadsheets" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json' | jq '.spreadsheetId, .spreadsheetUrl'11. Add New Sheet
11. 添加新工作表
Add a new sheet to an existing spreadsheet. Replace with your actual spreadsheet ID.
<your-spreadsheet-id>Write to :
/tmp/gsheets_request.jsonjson
{
"requests": [
{
"addSheet": {
"properties": {
"title": "New Sheet"
}
}
}
]
}Then run:
bash
bash -c 'curl -s -X POST "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>:batchUpdate" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json' | jq '.replies[0].addSheet.properties'向现有电子表格中添加新工作表。将替换为你的实际电子表格ID。
<your-spreadsheet-id>将以下内容写入:
/tmp/gsheets_request.jsonjson
{
"requests": [
{
"addSheet": {
"properties": {
"title": "New Sheet"
}
}
}
]
}然后运行:
bash
bash -c 'curl -s -X POST "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>:batchUpdate" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json' | jq '.replies[0].addSheet.properties'12. Delete Sheet
12. 删除工作表
Delete a sheet from a spreadsheet (use sheetId from metadata). Replace with your actual spreadsheet ID.
<your-spreadsheet-id>Write to :
/tmp/gsheets_request.jsonjson
{
"requests": [
{
"deleteSheet": {
"sheetId": 123456789
}
}
]
}Then run:
bash
bash -c 'curl -s -X POST "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>:batchUpdate" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json'从电子表格中删除工作表(使用元数据中的sheetId)。将替换为你的实际电子表格ID。
<your-spreadsheet-id>将以下内容写入:
/tmp/gsheets_request.jsonjson
{
"requests": [
{
"deleteSheet": {
"sheetId": 123456789
}
}
]
}然后运行:
bash
bash -c 'curl -s -X POST "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>:batchUpdate" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}" -H "Content-Type: application/json" -d @/tmp/gsheets_request.json'13. Search for Values
13. 搜索值
Find cells containing specific text (read all then filter). Replace with your actual spreadsheet ID:
<your-spreadsheet-id>bash
bash -c 'curl -s "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}"' | jq '[.values[] | select(.[0] | ascii_downcase | contains("search_term"))]'查找包含特定文本的单元格(读取所有数据后过滤)。将替换为你的实际电子表格ID:
<your-spreadsheet-id>bash
bash -c 'curl -s "https://sheets.googleapis.com/v4/spreadsheets/<your-spreadsheet-id>/values/Sheet1" -H "Authorization: Bearer ${GOOGLE_ACCESS_TOKEN}"' | jq '[.values[] | select(.[0] | ascii_downcase | contains("search_term"))]'A1 Notation Reference
A1表示法参考
| Notation | Description |
|---|---|
| Single cell A1 in Sheet1 |
| Range from A1 to B2 |
| Entire column A |
| Entire row 1 |
| From A1 to end of column C |
| Sheet names with spaces need quotes |
| 表示法 | 说明 |
|---|---|
| Sheet1中的单个单元格A1 |
| 从A1到B2的范围 |
| 整个A列 |
| 整个第1行 |
| 从A1到C列末尾的范围 |
| 名称包含空格的工作表需要加引号 |
Guidelines
注意事项
- Token expiration: Access tokens expire after ~1 hour; refresh with
gcloud auth print-access-token - Share with service account: When using service accounts, share the spreadsheet with the service account email
- Rate limits: Default quota is 300 requests per minute per project
- Use batch operations: Combine multiple reads/writes to reduce API calls
- valueInputOption: Use for formulas,
USER_ENTEREDfor literal stringsRAW - URL encode ranges: Ranges with special characters need URL encoding (e.g., spaces → )
%20
- 令牌过期:访问令牌约1小时后过期;可使用刷新
gcloud auth print-access-token - 与服务账号共享:使用服务账号时,请将电子表格共享给服务账号邮箱
- 速率限制:默认配额为每个项目每分钟300次请求
- 使用批量操作:合并多次读/写操作以减少API调用次数
- valueInputOption:使用处理公式,使用
USER_ENTERED处理字面字符串RAW - URL编码范围:包含特殊字符的范围需要进行URL编码(例如空格→)
%20