Last active
June 8, 2018 01:48
-
-
Save brito/1b3751a40cc88b90828b77dd5b9e7a49 to your computer and use it in GitHub Desktop.
An autoformat script for Google Sheets: set font, freeze header + column, rotate headers for numeric columns
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
var FONT = { | |
FAMILY: 'Inconsolata', | |
SIZE: 10 | |
}; | |
function onOpen() { | |
var menuTitle = 'Autoformat', | |
caption = [FONT.FAMILY, FONT.SIZE].join(' '), | |
functionName = 'autoformat' | |
SpreadsheetApp.getUi().createMenu(menuTitle).addItem(caption, functionName).addToUi() } | |
function autoformat(){ | |
var sheet = SpreadsheetApp.getActiveSheet(), | |
range = sheet.getDataRange(), | |
values = range.getValues(), | |
numRows = values.length, | |
numCols = values[0].length; | |
// sensible defaults | |
range | |
.setFontFamily(FONT.FAMILY) | |
.setVerticalAlignment('middle') | |
.setFontSize(FONT.SIZE); | |
// auto align | |
var isThin; | |
values.slice(0, 2).reverse().forEach(function(row, i){ | |
if (!i) | |
isThin = row.map(function(value){ | |
return 'boolean' == typeof value || | |
'number' == typeof value || | |
!isNaN((''+value).split('\n').join('')) }); | |
else isThin.forEach(function(thin, j){ | |
sheet.getRange(1, j+1) | |
.setTextRotation(thin ? 90 : 0) | |
.setHorizontalAlignment('center') | |
.setVerticalAlignment(thin ? 'bottom' : 'middle') | |
.setWrap(false); | |
sheet.getRange(2, j+1, numRows) | |
.setHorizontalAlignment(thin ? 'center': 'left') | |
.setWrap(true); | |
}); | |
}); | |
// headers | |
sheet.setFrozenRows(1); | |
sheet.setFrozenColumns(1); | |
sheet.getRange(1, 1, 1, numCols) | |
.setFontWeight('bold'); | |
//sheet.autoResizeColumns(1, numCols); | |
var maxLengths = _transpose(values) | |
.map(function(col){ | |
return col | |
.slice(1) | |
.map(function(a){ return (''+a).length || 1 }) | |
.reduce(function(a,b){ return Math.max(a, b) }); | |
}) | |
.map(function(ems){ return Math.sqrt(ems) * (FONT.SIZE * (.5+Math.sqrt(5)/2)) }) | |
.forEach(function(width_px, i){ | |
console.log(width_px, i+1) | |
// if (width_px < 10) | |
// sheet.autoResizeColumns(i + 1, 1); | |
// else | |
sheet.setColumnWidth(i + 1, width_px); | |
}); | |
} | |
// | |
function _transpose(a){ | |
return a[0].map(function (_, c) { return a.map(function (r) { return r[c]; }); }); } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment