首页 > 解决方案 > How to reverse engineer Custom Formatting into App Script?

问题描述

Is it possible to reverse engineer Custom Formatting rules that I entered by hand and create an App Script in return?

I would like to generate something like this

var rule = SpreadsheetApp.newConditionalFormatRule()
  .whenNumberBetween(1, 10)
  .setBackground("#FF0000")
  .setRanges([range])
  .build();

enter image description here

标签: google-apps-scriptgoogle-sheets

解决方案


在您的情况下,我认为使用 Sheets API 时,可以简单地创建脚本。

因为在使用 Sheets API 时,条件格式规则的每个设置都可以作为一个对象检索,并且可以使用该对象进行设置。另一方面,当使用电子表格服务(SpreasheetApp)时,需要准备每种设置方法。在这种情况下,我认为脚本可能有点复杂。

因此,在这个答案中,作为实现您目标的一个方向,我想建议将 Sheets API 与 Google Apps Script 一起使用。

示例脚本 1:

此示例脚本从 Google 电子表格中的特定工作表中检索条件格式规则。在使用此脚本之前,请在 Advanced Google services 中启用 Sheets API

function myFunction1() {
  const srcSpreadsheetId = "###"; // Please set the source Spreadsheet ID.
  const srcSheetId = "0"; // Please set the source sheet ID.

  const obj = Sheets.Spreadsheets.get(srcSpreadsheetId, {fields: "sheets(conditionalFormats,properties)"});
  const rules = obj.sheets.reduce((ar, s) => {
    if (s.properties.sheetId == srcSheetId && s.conditionalFormats) ar = ar.concat(s.conditionalFormats);
    return ar;
  }, []);
  console.log(JSON.stringify(rules)); // You can see all rules of conditional format rules in the specific sheet of the Spreadsheet.
}

示例脚本 2:

此示例脚本将通过上述示例脚本检索到的条件格式规则设置为 Google 电子表格中的特定工作表。

function myFunction2() {
  const rules = [,,,]; // Please set the retrieved conditional format rules.

  if (rules.length > 0) {
    const dstSpreadsheetId = "###"; // Please set the source Spreadsheet ID.
    const dstSheetId = "0"; // Please set the source sheet ID.

    const requests = rules.map((rule, i) => {
      rule.ranges.forEach(r => r.sheetId =  dstSheetId);
      return {addConditionalFormatRule: {index: i, rule: rule}};
    });
    Sheets.Spreadsheets.batchUpdate({requests: requests}, dstSpreadsheetId);
  }
}

参考:


推荐阅读