无法将范围插入到 Python 中的 google 个工作表

Can't insert range to google sheets in Python

我有包含数据的数组 table_data = [["11"],["22"]],[["33"],["44"]] 我想使用 sheet.values().update 将这些数据插入到 Google 工作表中,但使用 GridRange,没有命名范围 我有这个决心:

service = build('sheets', 'v4', credentials=creds())
    sheet = service.spreadsheets()
    body = {'values': values}
    SAMPLE_RANGE_NAME_2 = 'costs!A1:B2'
    value_input_option = 'RAW'
    result = sheet.values().update(
        spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME_2, valueInputOption=value_input_option, body=body).execute()

但是在 A1:B2 范围内使用不方便。我想用这样的东西

'startColumnIndex': 0,
'endColumnIndex': 1,
'startRowIndex': 0,
'endRowIndex': 1

我尝试为此使用 batchUpdate,但它只能接受字符串参数

spreadsheet_id = SPREADSHEET_ID  # TODO: Update placeholder value.

batch_update_spreadsheet_request_body = {
        "requests": [
            {
                "pasteData": {
                    "data": str(table_data),
                    "type": "PASTE_NORMAL",
                    "delimiter": ",",
                    "coordinate": {
                        "sheetId": 0,
                        "rowIndex": 0,
                        "columnIndex": 0
                    }
                }
            }
        ]
    }
request = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body=batch_update_spreadsheet_request_body)
response = request.execute()
  • 您想使用 GridRange 放置值。
  • 您想使用 table_data = [["11"],["22"]],[["33"],["44"]] 作为值。
    • 我认为如果你想把值放在2行2列,它就变成了table_data = [["11", "22"], ["33", "44"]]。所以我用了这个。
    • 如果要把11、22、33、44分别放到A1、B1、A2、B2中,就变成了table_data = [["11", "22"], ["33", "44"]]
    • 如果要把11、22、33、44分别放到A1、A2、B1、B2中,就变成了table_data = [["11", "33"], ["22", "44"]]

如果我的理解是正确的,用batchUpdate的"updateCells"方法代替"pasteData"怎么样?我认为您的情况有几种解决方案。所以请把这当作其中之一。

修改后的脚本:

spreadsheet_id = SPREADSHEET_ID
sheetId = 0
table_data = [["11", "33"], ["22", "44"]]  # or table_data = [["11", "22"], ["33", "44"]]
rows = [{'values': [{'userEnteredValue': {'stringValue': f}} for f in e]} for e in table_data]
rng = {'sheetId': sheetId, 'startRowIndex': 0, 'startColumnIndex': 0}
fields = 'userEnteredValue'
body = {'requests': [{'updateCells': {'rows': rows, 'range': rng, 'fields': fields}}]}
request = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body=body)
response = request.execute()
  • 当取值到A1:B2时,可以设置左上角单元格的坐标。所以在这种情况下,GridRange 变为 {'sheetId': sheetId, 'startRowIndex': 0, 'startColumnIndex': 0}

注:

  • 如果要使用table_data = [["11"], ["22"]], [["33"], ["44"]],请将rows修改为rows = [{'values': [{'userEnteredValue': {'stringValue': f[0]}} for f in e]} for e in table_data]

参考:

如果我误解了你的问题,我深表歉意。