github.com/richardwilkes/toolbox@v1.121.0/formats/xlsx/ref.go (about) 1 // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved. 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, version 2.0. If a copy of the MPL was not distributed with 5 // this file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 // 7 // This Source Code Form is "Incompatible With Secondary Licenses", as 8 // defined by the Mozilla Public License, version 2.0. 9 10 package xlsx 11 12 import ( 13 "strconv" 14 "strings" 15 ) 16 17 const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 18 19 // Ref holds a cell reference. 20 type Ref struct { 21 Row int 22 Col int 23 } 24 25 // ParseRef parses a string into a Ref. 26 func ParseRef(str string) Ref { 27 r := Ref{} 28 state := 0 29 for _, ch := range strings.ToUpper(str) { 30 if state == 0 { 31 if ch >= 'A' && ch <= 'Z' { 32 r.Col *= 26 33 r.Col += int(1 + ch - 'A') 34 } else { 35 state = 1 36 } 37 } 38 if state == 1 { 39 if ch >= '0' && ch <= '9' { 40 r.Row *= 10 41 r.Row += int(ch - '0') 42 } else { 43 break 44 } 45 } 46 } 47 if r.Col > 0 { 48 r.Col-- 49 } 50 if r.Row > 0 { 51 r.Row-- 52 } 53 return r 54 } 55 56 func (r Ref) String() string { 57 var a [65]byte 58 i := len(a) 59 col := r.Col 60 for col >= 26 { 61 i-- 62 q := col / 26 63 a[i] = letters[col-q*26] 64 col = q - 1 65 } 66 i-- 67 a[i] = letters[col] 68 return string(a[i:]) + strconv.Itoa(r.Row+1) 69 }