Google 工作表 API: 从单元格复制公式

Google sheets API: copy formula from cell

none个类似问题有真实答案,我试试看

我在预先存在的电子表格上使用 Google 表格 API。

我想复制A1中的公式:=A7/A2B1=B7/B2

我可以很好地复制内容,但不能复制公式:

body = {'values': [[result.get("values")[0]]]}
new_range = 'B1'
up_result = sheet.values().update(
spreadsheetId=SPREADSHEET_ID, range=new_range, 
    valueInputOption='USER_ENTERED', body=body).execute()

有没有办法复制公式?

是否比简单地使用数组公式更复杂?

=数组公式(A7:7/A2:2)

如果你只想把它转到B(或另一个设置列),你可以使用这个:

=数组公式(A7:B7/A2:B2)

如果你只希望它达到第 2 行中的数据,你可以使用这个:

=arrayformula(if(isblank(A2:2),A7:7/A2:2))

  • 您想将单元格 "A1" 的公式 =A7/A2 复制到单元格 "B1" 作为 =B7/B2
  • 您想使用表格 API 和 Python 的 google-api-python-客户端来实现此目的。
    • 根据你的脚本,我认为你可能会使用 google-api-python-client 和 Python,尽管 Python 的标签没有找到。
  • 您已经能够使用表格为电子表格输入和获取值 API。

如果我的理解是正确的,这个修改怎么样?在这次修改中,我使用了SheetsAPI.spreadsheets.batchUpdate的方法"CopyPasteRequest"。

修改后的脚本:

在使用此脚本之前,请设置 spreadsheet_idsheetId 的变量。

service = build('sheets', 'v4', credentials=creds)
spreadsheet_id = '###'  # Please set Spreadsheet ID.
sheetId = "###"  # Please set sheet ID.

batch_update_spreadsheet_request_body = {
    "requests": [
        {
            "copyPaste": {
                "source": {
                    "sheetId": sheetId,
                    "startRowIndex": 0,
                    "endRowIndex": 1,
                    "startColumnIndex": 0,
                    "endColumnIndex": 1
                },
                "destination": {
                    "sheetId": sheetId,
                    "startRowIndex": 0,
                    "endRowIndex": 1,
                    "startColumnIndex": 1,
                    "endColumnIndex": 2
                },
                "pasteType": "PASTE_FORMULA"
            }
        }
    ]
}
request = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body=batch_update_spreadsheet_request_body)
response = request.execute()
print(response)
  • 请将范围设置为gridrange。
    • 0, 1, 0, 1 对于 startRowIndexendRowIndexstartColumnIndexendColumnIndex 表示单元格 "A1".
    • 0, 1, 1, 2 对于 startRowIndexendRowIndexstartColumnIndexendColumnIndex 表示单元格 "B1".

结果:

  • 当上面的脚本是运行时"A1"的单元格有=A7/A2=B7/B2被放到单元格"B1".

注:

  • 在上面的脚本中,授权过程被省略了。请注意这一点。所以关于这个,请使用你的脚本。

参考文献:

如果我误解了您的问题而这不是您想要的结果,我深表歉意。