Google spreadsheet api batchupdate using python

Question:

I am trying to update multiple cell values using batchupdate. But giving me below error

My code:

import gspread

gc = gspread.service_account(filename='gdrive_cred.json')
sh = gc.open('SmartStraddle').sheet1

stock_name = "NIFTY50"
stock_price = 15000

batch_update_values = {
    'value_input_option': 'USER_ENTERED',
    'data': [
        {
            'range': "A1",
            'values': [stock_name]
        },
        {
            'range': "B2",
            'values': [stock_price]
        }
    ],
}

sh.batch_update(batch_update_values)

Error Message:

Traceback (most recent call last):
  File "*interactiveshell.py", line 3433, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-028b1369fa03>", line 23, in <module>
    sh.batch_update(batch_update_values)
  File "*utils.py", line 702, in wrapper
    return f(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^
  File "*worksheet.py", line 1152, in batch_update
    data = [
           ^
  File "*worksheet.py", line 1153, in <listcomp>
    dict(vr, range=absolute_range_name(self.title, vr["range"])) for vr in data
                                                   ~~^^^^^^^^^
TypeError: string indices must be integers, not 'str'

I am following this google documentation, but not sure how to construct data': [] field correctly.

Asked By: acr

||

Answers:

I guessed that you wanted to use batch_update(data, **kwargs).

Modification points:

  • When I saw the document of batch_update(data, **kwargs), it seems that the argument of data is as follows.

      batch_update_values = [
          {"range": "A1", "values": [[stock_name]]},
          {"range": "B2", "values": [[stock_price]]},
      ]
    
  • value_input_option is required to be put as an argument.

When these points are reflected in your script, how about the following modification?

Modified script:

From:

batch_update_values = {
    'value_input_option': 'USER_ENTERED',
    'data': [
        {
            'range': "A1",
            'values': [stock_name]
        },
        {
            'range': "B2",
            'values': [stock_price]
        }
    ],
}

sh.batch_update(batch_update_values)

To:

batch_update_values = [
    {"range": "A1", "values": [[stock_name]]},
    {"range": "B2", "values": [[stock_price]]},
]
sh.batch_update(batch_update_values, value_input_option="USER_ENTERED")
  • When this modified script is run, the values of NIFTY50 and 15000 are put to the cells "A2" and "B2", respectively.

Reference:

Answered By: Tanaike