forked from duanlizhi/gooxml
/
cellreference.go
86 lines (75 loc) · 1.92 KB
/
cellreference.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
82
83
84
85
86
// Copyright 2017 Baliance. All rights reserved.
//
// Use of this source code is governed by the terms of the Affero GNU General
// Public License version 3.0 as published by the Free Software Foundation and
// appearing in the file LICENSE included in the packaging of this file. A
// commercial license can be purchased by contacting sales@baliance.com.
package reference
import (
"errors"
"fmt"
"strconv"
"strings"
)
// CellReference is a parsed reference to a cell. Input is of the form 'A1',
// '$C$2', etc.
type CellReference struct {
RowIdx uint32
ColumnIdx uint32
Column string
AbsoluteColumn bool
AbsoluteRow bool
}
func (c CellReference) String() string {
buf := make([]byte, 0, 4)
if c.AbsoluteColumn {
buf = append(buf, '$')
}
buf = append(buf, c.Column...)
if c.AbsoluteRow {
buf = append(buf, '$')
}
buf = strconv.AppendInt(buf, int64(c.RowIdx), 10)
return string(buf)
}
// ParseCellReference parses a cell reference of the form 'A10' and splits it
// into column/row segments.
func ParseCellReference(s string) (CellReference, error) {
s = strings.TrimSpace(s)
if len(s) < 2 {
return CellReference{}, errors.New("cell reference must have at least two characters")
}
r := CellReference{}
// check for absolute column
if s[0] == '$' {
r.AbsoluteColumn = true
s = s[1:]
}
split := -1
lfor:
for i := 0; i < len(s); i++ {
switch {
case s[i] >= '0' && s[i] <= '9' || s[i] == '$':
split = i
break lfor
}
}
switch split {
case 0:
return CellReference{}, fmt.Errorf("no letter prefix in %s", s)
case -1:
return CellReference{}, fmt.Errorf("no digits in %s", s)
}
r.Column = s[0:split]
if s[split] == '$' {
r.AbsoluteRow = true
split++
}
r.ColumnIdx = ColumnToIndex(r.Column)
r64, err := strconv.ParseUint(s[split:], 10, 32)
if err != nil {
return CellReference{}, fmt.Errorf("error parsing row: %s", err)
}
r.RowIdx = uint32(r64)
return r, nil
}