Skip to content

Instantly share code, notes, and snippets.

@takapiro99
Created July 9, 2022 16:05
Show Gist options
  • Save takapiro99/65acbb2258b7a8a6c4f53ceb4ef6e969 to your computer and use it in GitHub Desktop.
Save takapiro99/65acbb2258b7a8a6c4f53ceb4ef6e969 to your computer and use it in GitHub Desktop.
スプシで hex のテキストのみあるセルの背景色をその色にする
const hexRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
// https://stackoverflow.com/a/11868398/13126073
function getContrastYIQ(hexcolor) {
if (hexcolor.length === 4) {
hexcolor = `#${hexcolor[1]}${hexcolor[1]}${hexcolor[2]}${hexcolor[2]}${hexcolor[3]}${hexcolor[3]}`
}
hexcolor = hexcolor.replace("#", "");
var r = parseInt(hexcolor.substr(0, 2), 16);
var g = parseInt(hexcolor.substr(2, 2), 16);
var b = parseInt(hexcolor.substr(4, 2), 16);
var yiq = (r * 299 + g * 587 + b * 114) / 1000;
return yiq >= 128 ? "black" : "white";
}
// セル内に HEX のカラーコードのみあった場合に背景色を着色する
// セルが空だったらスタイルをリセットする
// NOTE: 複数ある場合は反応しない
// NOTE: hex しか反応しない
function colorizeHexColorCodes() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheets()[0];
// 値がある範囲にある値の多次元配列を取得
const values = sheet.getDataRange().getValues();
const cellThatHaveHexColorCode = values
.flatMap((row, rowIndex) => row.map((col, colIndex) => ({ pos: [rowIndex, colIndex], val: col })))
.filter(cell => !!cell.val && cell.val.toString().match(hexRegex) && [4, 7].includes(cell.val.length))
cellThatHaveHexColorCode.forEach((cell) => {
const range = sheet.getRange(cell.pos[0] + 1, cell.pos[1] + 1);
range.setBackground(cell.val);
range.setFontColor(getContrastYIQ(cell.val))
range.setBorder(true, true, true, true, false, false, 'grey', SpreadsheetApp.BorderStyle.SOLID)
})
// カラーコードが無いセルのスタイルをリセットする
const cellThatNotHaveHexColorCode = values
.flatMap((row, rowIndex) => row.map((col, colIndex) => ({ pos: [rowIndex, colIndex], val: col })))
.filter((cell) => !cell.val)
cellThatNotHaveHexColorCode.forEach((cell) => {
const range = sheet.getRange(cell.pos[0] + 1, cell.pos[1] + 1);
range.setBackground("white");
range.setFontColor("black")
range.setBorder(false, false, false, false, false, false)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment