Google Spreadsheet API:duplicateSheet:没有带ID的工作表

时间:2017-07-18 02:56:21

标签: python google-sheets google-api-python-client

我正在尝试使用duplicateSheet方法使用batchUpdate()请求复制工作表:

body['requests'] = [
    {
        "duplicateSheet": {
            "newSheetName": date_today(),
            "sourceSheetId": int(sheet_number)
        }
    }
]

sheet = service.spreadsheets()
request = sheet.batchUpdate(spreadsheetId=spreadsheetId,
                            body=requestBody)
response = request.execute()

但我收到此错误消息:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/xxxxxxxxxx_xxxxxxxx-xxxxxxx:batchUpdate?alt=json returned "Invalid requests[0].duplicateSheet: No sheet with id: 3">

但是这张纸确实有这张纸。使用此JS代码确认工作表的ID:

SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getIndex();

2 个答案:

答案 0 :(得分:3)

"sourceSheetId"使用的工作表ID是gid。可以通过sheets.spreadsheets.get(对于Python)和getSheetId()(对于GAS)检索工作表ID。示例脚本如下。

Python示例

sheet = service.spreadsheets()
request = sheet.get(
    spreadsheetId=spreadsheetId,
    fields="sheets(properties(sheetId,title))")
response = request.execute()

GAS样本

var res = [
  [i.getSheetId(), i.getSheetName()]
  for each (i in SpreadsheetApp.getActiveSpreadsheet().getSheets())
];

答案 1 :(得分:0)

结束使用此代码(感谢我的同事):

meta = service.spreadsheets().get(spreadsheetId=SPREADSHEET_ID).execute()
sheets = meta.get("sheets", {})

for sheet in sheets:
    sheet_index = sheet.get("properties", {}).get("index")
    sheet_id = sheet.get("properties", {}).get("sheetId")
    if (sheet_index == index):
        return sheet_id