/
cell_ref.go
50 lines (39 loc) · 1.17 KB
/
cell_ref.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
// Copyright (c) 2017 Andrey Gayvoronsky <plandem@gmail.com>
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package primitives
import (
"fmt"
"github.com/plandem/ooxml"
"math"
"strconv"
"strings"
)
//CellRef is a type to encode XSD ST_CellRef, an A1 style reference to the location of this cell
type CellRef string
//ToIndexes returns 0-based indexes of reference
func (cr CellRef) ToIndexes() (int, int) {
colPart := strings.Map(ooxml.GetLettersFn, string(cr))
rowPart := strings.Map(ooxml.GetNumbersFn, string(cr))
var colIndex, rowIndex int
for i, j := len(colPart)-1, 0; i >= 0; i, j = i-1, j+1 {
colIndex += (int(colPart[i]) - int('A') + 1) * int(math.Pow(26, float64(j)))
}
rowIndex, _ = strconv.Atoi(rowPart)
rowIndex--
colIndex--
return colIndex, rowIndex
}
//CellRefFromIndexes returns a CellRef for 0-based indexes
func CellRefFromIndexes(colIndex, rowIndex int) CellRef {
if colIndex < 0 || rowIndex < 0 {
return ""
}
var colName string
i := colIndex + 1
for i > 0 {
colName = string((i-1)%26+65) + colName
i = (i - 1) / 26
}
return CellRef(fmt.Sprintf("%s%d", colName, rowIndex+1))
}