我可以在这里想到两种方法,我在下面都包括了。
您遇到的 JSON 类型错误可以通过 casting 将 df 行作为列表解决,如 method2 所示。
只需省略table_range,即可解决将所有内容放入单元格A1 的问题。
import gspread
import pandas as pd
# set variables
docid = 'yourdocidhere'
worksheetid = 'transactions'
credfile = 'path/to/file/credentials.json'
csvfile = 'path/to/file/transactions.csv'
# load GSheet
gc = gspread.service_account(filename=credfile)
sheet = gc.open_by_key(docid)
worksheet = sheet.worksheet(worksheetid)
# load CSV file into df
df_csv = pd.read_csv(csvfile)
def method1(worksheet: gspread.Worksheet, df: pd.DataFrame):
"""This is the 'cheaty' way. Just load the existing worksheet
into df, append other df and overwrite existing worksheet.
Note that this doesn't check if the values in df are already
in the worksheet...
Args:
worksheet (gspread.Worksheet): the worksheet with which to work
df (pd.DataFrame): the df to append
"""
# just load existing GSheet into a df
df_cheat = pd.DataFrame(worksheet.get_all_records())
# perform append. You might want to play with how you merge/append
# This method has the advantage of easy sorting.
df_cheat = df_cheat.append(df).sort_values(by='Date')
# overwrite worksheet
# you could easily create a new worksheet with this method as you have
# the df_cheat to work with
worksheet.update([df_cheat.columns.values.tolist()] + df_cheat.values.tolist())
def method2(worksheet: gspread.Worksheet, df: pd.DataFrame):
"""This method goes through the df row by row and adds
it to the worksheet by using casting.
https://www.w3schools.com/python/python_casting.asp
Args:
worksheet (gspread.Worksheet): the worksheet with which to work
df (pd.DataFrame): the df to append
"""
# go over the values in the df by row
for row in df.values:
# cast as list
row = list(row)
# if you leave out the table_range it will append at the end
worksheet.append_row(row)
method1(worksheet, df_csv)
method2(worksheet, df_csv)
path/to/file/transactions.csv
Date,Time,Amount,Type,Description,Category
4/1/2019,21:49:02,-$11,Withdrawal,Intuit,*QuickBooks Work - Organization
之前
之后