如何使用脚本将Google表格中的条件格式设置规则从一个表格复制到另一个表格?

时间:2019-11-19 17:22:59

标签: google-apps-script google-sheets scripting

我正在尝试在Google表格中将条件格式设置规则从我的一个表格复制到其他表格。我知道,我可以复制并使用“特殊粘贴”来复制/粘贴它们,但是我特别想使用脚本,因为我已经设置了一个脚本来自动创建新的工作表,并且我想应用对我制作的所有工作表进行条件格式设置,因为整个电子表格都是一种日志,并且包含条件格式的特定列适用于整个工作表。这是我所拥有的:

Screenshot

2 个答案:

答案 0 :(得分:0)

使用SpreadsheetApp函数[1]和ConditionalFormatRuleBuilder类[2],可以从工作表中的规则创建新规则并将其插入新工作表中。我创建以下代码,该代码可用于从“ Merkler”工作表中获取所有规则并将其插入“ New工作表”中,前提是这些规则适用于“ F”列。

function copyFormat() {
  //Get the Spreadsheet where the Merkler and new sheet are in
  var spreadSheet = SpreadsheetApp.openById("[SPREADSHEET-ID]");
  //The source sheet with the formatting in column F is called Merkler
  var sheet = spreadSheet.getSheetByName("Merkler");
  //The target sheet is called "New Sheet"
  var newSheet = spreadSheet.getSheetByName("New sheet");

  //The formatting will be taken from column F and copy to it in new Sheet
  var range = newSheet.getRange("F2:F1000");
  var column = 6; //F is the 6th column

  //Get all Sheet rules and iterate through them
  var rules = sheet.getConditionalFormatRules();
  var newRules = [];

  for(var r = 0; r < rules.length; r++) {
    var rule = rules[r];
    //Get condition for each rule
    var booleanCondition = rule.getBooleanCondition();

    //Get the ranges to which each rule applies and iterate through
    var ranges = rule.getRanges();
    for (var i = 0; i < ranges.length; i++) {
      var ruleColumn = ranges[i].getColumn();  

      //If condition isn't null and edited column is the same as the one in the range, add rule
      if((ruleColumn == column) && (booleanCondition != null)) {
        var newRule = SpreadsheetApp.newConditionalFormatRule()
        .withCriteria(booleanCondition.getCriteriaType(), booleanCondition.getCriteriaValues())
        .setBackground(booleanCondition.getBackground())
        .setRanges([range])
        .build();
        newRules.push(newRule);
      }
    }
  }
  newSheet.setConditionalFormatRules(newRules);
}

您需要替换SpreadsheetID。

[1] https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app

[2] https://developers.google.com/apps-script/reference/spreadsheet/conditional-format-rule-builder

答案 1 :(得分:0)

    function passConditionalFormat(sourceSheetName, targetSheetName) {
      var ss = SpreadsheetApp.getActive();
      //The source of data formatting rules
      var sourceSheet = ss.getSheetByName(sourceSheetName);
      var range = sourceSheet.getRange(1, 1, sourceSheet.getMaxRows(), sourceSheet.getMaxColumns());
      //The target of data formatting rules
      var targetSheet = ss.getSheetByName(targetSheetName);
      
      range.copyFormatToRange(targetSheet, 1, sourceSheet.getMaxColumns(), 1, sourceSheet.getMaxRows());
    }

您可以使用以下选项之一:

  1. copyFormatToRange(sheet, column, columnEnd, row, rowEnd)
  2. copyFormatToRange(gridId, column, columnEnd, row, rowEnd)

请注意,此解决方案仅适用于将条件格式从一张工作表传递到同一电子表格中的另一张