pedrovgp
pedrovgp

Reputation: 807

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

I have a google sheet file called "template". It has 2 worksheets. I have 100 other files called "Instance01", "Instance02", etc. which have 2 worksheets with the same name as the ones in "template".

I have created a new worksheet in "template", called "sheet3". I want to copy it to each of the 100 "Instance" documents, keeping the name "sheet3" in each Instance.

Can I achieve that with gspread? And how? If not, is there another way to do it programatically (or within reasonable time and effort)?

Upvotes: 0

Views: 2869

Answers (2)

Tanaike
Tanaike

Reputation: 201338

As the method for copying the sheets, there is the method of "spreadsheets.sheets.copyTo" in Sheets API.

You can see a sample script at this thread. I thought that because the object of credentials can be used for both gspread and googleapiclient, it might help to implement this.

Reference:

Upvotes: 0

pedrovgp
pedrovgp

Reputation: 807

@Tanaike comment showed the way. I document the code I used below.

# 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)

Upvotes: 1

Related Questions