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

使用Python调整Google Spreadsheet格式 实现首行表头居中及绿色填充

实现方案

你可以直接在spreadsheets.create的请求体中新增表头写入和格式配置,无需额外调用更新接口,具体修改如下:

1. 调整权限范围

原权限仅支持文件操作,需要补充表格编辑权限才能修改单元格格式,修改后需删除本地已有的token.json文件,重新运行代码完成授权,否则新权限不会生效:

# 原配置
# SCOPES = ["https://www.googleapis.com/auth/drive.file"]
# 新配置
SCOPES = ["https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/spreadsheets"]

2. 调整创建表格的请求体

在原来的sheets配置中新增data字段,配置表头内容、对齐方式和背景色:

# 自定义表头内容,可按实际需求修改,长度需和你设置的columnCount匹配
HEADER_VALUES = ["列1", "列2", "列3", "列4", "列5", "列6", "列7", "列8", "列9", "列10", "列11"]

spreadsheet_body = {
    'properties': {
        # spreadsheet name
        'title': 'test'
    },
    'sheets': [{
        'properties': {
            # worksheet name
            'title': 'Φύλλο1',
            'gridProperties': {
                # row\column number
                'rowCount': 100,
                'columnCount': 11
            },
        },
        # 新增以下内容配置表头属性
        'data': [{
            'startRow': 0,
            'startColumn': 0,
            'rowData': [{
                'values': [
                    {
                        'userEnteredValue': {'stringValue': header},
                        'userEnteredFormat': {
                            'horizontalAlignment': 'CENTER',
                            'backgroundColor': {
                                'red': 0.0,
                                'green': 0.8,
                                'blue': 0.0
                            }
                        }
                    } for header in HEADER_VALUES
                ]
            }]
        }]
    }]
}

补充说明

  • 背景色的RGB取值范围为0~1,你可以调整green字段的数值匹配你需要的绿色深度
  • 如果你需要创建完成后再调整表头格式,也可以调用spreadsheets().batchUpdate接口传入对应更新请求实现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:24:05