Google Sheets API添加HistogramChart触发sourceRange报错排查
Google Sheets API 创建直方图sourceRange报错解决
报错信息
调用Sheets API batchUpdate接口创建Histogram Chart时触发参数校验错误,错误详情:
Invalid requests[0].addChart: ChartSourceRange ranges require all rows or all columns to have length of 1
原始数据表
| Name | 15/06 | 16/06 | 17/06 | 20/06 | 21/06 | 22/06 | 23/06 |
|---|---|---|---|---|---|---|---|
| A | 4000 | 3812 | 3941 | 3734 | 3868 | 3815 | 3860 |
| B | 1 | 1 | 0 | 0 | 0 | 0 | 0 |
| C | 99 | 96 | 98 | 120 | 109 | 95 | 98 |
| D | 425 | 569 | 604 | 476 | 433 | 514 | 897 |
| E | 76 | 87 | 139 | 82 | 167 | 162 | 178 |
| F | 26 | 14 | 22 | 18 | 14 | 84 | 0 |
目标图表效果

原始问题代码
request_chart = { 'requests' : [ { 'addChart' : { 'chart' : { 'spec' : { 'title' : 'En nombre', 'histogramChart' : { "showItemDividers": False, 'legendPosition' : 'RIGHT_LEGEND', 'series' : [ { 'data': { 'sourceRange':{ 'sources': [ { "sheetId": 0, "startRowIndex": 1, "endRowIndex": 7, "startColumnIndex": 0, "endColumnIndex": 8, } ] } } } ] } }, 'position' : { 'newSheet' : True } } } } ] } service_sheets.spreadsheets().batchUpdate(spreadsheetId = id_fichier_historique, body = request_chart).execute()
报错原因
- 直方图接口对每个系列的
sourceRange有强制要求:单个source范围必须是一维结构,即要么是单行(行范围长度为1)、要么是单列(列范围长度为1),不支持传入多行多列的二维整块区域 - 原代码传入的范围覆盖了6行7列的数值+1列文本,属于二维区域,同时还包含了第一列的文本类Name字段,不符合数值数据源要求,直接触发校验报错
修改方法
将每一行的数值数据拆分为单独的系列传入,每个系列对应的sourceRange仅覆盖单行的数值列(跳过第一列文本列),保证每个source的行范围长度为1,符合接口规则。修改后的请求代码如下:
request_chart = { 'requests' : [ { 'addChart' : { 'chart' : { 'spec' : { 'title' : 'En nombre', 'histogramChart' : { "showItemDividers": False, 'legendPosition' : 'RIGHT_LEGEND', 'series' : [ # A行数据 { 'data': { 'sourceRange':{ 'sources': [ { "sheetId": 0, "startRowIndex": 1, "endRowIndex": 2, "startColumnIndex": 1, "endColumnIndex": 8, } ] } } }, # B行数据 { 'data': { 'sourceRange':{ 'sources': [ { "sheetId": 0, "startRowIndex": 2, "endRowIndex": 3, "startColumnIndex": 1, "endColumnIndex": 8, } ] } } }, # C行数据 { 'data': { 'sourceRange':{ 'sources': [ { "sheetId": 0, "startRowIndex": 3, "endRowIndex": 4, "startColumnIndex": 1, "endColumnIndex": 8, } ] } } }, # D行数据 { 'data': { 'sourceRange':{ 'sources': [ { "sheetId": 0, "startRowIndex": 4, "endRowIndex": 5, "startColumnIndex": 1, "endColumnIndex": 8, } ] } } }, # E行数据 { 'data': { 'sourceRange':{ 'sources': [ { "sheetId": 0, "startRowIndex": 5, "endRowIndex": 6, "startColumnIndex": 1, "endColumnIndex": 8, } ] } } }, # F行数据 { 'data': { 'sourceRange':{ 'sources': [ { "sheetId": 0, "startRowIndex": 6, "endRowIndex": 7, "startColumnIndex": 1, "endColumnIndex": 8, } ] } } } ] } }, 'position' : { 'newSheet' : True } } } } ] } service_sheets.spreadsheets().batchUpdate(spreadsheetId = id_fichier_historique, body = request_chart).execute()
内容的提问来源于stack exchange,提问作者mfau
相关产品推荐
相关产品推荐

