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

如何通过Google Sheet Python API v4设置各列不同宽度?

通过Google Sheets Python API批量设置列宽

完全可以一次请求完成所有列的宽度设置,不需要循环逐个调用API。核心是用Google Sheets API的batchUpdate接口,把所有列的宽度配置打包成一个请求数组发送。

具体实现步骤

  • 准备好列宽数值列表,每个值对应一列的宽度(单位:像素)
  • 构造一个包含多个updateDimensionProperties操作的请求数组,每个操作对应一列的宽度设置
  • 调用spreadsheets().batchUpdate一次性提交所有操作

Python代码示例

from googleapiclient.discovery import build
from google.oauth2 import service_account

# 初始化API客户端(替换成你的服务账号密钥路径和权限)
SERVICE_ACCOUNT_FILE = 'your-service-account-key.json'
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('sheets', 'v4', credentials=creds)

# 替换成你的表格ID和目标工作表ID(默认第一个工作表ID是0)
spreadsheet_id = 'your-spreadsheet-id'
target_sheet_id = 0

# 列宽列表:按顺序对应第1、2、3...列的宽度
column_widths = [120, 180, 90, 200, 150]

# 批量请求构造
requests = []
for col_idx, width in enumerate(column_widths):
    requests.append({
        'updateDimensionProperties': {
            'range': {
                'sheetId': target_sheet_id,
                'dimension': 'COLUMNS',
                'startIndex': col_idx,
                'endIndex': col_idx + 1
            },
            'properties': {'pixelSize': width},
            'fields': 'pixelSize'
        }
    })

# 发送一次性请求
service.spreadsheets().batchUpdate(
    spreadsheetId=spreadsheet_id,
    body={'requests': requests}
).execute()

注意事项

  • 用startIndex和endIndex指定列范围比列字母更稳定,尤其是列数较多时
  • 所有列的配置都放在同一个requests数组里,一次API调用就能完成所有设置
  • 确保你的服务账号拥有目标表格的编辑权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 08:23:17