4

(beginner) I'm attempting to copy values from one spreadsheet to another using python. I'm using gspread but I can't seem to figure out how to copy the values from my first spreadsheet to the other. How can I copy values from the first spreadsheet and paste it on the other using python?

Here is the updated code:import gspread

from oauth2client.service_account import ServiceAccountCredentials


scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('sheetproject-956vg2854670.json',scope)
client = gspread.authorize(creds)






spreadsheetId= "1CkeZ8Xw4Xmho-mrFP9teHWVT-unkApzMSUFql5KkrGI"
sourceSheetName = "python test"
destinationSheetName = "python csv"

client = gspread.authorize(creds)
spreadsheet = client.open_by_key(spreadsheetId)
sourceSheetId = spreadsheet.worksheet("python test")._properties['0']. #gid value in the url
destinationSheetId = spreadsheet.worksheet("python csv")._properties['575313690'] #gid value in the url
body = {
    "requests":  [
        {
            "copypaste": {
                "source": {
                    "sheetId": 0,

                    "startRowIndex": 0,
                    "endRowIndex": 20,
                    "startColumnIndex": 0,
                    "endcolumnIndex": 1
                },
                "destination": {
                    "sheetId": 575313690,
                    "startRowIndex": 0,
                    "endRowIndex": 20,
                    "startColumnIndex": 0,
                    "endcolumnIndex": 1
                },
                "pasteType": "Paste_Normal"
            }
        }
    ]
}
res = spreadsheet.batch_update(body)
print(res)
Jordan
  • 63
  • 2
  • 8

3 Answers3

3

Your requirements:

  • You want to copy the values from a sheet to other sheet in a Google Spreadsheet.
  • You want to achieve this using gspread with python.
  • You have already been able to get and put values for Google Spreadsheet using Google Sheets API.

In this answer, I would like to propose to use batch_update for copying the values from from a sheet to other sheet in the Spreadsheet. In this case, your goal can be achieved by one API call.

Sample script:

In this sample script, the script of authorization is removed. The sample script for copying values from a sheet to other sheet in the Spreadsheet is shown. So when you use this script, please add the authorization script, and run the script.

spreadsheetId = "###"  # Please set the Spreadsheet ID.
sourceSheetName = "Sheet1"  # Please set the sheet name of source sheet.
destinationSheetName = "Sheet2"  # Please set the sheet name of destination sheet.

client = gspread.authorize(credentials)
spreadsheet = client.open_by_key(spreadsheetId)
sourceSheetId = spreadsheet.worksheet(sourceSheetName)._properties['sheetId']
destinationSheetId = spreadsheet.worksheet(destinationSheetName)._properties['sheetId']
body = {
    "requests": [
        {
            "copyPaste": {
                "source": {
                    "sheetId": sourceSheetId,
                    "startRowIndex": 0,
                    "endRowIndex": 5,
                    "startColumnIndex": 0,
                    "endColumnIndex": 5
                },
                "destination": {
                    "sheetId": destinationSheetId,
                    "startRowIndex": 0,
                    "endRowIndex": 5,
                    "startColumnIndex": 0,
                    "endColumnIndex": 5
                },
                "pasteType": "PASTE_VALUES"
            }
        }
    ]
}
res = spreadsheet.batch_update(body)
print(res)

Note:

  • In this sample script, the values of cells of A1:E5 in the sheet of "Sheet1" are copied to the cells of A1:E5 in the sheet of "Sheet2".
  • In this case, the range is given by the GridRange.
  • This is a simple sample script. So please modify this for your actual situation.

References:

halfer
  • 19,824
  • 17
  • 99
  • 186
Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • is the sheet id the same thing as the Gid? – Jordan Mar 22 '20 at 01:54
  • @Jordan Thank you for replying. I apologize for the inconvenience. If `Gid` you say is `gid` of `https://docs.google.com/spreadsheets/d/###/edit#gid=123456`, the value of `sheetId` is the same with that of `gid`. By the way, if my answer didn't resolve your issue, please tell me. I have to modify it. – Tanaike Mar 22 '20 at 01:58
  • I'm still working through it however, the Gid from sheet 1 is 0, but when I plug that in, it the terminal reads: File "/Users/jordanmaggin/Desktop/python/copypaste.py", line 20, in sourceSheetId = spreadsheet.worksheet("python test")._properties['0'] KeyError: '0' – Jordan Mar 22 '20 at 03:59
  • @Jordan Thank you for replying. I apologize for the inconvenience. If you are actually using `sourceSheetId = spreadsheet.worksheet("python test")._properties['0']`, unfortunately, it is not correct. Because `'sheetId'` of `_properties['sheetId']` is used as the key of the object. You can also see this from the error message of `KeyError: '0'`. If you cannot understand about this, can you provide your current script for replicating your issue. If you can do, please add it to your question. By this, I would like to confirm it. If you can cooperate to resolve your issue, I'm glad. – Tanaike Mar 22 '20 at 04:08
  • @Jordan Thank you for replying and adding the script. From your script, in your case, the sheet IDs have already used in the request body. In this case, please remove `sourceSheetId = spreadsheet.worksheet("python test")._properties['0'].` and `destinationSheetId = spreadsheet.worksheet("python csv")._properties['575313690'] `, and run again. If the sheets with the sheet IDs of `0` and `575313690` are not included in the Spreadsheet, an error occurs. So please be careful this. – Tanaike Mar 22 '20 at 22:05
0

1) Import openpyxl library as xl.

2) Open the source excel file using the path in which it is located.

Note: The path should be a string and have double backslashes (\) instead of single backslash (). Eg: Path should be C:\Users\Desktop\source.xlsx Instead of C:\Users\Admin\Desktop\source.xlsx

3) Open the required worksheet to copy using the index of it. The index of worksheet ‘n’ is ‘n-1’. For example, the index of worksheet 1 is 0.

4) Open the destination excel file and the active worksheet in it.

5) Calculate the total number of rows and columns in source excel file.

6) Use two for loops (one for iterating through rows and another for iterating through columns of the excel file) to read the cell value in source file to a variable and then write it to a cell in destination file from that variable.

7) Save the destination file.

here is a py only code example from How to copy over an Excel sheet to another workbook in Python:

    import openpyxl as xl

path1 = 'C:\\Users\\Xukrao\\Desktop\\workbook1.xlsx'
path2 = 'C:\\Users\\Xukrao\\Desktop\\workbook2.xlsx'

wb1 = xl.load_workbook(filename=path1)
ws1 = wb1.worksheets[0]

wb2 = xl.load_workbook(filename=path2)
ws2 = wb2.create_sheet(ws1.title)

for row in ws1:
    for cell in row:
        ws2[cell.coordinate].value = cell.value

wb2.save(path2)
ItsMeNaira
  • 360
  • 1
  • 12
0

Using only gspread

For copying the whole sheet to another spreadsheet:

import gspread

client = gspread.authorize(<put here credentials>)

source_gsheet_url = '<put here url>'
source_worksheet_name = '<put here name>'
dest_gsheet_url = '<put here url>'

ws = gc.open_by_url(source_gsheet_url).worksheet(source_worksheet_name)
ws.copy_to(dest_gsheet_url)
George C
  • 1,168
  • 13
  • 30