Created
January 5, 2012 11:31
-
-
Save dexterous/1564892 to your computer and use it in GitHub Desktop.
Groovy function to generate Excel style column names from column a column index
This file contains 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
@groovy.transform.Field | |
final def alphabet = ('A'..'Z') | |
def column(n) { | |
n = n as Integer | |
return (n < alphabet.size()) ? | |
alphabet[n] : //first 'digit' is 1-based | |
column((n / 26) - 1) + column(n % 26) //0-based from now on, so reduce 1 | |
} | |
assert column( 0) == 'A' | |
assert column( 1) == 'B' | |
assert column( 9) == 'J' | |
assert column( 25) == 'Z' | |
assert column( 26) == 'AA' | |
assert column( 27) == 'AB' | |
assert column( 28) == 'AC' | |
assert column( 35) == 'AJ' | |
assert column( 51) == 'AZ' | |
assert column( 52) == 'BA' | |
assert column(702) == 'AAA' | |
def ABBA = 0 | |
[1, 2, 2, 0].reverse().eachWithIndex { e, i -> ABBA += e * 26**i } | |
assert column(ABBA) == 'ABBA' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment