Search code examples
pythonjsongoogle-sheets-apipygsheets

How to upload a worksheet using pygsheets


I'm working with http://pygsheets.readthedocs.io/en/latest/index.html a wrapper around the google sheets api v4.

I have a small script where I am trying to select a json sheet to upload to a google sheets worksheet. The file name is made up of the:

spreadsheetname_year_month_xxx.json

The code:

import tkinter as tk
import tkFileDialog
import pygsheets


root = tk.Tk()
root.withdraw()
file_path = tkFileDialog.askopenfilename()
print file_path
file_name = file_path.split('/')[-1]
print file_name
file_name_segments = file_name.split('_')
spreadsheet = file_name_segments[0]
worksheet = file_name_segments[1]+'_'+file_name_segments[2]

gc = pygsheets.authorize(outh_file='client_secret_xxxxxx.apps.googleusercontent.com.json')

ssheet = gc.open(spreadsheet)
ws = ssheet.add_worksheet(worksheet(ssheet,str(raw_input(file_path))))

The file path leads to a generated json file that looks like:

{
  "count": 12, 
  "results": [
    {
      "case": "abc1", 
      "case_name": "invalid", 
      "case_type": "invalid", 

    }, 
    {
      "case": "abc2", 
      "case_name": "invalid", 
      "case_type": "invalid", 
      },
............

I am getting :

File "upload_to_google_sheets.py", line 27, in <module>
ws = ssheet.add_worksheet(worksheet(ssheet,str(raw_input(file_path))))
TypeError: 'unicode' object is not callable

As you can see I'm trying to instantiate a worksheet with the json data. What am I doing wrong?


Solution

  • The JsonSheet param is not for values of the worksheet, it is for specifying the properties of the worksheet, hence should be of this format.

    As directly converting a json to spreadsheet is rather ambiguous, you will need to first convert it to a numpy array (matrix) or an pandas DataFrame. Then you can use set_as_df of just update_values for updating the spreadsheet.