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

如何用Python更新同一Spreadsheet内不同gid的多个Sheet?

如何用Python更新Google Sheets中的多个工作表

要操作同一个Spreadsheet内的不同工作表,核心是在API请求的range参数中明确指定目标工作表,无需依赖gid(当然也支持用gid),具体实现如下:

方法1:通过工作表名称指定(推荐)

Google Sheets API支持用"工作表名称!单元格范围"的格式定位目标工作表,这比gid更直观易维护。修改你的APPEND_GSHEET函数,让它接受工作表名称作为参数,动态构造范围字符串即可:

import os
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

SAMPLE_SPREADSHEET_ID = '1nt7cmF5nmWcoBy9r8Yxoz670C97FH1mzKuLarararar'

def gservice():
    SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    return build('sheets', 'v4', credentials=creds)

sheet = gservice().spreadsheets()

def APPEND_GSHEET(sheet_name, some_data):
    # 构造包含工作表名称的范围字符串
    range_str = f"{sheet_name}!A1:B11"
    resource = {
        "majorDimension": "ROWS",
        "values": some_data
    }
    sheet.values().append(
        spreadsheetId=SAMPLE_SPREADSHEET_ID,
        range=range_str,
        body=resource,
        valueInputOption="USER_ENTERED"
    ).execute()

# 调用示例:向不同工作表追加数据
APPEND_GSHEET("Sheet1", [[1,2,3]])  # 主表
APPEND_GSHEET("销售数据", [[4,5,6]])  # 名为"销售数据"的工作表
APPEND_GSHEET("'带空格的工作表'", [[7,8,9]])  # 工作表名称含空格时,用单引号包裹

方法2:通过gid指定工作表

如果必须使用gid,格式为"gid=工作表gid值!单元格范围",替换range_str即可:

def APPEND_GSHEET_BY_GID(gid, some_data):
    range_str = f"gid={gid}!A1:B11"
    resource = {
        "majorDimension": "ROWS",
        "values": some_data
    }
    sheet.values().append(
        spreadsheetId=SAMPLE_SPREADSHEET_ID,
        range=range_str,
        body=resource,
        valueInputOption="USER_ENTERED"
    ).execute()

# 调用示例:向gid为123456的工作表追加数据
APPEND_GSHEET_BY_GID(123456, [[10,11,12]])

说明:

  • 工作表名称如果包含空格、特殊字符,需要用单引号包裹,比如"'Q3 报表'!A1:C10"
  • 无论是用名称还是gid,API的调用逻辑和追加数据的逻辑完全一致,只是range参数的格式不同

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:42:49