我有一个名为“模板”的Google工作表文件。它有2个工作表。我还有100个其他文件,分别称为“ Instance01”,“ Instance02”等,其中有2个工作表与“模板”中的工作表具有相同的名称。
我在“模板”中创建了一个新工作表,称为“ sheet3”。我想将其复制到100个“实例”文档中的每个文档中,并在每个实例中保留名称“ sheet3”。
我可以使用gspread实现吗?如何?如果没有,还有其他方法可以通过编程方式(或在合理的时间和精力范围内)进行吗?
答案 0 :(得分:0)
@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
# https://stackoverflow.com/questions/38074069/how-do-i-rename-a-worksheet-in-a-google-sheets-spreadsheet-using-the-api-in-py
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)
答案 1 :(得分:0)
作为复制工作表的方法,Sheets API中有“ spreadsheets.sheets.copyTo”方法。
您可以在this thread上查看示例脚本。我以为,因为凭据的对象可用于gspread和googleapiclient,所以可能有助于实现这一点。