I am trying to replace all the values in a column which starts with “barcode”. However for now, I am able to replace all the values based on the name of the values.
JavaScript
x
17
17
1
import gspread
2
from oauth2client.service_account import ServiceAccountCredentials
3
4
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
5
credentials = ServiceAccountCredentials.from_json_keyfile_name('extended-signal-307001-
6
4e0bee527c0d.json', scope)
7
gc = gspread.authorize(credentials)
8
wks = gc.open('test').sheet1
9
10
column_o = wks.findall('barcode recognition error', in_column=15)
11
print(column_o)
12
13
for cell in column_o:
14
cell.value = 'barcode error'
15
16
wks.update_cells(column_o)
17
Currently, it only replaces if it finds the exact value inside the column which is “barcode recognition error”. I want to find the values that starts with “barcode” and replace all those values with “barcode error”.
Advertisement
Answer
I believe your goal and your current situation as follows.
- You want to replace the cell value including
barcode
at the top word withbarcode error
. - You want to achieve this using gspread with python.
- You have already been able to get and put values for Google Spreadsheet using Sheets API.
In this case, I would like to propose to use the batchUpdate method of Sheets API. I thought that when the batchUpdate method is used, your goal can be achieve by one API call. The sample script is as follows.
Sample script:
Please use your script for retrieving credentials
.
JavaScript
1
19
19
1
gc = gspread.authorize(credentials)
2
spreadsheet = gc.open('test')
3
wks = spreadsheet.sheet1
4
body = {
5
"requests": [
6
{
7
"findReplace": {
8
"find": "^barcode[\s\w]+",
9
"searchByRegex": True,
10
"range": {
11
"sheetId": wks.id,
12
},
13
"replacement": "barcode error"
14
}
15
}
16
]
17
}
18
spreadsheet.batch_update(body)
19
- In this sample script, all cells in the 1st tab of the Spreadsheet are checked and replaced with
barcode error
. If you want to check the specific column and row, please set the gridRange forrange
.