简体   繁体   English

(gspread) 如何使用 gspread 将自定义公式放入单元格中?

[英](gspread) How can I put a custom formula into a cell using gspread?

I want to put a custom formula into a sheet using gspread.我想使用 gspread 将自定义公式放入工作表中。 This can be done in Google Sheets and it looks like this .这可以在 Google 表格中完成,看起来像这样

I want to automate the process of inputting this using gspread, similar to how you can use batch_update to format multiple cells, I would like to use it to add a custom formula to multiple cells.我想使用 gspread 自动输入这个过程,类似于如何使用 batch_update 格式化多个单元格,我想用它来向多个单元格添加自定义公式。

you can use valueInputOption='USER_ENTERED' parameter on your sheet update.您可以在工作表更新中使用valueInputOption='USER_ENTERED'参数。 This will basically input into the spreadsheet call like you input it manually yourself.这将基本上像您自己手动输入一样输入到电子表格调用中。 View more here, https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption在此处查看更多信息, https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption

with sheets api:与张 api:

sheets_service = build('sheets', 'v4', credentials=auth.get_credentials())
response = sheets_service.spreadsheets().values().update(
                spreadsheetId='<ENTER SPREADSHEET ID HERE>', range='<ENTER CELL RANGE HERE>', 
                valueInputOption='USER_ENTERED', body='<YOUR CUSTOM FORMULA HERE>').execute()

with gspread:使用 gspread:

sh.values_update(
    'Sheet1!A2',
    params={
        'valueInputOption': 'USER_ENTERED'
    },
    body={
        'values': ...
    }
)

https://docs.gspread.org/en/v3.7.0/api.html#gspread.models.Spreadsheet.values_update https://docs.gspread.org/en/v3.7.0/api.html#gspread.models.Spreadsheet.values_update

I believe your goal is as follows.我相信你的目标如下。

  • You want to create the conditional formatting rule of =indirect("Sheet1!B2")<>"hello" and when this is true, you want to set the background color to white.您想创建=indirect("Sheet1!B2")<>"hello"的条件格式规则,当这是真的时,您想将背景颜色设置为白色。
  • You want to create the conditional formatting rule for all cells in a sheet of Google Spreadsheet.您想为 Google 电子表格中的所有单元格创建条件格式规则。
  • You want to achieve this using gspread for python.您想使用 gspread for python 来实现这一点。

In this case, how about the following sample script?在这种情况下,下面的示例脚本怎么样?

Sample script:示例脚本:

spreadsheetId = "###" # Please set your Spreadsheet ID.
spreadsheet = client.open_by_key(spreadsheetId)
sheet = spreadsheet.worksheet("Sheet2") # Please set your sheet name.

formula = '=indirect("Sheet1!B2")<>"hello"'
body = {
    "requests": [
        {
            "addConditionalFormatRule": {
                "index": 0,
                "rule": {
                    "ranges": [{"sheetId": sheet.id}],
                    "booleanRule": {
                        "condition": {
                            "type": "CUSTOM_FORMULA",
                            "values": [{"userEnteredValue": formula}],
                        },
                        "format": {
                            "backgroundColorStyle": {
                                "rgbColor": {"red": 1, "green": 1, "blue": 1}
                            }
                        },
                    },
                },
            }
        }
    ]
}
spreadsheet.batch_update(body)
  • When this script is run, the above addConditionalFormatRule is created for all cells in "Sheet2".运行此脚本时,将为“Sheet2”中的所有单元格创建上述addConditionalFormatRule When Sheet1!B2 is not hello , the background color of all cells of "Sheet2" is white.Sheet1!B2不是hello时,“Sheet2”所有单元格的背景颜色为白色。

References:参考:

Added:添加:

About your following reply,关于您的以下回复,

I've modified my script based off of yours and it works perfect.我已经根据您的脚本修改了我的脚本,并且效果很好。 I just want to know if its possible to have a list of conditional format rules that can be created for separate cells.我只想知道是否有可能为单独的单元格创建条件格式规则列表。 Is this possible?这可能吗?

Your expected goal is the following sample script?您的预期目标是以下示例脚本?

Sample script:示例脚本:

spreadsheetId = "###" # Please set your Spreadsheet ID.
sheetName = "Sheet2" # Please set your sheet name.
spreadsheet = client.open_by_key(spreadsheetId)
sheet = spreadsheet.worksheet(sheetName)
sheetId = sheet.id
service = build("sheets", "v4", credentials=client.auth)
res = service.spreadsheets().get(spreadsheetId=spreadsheetId, ranges=sheetName, fields="sheets(properties(gridProperties(rowCount,columnCount)))").execute()

row = res["sheets"][0]["properties"]["gridProperties"]["rowCount"]
column = res["sheets"][0]["properties"]["gridProperties"]["columnCount"]

formula = '=indirect("Sheet1!B2")<>"hello"'
requests = []
for i in range(row):
    for j in range(column):
        requests.append(
            {
                "addConditionalFormatRule": {
                    "index": 0,
                    "rule": {
                        "ranges": [
                            {
                                "sheetId": sheetId,
                                "startRowIndex": i,
                                "endRowIndex": i + 1,
                                "startColumnIndex": j,
                                "endColumnIndex": j + 1,
                            }
                        ],
                        "booleanRule": {
                            "condition": {
                                "type": "CUSTOM_FORMULA",
                                "values": [{"userEnteredValue": formula}],
                            },
                            "format": {
                                "backgroundColorStyle": {
                                    "rgbColor": {"red": 1, "green": 1, "blue": 1}
                                }
                            },
                        },
                    },
                }
            }
        )
spreadsheet.batch_update({"requests": requests})
  • In this case, in order to retrieve the values of row and column of the sheet, googleapis for python is used.在这种情况下,为了检索工作表的行和列的值,使用了 python 的 googleapis。 So, please add from googleapiclient.discovery import build .所以,请添加from googleapiclient.discovery import build
  • When this script is run, addConditionalFormatRule is create in all cells of "Sheet2".运行此脚本时,会在“Sheet2”的所有单元格中创建addConditionalFormatRule But, I thought that this is the same result with the above script.但是,我认为这与上述脚本的结果相同。
  • PLESE BE CAREFUL请小心
    • When this script is run, addConditionalFormatRule is create in all cells of "Sheet2".运行此脚本时,会在“Sheet2”的所有单元格中创建addConditionalFormatRule So, for example, when the default sheet is used, a lot of conditional formatting rules are created in all cells of 1000 rows x 26 columns.因此,例如,当使用默认工作表时,会在 1000 行 x 26 列的所有单元格中创建许多条件格式规则。 Please be careful about this.请注意这一点。
    • If you want to limit the cells, please manually set row and column .如果要限制单元格,请手动设置rowcolumn

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

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