如何在Google表上编程删除所有条件格式



我尝试结合两个示例从https://developers.google.com/sheets/api/samples/conditional-formatting

  1. 阅读所有条件格式。
  2. 删除它们。

删除需要删除索引,但这在读取API响应中未返回。我尝试假设数组中返回格式的索引是适当的,但是在操作中间,这遇到了"索引的条件格式",然后才被删除。

这是我要清理的表格的副本:https://docs.google.com/spreadsheets/d/1y0tsecka-1gziimese74ihpfqgkuo985eznovq9yznovq9y0bu/edit un/eedit #gid #gid=0

该解决方案怎么样?在此解决方案中,您的问题可以通过API请求的2次解决。

1。从电子表格上的表格中检索所有条件格式。

sheets.spreadsheets.get用于这种情况。

请求:

GET https://sheets.googleapis.com/v4/spreadsheets/### spreadsheet ID ###?ranges=### sheet name ###&fields=sheets%2FconditionalFormats%2Franges%2FsheetId

请输入### spreadsheet ID ###### sheet name ###

响应:

此响应检索条件格式的数量。这用于删除条件格式。

{"sheets": [{"conditionalFormats": [
  {"ranges": [{"sheetId": #####}]},
  {"ranges": [{"sheetId": #####}]}
]}]}

2。删除所有条件格式。

sheets.spreadsheets.batchUpdate用于这种情况。

请求:

POST https://sheets.googleapis.com/v4/spreadsheets/### spreadsheet ID ###:batchUpdate

请求正文:

在这里,index是指通过上述GET方法检索的条件格式的数量。例如,当表格中有2种条件格式时,requests的长度为2。以下requests[0]表示sheets.conditionalFormats[0]如上图所示。

{"requests": [
  {"deleteConditionalFormatRule": {"sheetId": #####, "index": 0}},
  {"deleteConditionalFormatRule": {"sheetId": #####, "index": 1}}
]}

请输入### spreadsheet ID ###sheetId

注意:

  • 为了使用上述API,您可以检索访问令牌。
  • 因为要删除表上的所有条件格式,因此从电子表格中检索到的信息是必需的。

参考:

  • Sheets.spreadsheets.get
  • sheets.spreadsheets.batchupdate

如果我误解了您的问题,对不起。

详细说明以前的答案和评论,并希望能节省其他时间,这是我在给定表中删除所有条件格式的所做的。

def delete_conditional_format_rules(spread_sheet_id, sheet_id)
  reqs = []
  sheet_info = JSON.parse(google.get_spreadsheet(spread_sheet_id).to_json)
  sheet_info['sheets'].each do |info|
    if info['properties']['sheetId'] == sheet_id && info['conditionalFormats']
      info['conditionalFormats'].each do |i| 
        reqs.push(
          delete_conditional_format_rule: {
            index: 0,
            sheet_id: sheet_id
          }
        )
      end
    end
  end
  body = { requests: reqs }
  sheets.spreadsheets.batch_update_spreadsheet(spread_sheet_id, body)
end

从sheets.spreadsheets.get中获取电子表格信息后,我在每张纸上循环。在找到我要编辑的表格与通过该方法传递的内容进行编辑之后,我检查一下它是否具有任何条件格式(以进行null证明)。然后,对于条件词的每个数组元素,我将请求对象添加到我传达的最终数组中,并在索引0中删除。

这可能有点笨拙,但是我知道它要做我需要的事情。希望这会有所帮助。

最新更新