使用gspread和Google sheets API复制一个sheet到多个工作簿

Use gspread and Google sheets API to copy a sheet to multiple workbooks

我有一个名为 "template" 的 google sheet 文件。它有 2 个工作sheet。我还有 100 个名为 "Instance01"、"Instance02" 等的文件,其中有 2 个工作 sheet 与 "template".

中的文件同名

我在 "template" 中创建了一个新作品sheet,名为 "sheet3"。我想将它复制到 100 个 "Instance" 文档中的每一个,并在每个实例中保留名称 "sheet3"。

我可以用 gspread 实现吗?如何?如果没有,是否有另一种方法以编程方式(或在合理的时间和努力内)进行?

@Tanaike 评论指明了方向。我在下面记录了我使用的代码。

# Build the service and gspread agent
sheets_service = build('sheets', 'v4', credentials=credentials)
gc = gspread.authorize(credentials)

# Create functions to rename the sheet after copying
# For renaming sheets
# 
def batch(requests, spreadsheetId, service):
    body = {
        'requests': requests
    }
    return service.spreadsheets().batchUpdate(spreadsheetId=spreadsheetId, body=body).execute()

def renameSheet(spreadsheetId, sheetId, newName, service):
    return batch({
        "updateSheetProperties": {
            "properties": {
                "sheetId": sheetId,
                "title": newName,
            },
            "fields": "title",
        }
    },
        spreadsheetId,
        service)

# Now execute the copies

# The ID of the spreadsheet containing the sheet to copy. Everybody has access!!!
spreadsheet_id = ORIGINAL_spreadsheet_id # template workbook

# The ID of the sheet to copy. Everybody has access!!!
sheet_id = original_sheet_id # template sheet id

for workbook_id in COPY_TO: #COPY_TO is a list of workbooks ids
    print(workbook_id)
    destiny_spreadsheet_id = workbook_id
    copy_sheet_to_another_spreadsheet_request_body = {
      "destinationSpreadsheetId": destiny_spreadsheet_id
    }

    request = sheets_service.spreadsheets().sheets().copyTo(spreadsheetId=spreadsheet_id, sheetId=sheet_id, body=copy_sheet_to_another_spreadsheet_request_body)
    response = request.execute()

    # Rename it
    copied_to_sheet = gc.open_by_key(destiny_spreadsheet_id) #template.worksheet(destiny)
    sheet = copied_to_sheet.worksheet('Copy of ' + NAME_OF_SHEET_TO_BE_COPIED)
    renameSheet(destiny_spreadsheet_id, sheet.id, NAME_OF_SHEET_TO_BE_COPIED, sheets_service)

作为复制表格的方法,表格API中有"spreadsheets.sheets.copyTo"的方法。

您可以在 查看示例脚本。我认为因为凭据对象可以同时用于 gspread 和 googleapiclient,所以它可能有助于实现这一点。

参考: