首页 > 解决方案 > 如何通过 python 正确更新 Google Sheet 图表数据范围?

问题描述

我最近一直在努力通过 python 更新谷歌图表数据范围。有一个 json 有效负载updateChartSpec应该执行此操作,它似乎与addChart完全相同,它对我来说工作得很好,只是需要额外chartId指定。

这是我的代码:

def add_sheet_chart(service, which_sheet, last_row):
    response = service.spreadsheets().get(spreadsheetId=spreadsheet_id, ranges=[], includeGridData=False).execute()
    sheet_array = response.get('sheets')

    # Get existing chart id here, if there are not charts, it's left as -1.
    sheet_id = 0
    chart_id = -1
    for sheet in sheet_array:
        if sheet.get('properties').get('title') == which_sheet:
            chart_array = sheet.get('charts')
            if chart_array:
                if len(chart_array) != 0:
                    chart_id = chart_array[0].get('chartId')
            sheet_id = sheet.get('properties').get('sheetId')
            break

    title = "..."
    bottom_title = "..."
    left_title = "..."

    requests = []

    if chart_id == -1:  # <- insert new chart here (works fine)
        requests.append({
                "addChart": {
                    "chart": {
                        "spec": get_chart_spec(sheet_id, last_row, title, bottom_title, left_title),
                        "position": {
                            "overlayPosition": {
                                "anchorCell": {
                                    "sheetId": sheet_id,
                                    "rowIndex": 4,
                                    "columnIndex": 8
                                },
                                "widthPixels": 900,
                                "heightPixels": 600
                            }
                        }
                    }
                }
        })
    else:  # <- update existing chart here (doesn't work)
        requests.append({
            "updateChartSpec": {
                "chartId": chart_id,
                "spec": get_chart_spec(sheet_id, last_row, title, bottom_title, left_title)
            }
        })
        return

    body = {
        'requests': requests
    }
    service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body=body).execute()


def get_chart_spec(sheet_id, last_row, title, bottom_title, left_title):
    spec = {
        "title": title,
        "basicChart": {
            "chartType": "COMBO",
            "legendPosition": "TOP_LEGEND",
            "axis": [
                {
                    "position": "BOTTOM_AXIS",
                    "title": bottom_title
                },
                {
                    "position": "LEFT_AXIS",
                    "title": left_title
                }
            ],
            "domains": [
                {
                    "domain": {
                        "sourceRange": {
                            "sources": [
                                {
                                    "sheetId": sheet_id,
                                    "startRowIndex": 0,
                                    "endRowIndex": last_row,
                                    "startColumnIndex": 1,
                                    "endColumnIndex": 2
                                }
                            ]
                        }
                    }
                }
            ],
            "series": [
                {
                    "series": {
                        "sourceRange": {
                            "sources": [
                                {
                                    "sheetId": sheet_id,
                                    "startRowIndex": 0,
                                    "endRowIndex": last_row,
                                    "startColumnIndex": 2,
                                    "endColumnIndex": 3,
                                }
                            ]
                        }
                    },
                    "targetAxis": "LEFT_AXIS",
                    "type": "LINE",
                    "lineStyle": {
                        "width": 4
                    },
                    "color": colors['blue']
                },
                {
                    "series": {
                        "sourceRange": {
                            "sources": [
                                {
                                    "sheetId": sheet_id,
                                    "startRowIndex": 0,
                                    "endRowIndex": last_row,
                                    "startColumnIndex": 3,
                                    "endColumnIndex": 4,
                                }
                            ]
                        }
                    },
                    "targetAxis": "LEFT_AXIS",
                    "type": "COLUMN",
                    "color": colors['red']
                },
                {
                    "series": {
                        "sourceRange": {
                            "sources": [
                                {
                                    "sheetId": sheet_id,
                                    "startRowIndex": 0,
                                    "endRowIndex": last_row,
                                    "startColumnIndex": 4,
                                    "endColumnIndex": 5,
                                }
                            ]
                        }
                    },
                    "targetAxis": "LEFT_AXIS",
                    "type": "COLUMN",
                    "color": colors['green']
                },
                {
                    "series": {
                        "sourceRange": {
                            "sources": [
                                {
                                    "sheetId": sheet_id,
                                    "startRowIndex": 0,
                                    "endRowIndex": last_row,
                                    "startColumnIndex": 5,
                                    "endColumnIndex": 6,
                                }
                            ]
                        }
                    },
                    "targetAxis": "LEFT_AXIS",
                    "type": "COLUMN",
                    "color": colors['orange']
                }
            ],
            "headerCount": 1,
            "stackedType": "STACKED"
        }
    }
    return spec

当我更新图表规范时唯一改变的是last_row变量,我只是调试了它,它是一个正确的值。这是一张图片(有些东西是白化的,但它们与主题无关),底部应该包括所有周数,但它只包括最初生成图表的那些周:不完整的图表

我在任何地方都找不到类似的东西,但是看到在任何地方都没有关于自动谷歌表格图表的讨论,我并不感到惊讶。如果有帮助,图表也会发布。

标签: pythonchartsgoogle-sheets-api

解决方案


return 语句弄乱了您的代码!

找到图表时 ( chart_id != -1),代码进入一个else块。在此块的末尾,在附加图表更新请求后,您添加了一个return结束函数执行的语句,因此代码永远不会到达batchUpdate下面的调用。因此,图表未更新:

    else:
        requests.append({
            "updateChartSpec": {
                "chartId": chart_id,
                "spec": get_chart_spec(sheet_id, last_row, title, bottom_title, left_title)
            }
        })
        return  # REMOVE THIS!

没有理由return在那里。删除它以使您的图表成功更新。

参考:


推荐阅读