This repository has been archived by the owner on Oct 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
excel.go
97 lines (76 loc) · 1.76 KB
/
excel.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
87
88
89
90
91
92
93
94
95
96
97
package xpbonds
import (
"io"
"regexp"
"strings"
"github.com/360EntSecGroup-Skylar/excelize"
"github.com/pkg/errors"
)
const invalidCell = "#VALUE!"
var reFocusedSheet = regexp.MustCompile("(?i)^focused [a-z]+$")
func parseExcel(excel io.Reader, dateFormat DateFormat, focusedOnly bool) (Bonds, error) {
xlsx, err := excelize.OpenReader(excel)
if err != nil {
return nil, errors.Wrap(err, "failed to open excel")
}
sheets := xlsx.GetSheetMap()
var bonds Bonds
for _, sheet := range sheets {
if focusedOnly && !reFocusedSheet.MatchString(sheet) {
continue
}
rows := xlsx.GetRows(sheet)
sheetBonds, err := parseSheet(rows, dateFormat)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse sheet '%s'", sheet)
}
bonds = append(bonds, sheetBonds...)
}
return bonds, nil
}
func parseSheet(rows [][]string, dateFormat DateFormat) (Bonds, error) {
normalized := make(Bonds, 0, len(rows))
for _, r := range rows {
row := row(r)
if row.ignore() {
continue
}
bond, err := parseBond(row, dateFormat)
if err != nil {
return nil, errors.Wrap(err, "failed to parse bond")
}
normalized = append(normalized, bond)
}
return normalized, nil
}
type row []string
func (r row) ignore() bool {
if len(r) != 16 {
return true
}
cell := strings.TrimSpace(r[0])
if cell == "" || cell == "Name" {
return true
}
// detect and remove lines without value
empty := true
for _, cell := range r[1:] {
if cell != "" {
empty = false
break
}
}
return empty
}
func (r row) get(i int) string {
if i < 0 || i >= len(r) || r[i] == invalidCell {
return ""
}
v := r[i]
v = strings.ToLower(v)
v = strings.TrimSpace(v)
if strings.Contains(v, "n.a.") || strings.Contains(v, "n/a") || v == "-" {
return ""
}
return r[i]
}