简体   繁体   English

如何通过python在单元格中使用Google sheet API V4插入注释

[英]How to use Google sheet API V4 insert note in cell by python

I don't know how to add note in a cell by Google Sheet API: https://developers.google.com/sheets/api/guides/values#writing_multiple_ranges我不知道如何通过 Google Sheet API 在单元格中添加注释: https : //developers.google.com/sheets/api/guides/values#writing_multiple_ranges

I read info of Google Sheet API: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#CellData我阅读了 Google Sheet API 的信息: https : //developers.google.com/sheets/api/reference/rest/v4/spreadsheets#CellData

I also read this question but it's still not working Is it possible to use the Google Spreadsheet API to add a comment in a cell?我也阅读了这个问题,但它仍然不起作用是否可以使用 Google 电子表格 API 在单元格中添加注释?

I don't know how to set note in the value.我不知道如何在值中设置注释。 I need someone help ~!我需要人帮忙~! Thanks a lot.非常感谢。

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
# Scope type --> https://developers.google.com/sheets/api/guides/authorizing
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'  
CLIENT_SECRET_FILE = 'client_secret.json'        # credentials file name
APPLICATION_NAME = 'auto_update_caspar'


def get_credentials():
"""Gets valid user credentials from storage.

If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.

Returns:
    Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
    os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
                               'auto_update_client_caspar.json')

store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
    flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
    flow.user_agent = APPLICATION_NAME
    if flags:
        credentials = tools.run_flow(flow, store, flags)
    else: # Needed only for compatibility with Python 2.6
        credentials = tools.run(flow, store)
    print('Storing credentials to ' + credential_path)
return credentials

def main():
"""Shows basic usage of the Sheets API.

Creates a Sheets API service object and prints the names and majors of
students in a sample spreadsheet:
https://docs.google.com/spreadsheets/d/1k7OmDU_QUrCPVmsEpWFRCj-4BOu6PcUb7-SQlA7T_8I/edit
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                'version=v4')
service = discovery.build('sheets', 'v4', http=http,
                          discoveryServiceUrl=discoveryUrl)

spreadsheetId = '1lEJeSNe5T3rNXEEMjY4D04QkoW-ngOeiFo40_S4H4FI'
rangeName = 'stress_temp!A3'

result = service.spreadsheets().values().get(
    spreadsheetId=spreadsheetId, range=rangeName).execute()
print (result)
values = result.get('values', [])

if not values:
    print('No data found.')
else:
    print('Name, Major:')
    for row in values:
        # Print columns A and E, which correspond to indices 0 and 4.
        print('%s' % row[0])



value_input_option = 'RAW'
range_name = 'stress_temp!A3'
values = [['aa']]
data = [
    {
        'range': range_name,
        'values': values
    },
]`enter code here`
body = {
  'valueInputOption': value_input_option,
  'data': data
}
result = service.spreadsheets().values().batchUpdate(
    spreadsheetId=spreadsheetId, body=body).execute()



if __name__ == '__main__':
main()

In Python, I use this piece of code and it work.在 Python 中,我使用了这段代码并且它工作正常。

from googleapiclient.discovery import build
from google.oauth2 import service_account

SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file",
                  "https://www.googleapis.com/auth/spreadsheets"]
SERVICE_ACCOUNT_FILE = 'credentials.json'

credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('sheets', 'v4', credentials=credentials)

spreadsheetId = "O188999ITC"
sheetid_src = "123a"
notes = {
            "updateCells": {
                "range": {
                    "sheetId": sheetid_src,
                    "startRowIndex": 1,
                    "endRowIndex: 1,
                    "startColumnIndex": 1,
                    "endColumnIndex": 1
                },
                "rows": [
                    {
                        "values": [
                            {
                                "note": "my note"
                            }
                        ]
                    }
                ],
                "fields": "note"
            }
        }
body = {"requests":[notes]}
result = service.spreadsheets().values().batchUpdate(
    spreadsheetId=spreadsheetId, body=body).execute()

Note are available in API with cellData, so you have to update values of differents cells with the keyword "Notes". Note 在带有 cellData 的 API 中可用,因此您必须使用关键字“Notes”更新不同单元格的值。

You can find more information here : https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#celldata您可以在此处找到更多信息: https : //developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#celldata

I don't see any documentation regarding your issue.我没有看到有关您的问题的任何文档。 You may refer with this SO thread however it discussed how to get a note using getNote() .您可以参考这个SO 线程,但是它讨论了如何使用getNote()获取笔记。 In your case, you need to use Google Apps Script and use the methods:在您的情况下,您需要使用 Google Apps Script 并使用以下方法:

  • setNote(note) - Sets the note to the given value. setNote(note) - 将注释设置为给定值。
  • setNotes(notes) - Sets a rectangular grid of notes (must match dimensions of this range). setNotes(notes) - 设置一个矩形的音符网格(必须匹配这个范围的尺寸)。

You may also check into this related reported issue .您也可以查看此相关报告的问题 Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM