Google Sheets - 根据文本值自动设置单元格的背景颜色

Google Sheets - Set background color of cell based on text value automatically

是否可以根据单元格的文本值自动更改单元格的背景?这些将适用于任意数量的值,而不仅仅是预定义的。这个想法是根据文本值生成 'hash',然后根据该哈希值随机选择一种颜色。什么颜色都无所谓,只要不同的值有不同的颜色就很容易区分。

例如,假设单元格具有以下值:

它们都有不同的背景颜色,因为它们包含不同的文本值。实际的背景颜色没有区别。理想情况下,如果背景颜色为 'dark',文本颜色将为白色,如果背景颜色为 'light',文本颜色将为黑色。这样您就可以随时阅读文本。

这是我对问题的近似:

const sS = SpreadsheetApp.getActiveSheet()
const docProperties = PropertiesService.getDocumentProperties()

function colorTheDifference() {
  const { getRow, getNumRows, getColumn, getNumColumns } = sS.getDataRange()
  const [rw, nRw, cl, nCl] = [getRow(), getNumRows(), getColumn(), getNumColumns()]
  const values = sS.getRange(rw, cl, nRw, nCl).getValues()
  for (let i = rw; i <= nRw; i++) {
    for (let j = cl; j <= nCl; j++) {
      const word = values[i - 1][j - 1]
      if(!word) continue
      sS.getRange(i, j).setBackground(saveColor(word))
    }
  }
}

function saveColor(word) {
  if (docProperties.getKeys().includes(word)) {
    return docProperties.getProperty(word)
  } else {
    const randomColorPick = randomColor()
    docProperties.setProperty(word, randomColorPick)
    return randomColorPick
  }
}

// 
const randomColor = () => '#' + (Math.random() * 0xFFFFFF << 0).toString(16).padStart(6, '0');

function onOpen() {
  // colorTheDifference()
  SpreadsheetApp
    .getUi()
    .createMenu('Custom Menu')
    .addItem('Color It', 'colorTheDifference')
    .addToUi()
}

该脚本分析所有单元格值,将它们在 DocumentProperties 内与随机颜色相关联(当样本量增加时这可能会导致某种问题,应实施控制以检查此类颜色是否存在) 然后将该颜色添加到单元格。

如您所见,我将它添加到菜单中的一个函数中,但它可以在 onOpen so that it is parsed directly when opening the document, or associate it to onEdit 中调用(我认为这太过分了)。

这不是解决问题的最佳方法,应该转向 batchUpdate

有趣的问题。

我写了一些东西,它使用 onEdit() 函数根据特定列中的值 format/highlight/color 给定的 row/range。

我会在完成完整记录后在下面发表评论,但希望很容易弄清楚如何调整 userParams 对象。

Give it a try here on this sample sheet。 B 列中的值将根据“图例”

的 background/font 颜色/文本样式突出显示该行