如何修复Google Sheets API中addTable请求的列名偏移问题?
问题原因分析
你遇到的列名偏移问题,核心是对columnProperties中的columnIndex字段理解有误:该字段对应的是整个工作表的绝对列索引,而非表格范围内的相对索引。
你的表格范围是工作表的列1到3(B、C列),但请求中设置columnIndex:0(对应A列,超出表格范围)和columnIndex:1(对应B列),导致API将第一个列属性错误应用到表格外的A列,第二个属性应用到B列,表格的C列则被错误赋值为第一个属性的内容,最终出现列名错位和偏移。
解决方案
推荐两种修复方式:
方案1:移除columnIndex字段(更简洁)
columnProperties数组的默认顺序就是表格列的从左到右顺序,无需指定索引,直接按表格列顺序定义属性即可:
{ "requests": [ { "addTable": { "table": { "tableId": "xxxxxx", "name": "Foobar", "range": { "sheetId": xxxxxx, "startRowIndex": 2, "endRowIndex": 4, "startColumnIndex": 1, "endColumnIndex": 3 }, "columnProperties": [ { "columnName": "Column 1", "columnType": "PERCENT" }, { "columnName": "Column 2", "columnType": "DROPDOWN", "dataValidationRule": { "condition": { "type": "ONE_OF_LIST", "values": [ { "userEnteredValue": "Not Started" }, { "userEnteredValue": "In Progress" }, { "userEnteredValue": "Complete" } ] } } } ] } } } ], "includeSpreadsheetInResponse": false }
方案2:使用工作表绝对列索引
如果需要保留columnIndex,需将其设置为表格对应列的工作表绝对索引(你的表格两列对应工作表列1和列2):
{ "requests": [ { "addTable": { "table": { "tableId": "xxxxxx", "name": "Foobar", "range": { "sheetId": xxxxxx, "startRowIndex": 2, "endRowIndex": 4, "startColumnIndex": 1, "endColumnIndex": 3 }, "columnProperties": [ { "columnIndex": 1, "columnName": "Column 1", "columnType": "PERCENT" }, { "columnIndex": 2, "columnName": "Column 2", "columnType": "DROPDOWN", "dataValidationRule": { "condition": { "type": "ONE_OF_LIST", "values": [ { "userEnteredValue": "Not Started" }, { "userEnteredValue": "In Progress" }, { "userEnteredValue": "Complete" } ] } } } ] } } } ], "includeSpreadsheetInResponse": false }
内容的提问来源于stack exchange,提问作者kviLL
相关产品推荐
相关产品推荐

