简体   繁体   中英

Copying and Pasting from one Google Sheet to another

I am relatively new to python and am struggling to figure out a way to copy and paste data from one google sheet to another using gspread. Does anyone know how to do this without using win32 to copy to an excel as a bridge?? Please see the code and error msg below:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
import numpy as np
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(r'C:\Users\Documents\Scripts\FX Rates Query\key.json', Scope)

client = gspread.authorize(creds)

sheet = client.open("Capital").sheet1
data=sheet.get_all_records()

df = pd.DataFrame(data)
df.to_excel(r'C:\Users\Documents\Reserves_extract.xlsx')
sheet1 = client.open("Cash Duration ").sheet1
mgnt_fees = sheet1.col_values(5)
fees = pd.DataFrame(mgnt_fees)
fees1 = fees[fees!=0]
print(fees1)
update = sheet1.update('B7',fees1)
##^^ERROR MSG IS COMING FROM HERE

Error msg:

raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type DataFrame is not JSON serializable

From your replying of I would like to copy a specific column from google spreadsheet A to google spreadsheet B , in this case, how about the following modification?

Modified script:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
import numpy as np
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(r'C:\Users\Documents\Scripts\FX Rates Query\key.json', Scope)

client = gspread.authorize(creds)

# I modified below script.
spreadsheetA = client.open("Capital")
spreadsheetB = client.open("Cash Duration ")
srcCol = "'" + spreadsheetA.sheet1.title + "'!A1:A" # This is the column "A" of the 1st tab of Spreadsheet A.
dstCol = "'" + spreadsheetB.sheet1.title + "'!B1:B" # This is the column "B" of the 1st tab of Spreadsheet B.
src = spreadsheetA.values_get(srcCol)
del src['range']
spreadsheetB.values_update(dstCol, params={'valueInputOption': 'USER_ENTERED'}, body=src)
  • In this modified script, column "A" of the 1st tab of Spreadsheet A is copied to column "B" of the 1st tab of Spreadsheet B. Please modify this for your actual situation.

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM