1

I am trying to add columns to a Google Sheets, but I get an error. I need to add a copy of the previous column.

Code:

def insert_column():
   sa = gspread.service_account(filename="service_account.json")
   sh = sa.open("**NAME**")
   wks = sh.worksheet("Class Data")

   data = {
       "requests": [
           {
               "insertDimension": {
                   "range": {
                       "sheetId": 0,
                       "dimension": "COLUMNS",
                       "startIndex": 4,
                       "endIndex": 5
                   },
                   "inheritFromBefore": True
               }
           },
       ],
   }

   wks.batch_update(data).execute()

An Error: TypeError: string indices must be integers

I think the problem is here wks.batch_update(data).execute() , but I don't know how to solve it.

Tanaike
  • 181,128
  • 11
  • 97
  • 165
pdvp
  • 11
  • 2
  • Please provide a minimal reproducible code. This way other users can run your code and diagnose the error – Melon May 17 '22 at 08:01

1 Answers1

0

When I saw the document of gspread, it seems that batch_update(body) is the method of class gspread.spreadsheet.Spreadsheet. But, you are using this method as the method of class gspread.worksheet.Worksheet. I think that this is the reason for your issue of TypeError: string indices must be integers. And also, execute() is not required to be used.

When these points are reflected in your script, it becomes as follows.

Modified script:

def insert_column():
   sa = gspread.service_account(filename="service_account.json")
   sh = sa.open("**NAME**")
   # wks = sh.worksheet("Class Data") # In this script, this line is not used.

   data = {
       "requests": [
           {
               "insertDimension": {
                   "range": {
                       "sheetId": 0, # <--- Please set the sheet ID of "Class Data" sheet.
                       "dimension": "COLUMNS",
                       "startIndex": 4,
                       "endIndex": 5
                   },
                   "inheritFromBefore": True
               }
           },
       ],
   }

   sh.batch_update(data)

Note:

  • This modified script supposes that your service account can access to the Spreadsheet. Please be careful about this.

Reference

Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • 1
    To the user who downvoted. When I tested my proposed script again, I confirmed that the OP's error `TypeError: string indices must be integers` was removed, and the script worked. From this situation, I cannot understand the reason for your action. Can I ask you about the detail of it? If my answer has modification points, please tell me. I would like to confirm it and improve my answer. If you can cooperate to improve this answer, I'm glad. Can you cooperate to do it? – Tanaike Aug 03 '23 at 00:50