-
Notifications
You must be signed in to change notification settings - Fork 0
/
xlsx.go
138 lines (128 loc) · 2.3 KB
/
xlsx.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package xlsx_tables
import (
"archive/zip"
"encoding/xml"
"fmt"
"io"
"strconv"
)
type Reader struct {
Worksheet string
sharedStrings []string
zr *zip.ReadCloser
dec *xml.Decoder
numLine int
}
func NewReader(zr *zip.ReadCloser) *Reader {
return &Reader{
zr: zr,
Worksheet: "sheet1",
}
}
func (r *Reader) Read() ([]string, error) {
if r.sharedStrings == nil {
if err := r.loadStrings(); err != nil {
return nil, err
}
}
if r.dec == nil {
err := r.openWorksheet()
if err != nil {
return nil, err
}
}
// find the first row from wherever we are in the buffer
for {
token, err := r.dec.Token()
if err != nil {
return nil, err
}
switch se := token.(type) {
case xml.StartElement:
ele := se.Name.Local
if ele != "row" {
continue
}
var row Row
err = r.dec.DecodeElement(&row, &se)
if err != nil {
return nil, err
}
rec := []string{}
for _, v := range row.C {
if v.T == "n" {
rec = append(rec, v.V)
continue
}
i, err := strconv.Atoi(v.V)
if err != nil {
return nil, err
}
rec = append(rec, r.sharedStrings[i])
}
return rec, nil
default:
}
}
return nil, nil
}
func (r *Reader) loadStrings() (err error) {
var ssrc io.ReadCloser
defer func() {
if ssrc != nil {
ssrc.Close()
}
}()
for _, v := range r.zr.File {
if v.Name != "xl/sharedStrings.xml" {
continue
}
ssrc, err = v.Open()
if err != nil {
return err
}
break
}
dec := xml.NewDecoder(ssrc)
for {
token, err := dec.Token()
if err != nil {
if err == io.EOF {
break
}
return err
}
// Inspect the type of the token just read.
switch se := token.(type) {
case xml.StartElement:
ele := se.Name.Local
if ele != "si" {
continue
}
var si StringItem
if err := dec.DecodeElement(&si, &se); err != nil {
return err
}
r.sharedStrings = append(r.sharedStrings, si.T)
default:
}
}
return nil
}
func (r *Reader) openWorksheet() error {
for _, v := range r.zr.File {
if v.Name != fmt.Sprintf("xl/worksheets/%s.xml", r.Worksheet) {
continue
}
rc, err := v.Open()
if err != nil {
return err
}
r.dec = xml.NewDecoder(rc)
break
}
if r.dec == nil {
return fmt.Errorf("no worksheet with the name %q found", r.Worksheet)
}
return nil
}