'Adding columns to Google Sheets
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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tanaike |
