谷歌表格更新代码输出‘None cells updated’问题求助
Google Sheets API 更新单元格显示“None cells updated”的解决方法
你的代码核心问题是没有使用传入的_values参数,函数内部硬编码了一个空的values列表,导致更新请求携带的是空数据,自然没有单元格被修改。
修正步骤:
- 删除函数内定义的空
values列表,直接使用传入的_values参数构建请求体 - 清理重复的导入语句,避免代码冗余
修正后的完整代码:
import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] # The ID and range of a sample spreadsheet. SAMPLE_SPREADSHEET_ID = '1ZaDwxCNxRzsV-OqaoeNvu-kDF3golHUMGh1FH11EVZ0' SAMPLE_RANGE_NAME = 'A1:B2' def update_values(spreadsheet_id, range_name, value_input_option, _values): """ Updates values in a Google Sheet range. """ creds = Credentials.from_authorized_user_file('token.json', SCOPES) try: service = build('sheets', 'v4', credentials=creds) # 直接使用传入的_values参数 body = { 'values': _values } result = service.spreadsheets().values().update( spreadsheetId=spreadsheet_id, range=range_name, valueInputOption=value_input_option, body=body).execute() print(f"{result.get('updatedCells')} cells updated.") return result except HttpError as error: print(f"An error occurred: {error}") return error if __name__ == '__main__': update_values(SAMPLE_SPREADSHEET_ID, SAMPLE_RANGE_NAME, 'USER_ENTERED', [ ['A', 'B'], ['C', 'D'], ])
运行修正后的代码,终端会输出4 cells updated,同时你的Google Sheet中A1:B2范围的单元格会被替换为传入的['A','B']和['C','D']。
内容的提问来源于stack exchange,提问作者Nilesh Pal
相关产品推荐
相关产品推荐

