繁体   English   中英

应用脚本中不同列(不同行)中具有相同值的单元格颜色

[英]Color cells with same value in different columns (different rows) in app script

我想为不同列中具有相同值的单元格着色 有没有办法在应用脚本中做到这一点?

在此处输入图像描述

请自行定义distinctColors并确保有足够的 colors 用于您的数据。

function test() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const range = sheet.getDataRange();
  const values = range.getValues();
  const rows = values.length;
  const cols = values[0].length;
  const colors = new Array(rows).fill().map(row => new Array(cols));
  
  const distinctColors = ['red', 'blue', 'green', 'yellow'];
  const distinctValues = {};
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      const value = values[i][j];
      if (!distinctValues[value]) { distinctValues[value] = []; }
      distinctValues[value].push({i: i, j:j});
    }
  }
  
  let k = 0;
  for (const array of Object.values(distinctValues)) {
    if (array.length == 1) { continue; }
    for (const v of array) {
      colors[v.i][v.j] = distinctColors[k];
    }
    k++;
  }
  range.setBackgrounds(colors);
}
  • 创建一Set唯一值
  • 为随机颜色创建一个值Map
  • Map 使用Array.map的颜色范围值
  • 将映射的 colors 数组设置回range
const colorSameValues = () => {
  const sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1'),
    range = sheet.getDataRange(),
    values = range.getValues(),
    set /* unique set */ = new Set(values.flat()),
    map /* values to color map */ = new Map(),
    hex /* random hex color code */ = () =>
      '#' +
      Array(3)
        .fill()
        .map(() =>
          Math.floor(Math.random() * 256)
            .toString(16)
            .padStart(2, '0')
        )
        .join('');
  set.delete('');
  set.forEach((val) => map.set(val, hex()));
  range.setBackgrounds(values.map((row) => row.map(map.get.bind(map))));
};

暂无
暂无

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

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