-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
81 lines (72 loc) · 1.9 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package xlsx
import "fmt"
func createIdentifierFromCoords(x, y int) string {
letterPart := numericToLetters(x)
numericPart := y + 1
return fmt.Sprintf("%s%d", letterPart, numericPart)
}
func numericToLetters(colRef int) string {
parts := intToBase26(colRef)
return formatColumnName(smooshBase26Slice(parts))
}
func intToBase26(x int) (parts []int) {
// Excel column codes are pure evil - in essence they're just
// base26, but they don't represent the number 0.
b26Denominator, _ := getLargestDenominator(x, 1, 26, 0)
// This loop terminates because integer division of 1 / 26
// returns 0.
for d := b26Denominator; d > 0; d = d / 26 {
value := x / d
remainder := x % d
parts = append(parts, value)
x = remainder
}
return parts
}
func getLargestDenominator(numerator, multiple, baseDenominator, power int) (int, int) {
if numerator/multiple == 0 {
return 1, power
}
next, nextPower := getLargestDenominator(
numerator, multiple*baseDenominator, baseDenominator, power+1)
if next > multiple {
return next, nextPower
}
return multiple, power
}
func smooshBase26Slice(b26 []int) []int {
// Smoosh values together, eliminating 0s from all but the
// least significant part.
lastButOnePart := len(b26) - 2
for i := lastButOnePart; i > 0; i-- {
part := b26[i]
if part == 0 {
greaterPart := b26[i-1]
if greaterPart > 0 {
b26[i-1] = greaterPart - 1
b26[i] = 26
}
}
}
return b26
}
func formatColumnName(colID []int) string {
lastPart := len(colID) - 1
result := ""
for n, part := range colID {
if n == lastPart {
// The least significant number is in the
// range 0-25, all other numbers are 1-26,
// hence we use a different offset for the
// last part.
result += string(part + 65)
} else {
// Don't output leading 0s, as there is no
// representation of 0 in this format.
if part > 0 {
result += string(part + 64)
}
}
}
return result
}