使用Python调用Google API为Google Sheets特定单元格添加评论失败的问题求助
使用Python调用Google API为Google Sheets特定单元格添加评论失败的问题求助
看起来你踩了一个常见的API使用误区——你用错API啦!
你现在调用的是Google Drive API的comments().create()方法,但Drive API的评论是针对整个文件的,并不是和Google Sheets里的特定单元格绑定的。这就导致你创建的评论其实是“文件级”的,根本关联不到你想要的单元格,所以才会出现评论显示[Original content deleted]、单元格也没评论标记的情况。
要给Google Sheets的特定单元格添加评论,你应该使用Google Sheets API的spreadsheets.comments.create方法,而不是Drive API。下面是修改后的代码示例:
sheets_service = build('sheets', 'v4', credentials=credentials) content = request.form.get('content') # 指定你要添加评论的单元格范围,比如Sheet1的A1单元格 target_range = 'Sheet1!A1' # 使用Sheets API创建单元格评论 response = sheets_service.spreadsheets().comments().create( spreadsheetId=SPREADSHEET_ID, body={ 'range': { 'a1Notation': target_range # 用A1格式直接指定单元格,简单直观 }, 'content': content } ).execute() print(f"评论创建成功,ID: {response.get('commentId')}")
另外还有几个注意点要提醒你:
- 确保你已经在Google Cloud Console启用了Sheets API,而不是只启用Drive API
- 你的credentials需要包含Sheets相关的权限,比如
https://www.googleapis.com/auth/spreadsheets(如果只是评论,https://www.googleapis.com/auth/spreadsheets.readonly是不够的,需要编辑权限) - 如果你需要更精确地指定单元格,也可以用行列索引的方式代替
a1Notation,比如针对A1单元格:'range': { 'sheetId': 你的工作表GID, # 可以从Sheets的URL里找到,比如gid=123456,123456就是sheetId 'startRowIndex': 0, 'endRowIndex': 1, 'startColumnIndex': 0, 'endColumnIndex': 1 }
备注:内容来源于stack exchange,提问作者hohograndma
相关产品推荐
相关产品推荐

