Last active
December 26, 2015 10:49
-
-
Save denilsonsa/7139803 to your computer and use it in GitHub Desktop.
Sets the cell background color to red-yellow-green based on its value. Used on this Google Spreadsheet: https://docs.google.com/spreadsheet/ccc?key=0AvfBqhRA8IzYdEJfNl83R2w0OGRVZUNFaWxlRFlEVGc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // cell-color-based-on-value.gs | |
| // | |
| // For more information on using the Spreadsheet API, see | |
| // https://developers.google.com/apps-script/service_spreadsheet | |
| // Returns a linear interpolation of y1,y2 based on x value between x1,x2. | |
| function linearInterp(x, x1, x2, y1, y2) { | |
| if (x <= x1) return y1; | |
| if (x >= x2) return y2; | |
| return y1 + (y2 - y1) * (x - x1) / (x2 - x1); | |
| } | |
| // http://stackoverflow.com/a/5624139/ | |
| function rgbToHex(r, g, b) { | |
| return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); | |
| } | |
| function calculateColor(value) { | |
| // Too bad Google Spreadsheets do not support HSL notation (as of 2013-10-24). | |
| // return "hsl(" + linearInterp(value, 0.00, 1.00, 120, 0) + ", 75%, 50%)"; | |
| var n = linearInterp(value, 0.00, 1.00, 0.0, 2.0); | |
| // background : -webkit-linear-gradient(right, rgb(255, 64, 64) 0%, rgb(255, 255, 64) 50%, rgb(64, 255, 64) 100%); | |
| var r = linearInterp(n, 0, 1, 64, 255); | |
| var g = linearInterp(n, 1, 2, 255, 64); | |
| var b = 64; | |
| return rgbToHex(r,g,b); | |
| } | |
| // cell is a Range object. | |
| function recolorSingleCell(cell) { | |
| var value = parseFloat(cell.getValue()); | |
| if (isNaN(value)) return; | |
| cell.setBackground(calculateColor(value)); | |
| } | |
| function recolorTheCells() { | |
| // Hard-coding the first sheet. | |
| var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; | |
| var range = sheet.getRange("G:G"); | |
| var numRows = range.getNumRows(); | |
| var numCols = range.getNumColumns(); | |
| for (var i = 0; i < numRows; i++) { | |
| for (var j = 0; j < numCols; j++) { | |
| recolorSingleCell(range.getCell(i + 1, j + 1)); | |
| } | |
| } | |
| }; | |
| function onOpen() { | |
| var sheet = SpreadsheetApp.getActiveSpreadsheet(); | |
| var entries = [{ | |
| name : "Recolor the cells!", | |
| functionName : "recolorTheCells" | |
| }]; | |
| sheet.addMenu("SCRIPT", entries); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment