我想為不同列中具有相同值的單元格著色。有沒有辦法在應用程式腳本中做到這一點?

uj5u.com熱心網友回復:
請定義distinctColors自己并確保您的資料有足夠的顏色。
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);
}
uj5u.com熱心網友回復:
- 創造一個
Set獨特的價值 - 創建一個隨機顏色的值
Map - 使用以下方法將范圍值映射到顏色
Array.map - 將映射的顏色陣列設定回
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))));
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/392668.html
上一篇:GoogleApps腳本范圍保護鎖定標簽顏色和標簽重命名
下一篇:使用復選框顯示/隱藏列
