-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathread.go
556 lines (513 loc) · 12.5 KB
/
read.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
package excel
import (
"encoding/xml"
"fmt"
"io"
"reflect"
"strings"
convert "github.com/szyhf/go-convert"
twentysix "github.com/szyhf/go-excel/internal/twenty_six"
)
// read is default implement of reader
type read struct {
connecter *connect
decoder *xml.Decoder
decoderReadCloseer io.ReadCloser
title *titleRow
schameMap map[reflect.Type]*schema
worksheetName string
}
// Move the cursor to next row's start.
func (rd *read) Next() bool {
for t, err := rd.decoder.Token(); err == nil; t, err = rd.decoder.Token() {
switch token := t.(type) {
case xml.StartElement:
switch token.Name.Local {
case _RowPrefix:
return true
}
}
}
return false
}
// Read current row into an object by its pointer
// return: the last row might be a row with not data,
//
// in rd case will return io.EOF
func (rd *read) Read(i interface{}) error {
t := reflect.TypeOf(i)
switch t.Kind() {
case reflect.Ptr:
t = t.Elem()
switch t.Kind() {
case reflect.Slice,
reflect.Array:
v := reflect.ValueOf(i)
return rd.readToSlice(t, v)
case reflect.Struct:
v := reflect.ValueOf(i)
return rd.readToStruct(t, v)
case reflect.Map:
if t.Key().Kind() != reflect.String {
return fmt.Errorf("%T should be pointer to map of string key", i)
}
v := reflect.ValueOf(i)
return rd.readToMap(t, v)
default:
return fmt.Errorf("%T should be pointer to struct or map[string]string", i)
}
default:
return fmt.Errorf("%T should be pointer to struct or map[string]string", i)
}
}
func (rd *read) InputOffset() int64 {
return rd.decoder.InputOffset()
}
func (rd *read) GetSheetSize() uint64 {
return rd.connecter.worksheetNameFileMap[rd.worksheetName].UncompressedSize64
}
func (rd *read) Close() error {
if rd.decoder != nil {
rd.decoder = nil
}
if rd.decoderReadCloseer != nil {
rd.decoderReadCloseer.Close()
rd.decoderReadCloseer = nil
}
rd.connecter = nil
rd.title = nil
rd.schameMap = nil
return nil
}
// Read all rows
func (rd *read) ReadAll(container interface{}) error {
val := reflect.ValueOf(container)
typ := reflect.Indirect(val).Type()
if val.Kind() != reflect.Ptr {
return ErrInvalidConatiner
}
if typ.Kind() != reflect.Slice {
return ErrInvalidConatiner
}
elemTyp := typ.Elem()
if elemTyp.Kind() == reflect.Ptr {
elemTyp = elemTyp.Elem()
}
var err error
switch elemTyp.Kind() {
case reflect.Struct:
elemSchema := newSchema(elemTyp)
slcVal := val.Elem()
for rd.Next() {
elmVal := sliceNextElem(slcVal)
for err = ErrEmptyRow; err == ErrEmptyRow; {
err = rd.readToValue(elemSchema, elmVal)
}
if err != nil {
// remove the last row.
slcVal.SetLen(slcVal.Len() - 1)
if err != io.EOF {
// EOF is normal.
return err
}
}
}
case reflect.Map:
slcVal := val.Elem()
for rd.Next() {
elmVal := sliceNextElem(slcVal)
for err = ErrEmptyRow; err == ErrEmptyRow; {
err = rd.readToMap(elemTyp, elmVal)
}
if err != nil {
// remove the last row.
slcVal.SetLen(slcVal.Len() - 1)
if err != io.EOF {
// EOF is normal.
return err
}
}
}
case reflect.Slice,
reflect.Array:
slcVal := val.Elem()
for rd.Next() {
elmVal := sliceNextElem(slcVal)
for err = ErrEmptyRow; err == ErrEmptyRow; {
err = rd.readToSlice(elemTyp, elmVal)
}
if err != nil {
// remove the last row.
slcVal.SetLen(slcVal.Len() - 1)
if err != io.EOF {
// EOF is normal.
return err
}
}
}
}
return nil
}
func (rd *read) GetTitles() []string {
if rd.title == nil {
return []string{}
}
// prevent unexpect edit
titles := make([]string, len(rd.title.titles))
copy(titles, rd.title.titles)
return titles
}
func (rd *read) readToStruct(t reflect.Type, v reflect.Value) error {
if len(rd.title.dstMap) != len(rd.title.titles) {
return ErrDuplicatedTitles
}
s := rd.getSchame(t)
if v.IsNil() {
v.Set(reflect.New(t))
}
v = v.Elem()
var err error
for err = ErrEmptyRow; err == ErrEmptyRow; {
err = rd.readToValue(s, v)
}
return err
}
// v should be value of map[string]string
func (rd *read) readToMap(t reflect.Type, v reflect.Value) error {
if len(rd.title.dstMap) != len(rd.title.titles) {
return ErrDuplicatedTitles
}
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
v.Set(reflect.MakeMapWithSize(t, len(rd.title.dstMap)))
var err error
for err = ErrEmptyRow; err == ErrEmptyRow; {
err = rd.readToMapValue(v)
}
if v.Len() < len(rd.title.dstMap) {
for _, keyValue := range v.MapKeys() {
title := keyValue.String()
if _, ok := rd.title.dstMap[title]; !ok {
// fill default value to column not read.
val := reflect.New(v.Type().Elem())
v.SetMapIndex(reflect.ValueOf(title), val.Elem())
}
}
}
return err
}
func (rd *read) readToSlice(t reflect.Type, v reflect.Value) (err error) {
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
// if use rd.title.dstMap as len to slice, the titles with duplcated key will be ignored.
// in slice case, ignore the duplicated key and read all cells is ok.
v.Set(reflect.MakeSlice(t, len(rd.title.titles), len(rd.title.titles)))
for err = ErrEmptyRow; err == ErrEmptyRow; {
err = rd.readToSliceValue(v)
}
return
}
func (rd *read) readToValue(s *schema, v reflect.Value) (err error) {
if len(rd.title.dstMap) != len(rd.title.titles) {
return ErrDuplicatedTitles
}
tempCell := &xlsxC{}
fieldsMap, err := rd.title.MapToFields(s)
if err != nil {
return err
}
scaned := false
defer func() {
if !scaned && err == nil {
err = ErrEmptyRow
}
}()
isV := false
for t, e := rd.decoder.Token(); e == nil; t, e = rd.decoder.Token() {
switch token := t.(type) {
case xml.StartElement:
switch token.Name.Local {
case _C:
tempCell.R = ""
tempCell.T = ""
for _, a := range token.Attr {
switch a.Name.Local {
case _R:
tempCell.R = a.Value
case _T:
tempCell.T = a.Value
}
}
case _V:
isV = true
}
case xml.EndElement:
// 避免上个节点的状态未正确处理以后延伸到下次
isV = false
if token.Name.Local == _RowPrefix {
// fill default value to column not read.
for _, notFilledFields := range fieldsMap {
for _, fieldCnf := range notFilledFields {
fieldValue := v.Field(fieldCnf.FieldIndex)
// log.Printf("Fill %s = %v with default: %s", v.Type().Field(fieldCnf.FieldIndex).Name, fieldValue.Interface(), fieldCnf.DefaultValue)
err = fieldCnf.ScanDefault(fieldValue)
if err != nil {
return err
}
}
}
// 结束当前行
return err
}
case xml.CharData:
if !isV {
// log.Println(string(token))
break
}
trimedColumnName := strings.TrimRight(tempCell.R, _AllNumber)
columnIndex := twentysix.ToDecimalism(trimedColumnName)
fields, ok := fieldsMap[columnIndex]
if !ok {
// Not an error, just ignore rd column.
break
}
var valStr string
if tempCell.T == _S {
// get string from shared
valStr = rd.connecter.getSharedString(convert.MustInt(string(token)))
} else {
valStr = string(token)
}
// println("Key:", trimedColumnName, "Val:", valStr)
scaned = true
isV = false
for _, fieldCnf := range fields {
fieldValue := v.Field(fieldCnf.FieldIndex)
err = fieldCnf.scan(valStr, fieldValue)
if err != nil && len(valStr) > 0 {
return err
}
}
if err == nil {
delete(fieldsMap, columnIndex)
}
}
}
if err != nil {
return err
}
return io.EOF
}
func (rd *read) readToMapValue(v reflect.Value) (err error) {
if len(rd.title.dstMap) != len(rd.title.titles) {
return ErrDuplicatedTitles
}
tempCell := &xlsxC{}
scaned := false
defer func() {
if !scaned && err == nil {
err = ErrEmptyRow
}
}()
isV := false
for t, e := rd.decoder.Token(); e == nil; t, e = rd.decoder.Token() {
switch token := t.(type) {
case xml.StartElement:
switch token.Name.Local {
case _C:
tempCell.R = ""
tempCell.T = ""
for _, a := range token.Attr {
switch a.Name.Local {
case _R:
tempCell.R = a.Value
case _T:
tempCell.T = a.Value
}
}
case _V:
isV = true
}
case xml.EndElement:
// 避免上个节点的状态未正确处理以后延伸到下次
isV = false
if token.Name.Local == _RowPrefix {
// end of current row
return err
}
case xml.CharData:
if !isV {
break
}
trimedColumnName := strings.TrimRight(tempCell.R, _AllNumber)
var valStr string
if tempCell.T == _S {
// get string from shared
valStr = rd.connecter.getSharedString(convert.MustInt(string(token)))
} else {
valStr = string(token)
}
val := reflect.New(v.Type().Elem())
_ = scan(valStr, val.Interface())
columnIndex := twentysix.ToDecimalism(trimedColumnName)
title := rd.title.srcMap[columnIndex]
v.SetMapIndex(reflect.ValueOf(title), val.Elem())
// log.Println("Key:", trimedColumnName, "Val:", valStr)
scaned = true
isV = false
}
}
if err != nil {
return err
}
return io.EOF
}
func (rd *read) readToSliceValue(v reflect.Value) (err error) {
tempCell := &xlsxC{}
scaned := false
defer func() {
if !scaned && err == nil {
err = ErrEmptyRow
}
}()
isV := false
for t, e := rd.decoder.Token(); e == nil; t, e = rd.decoder.Token() {
switch token := t.(type) {
case xml.StartElement:
switch token.Name.Local {
case _C:
tempCell.R = ""
tempCell.T = ""
for _, a := range token.Attr {
switch a.Name.Local {
case _R:
tempCell.R = a.Value
case _T:
tempCell.T = a.Value
}
}
case _V:
isV = true
}
case xml.EndElement:
// 避免上个节点的状态未正确处理以后延伸到下次
isV = false
if token.Name.Local == _RowPrefix {
// end of current row
return err
}
case xml.CharData:
if !isV {
break
}
trimedColumnName := strings.TrimRight(tempCell.R, _AllNumber)
var valStr string
if tempCell.T == _S {
// get string from shared
valStr = rd.connecter.getSharedString(convert.MustInt(string(token)))
} else {
valStr = string(token)
}
columnIndex := twentysix.ToDecimalism(trimedColumnName)
if columnIndex < v.Len() {
val := v.Index(columnIndex)
if val.Type().Kind() == reflect.Ptr {
val.Set(reflect.New(val.Type().Elem()))
_ = scan(valStr, val.Interface())
} else if val.CanAddr() {
_ = scan(valStr, val.Addr().Interface())
} else {
return fmt.Errorf("unexpect type of %T, is not ptr and can't addr", v.Interface())
}
// } else {
// log.Printf("columnIndex(%d) < v.Len(%d)", columnIndex, v.Len())
}
// log.Println("Key:", trimedColumnName, "Val:", valStr)
scaned = true
isV = false
}
}
if err != nil {
return err
}
return io.EOF
}
func (rd *read) getSchame(t reflect.Type) *schema {
s, ok := rd.schameMap[t]
if !ok {
s = newSchema(t)
rd.schameMap[t] = s
}
return s
}
func newReader(cn *connect, workSheetFileReader io.ReadCloser, titleRowIndex, skip int, sheetName string) (Reader, error) {
rd, err := newBaseReaderByWorkSheetFile(cn, workSheetFileReader, sheetName)
if err != nil {
return nil, err
}
// consider title row
var i = 0
// <= because Next() have to put the pointer to the Index row.
for ; i <= titleRowIndex; i++ {
if !rd.Next() {
return rd, nil
}
}
rd.title, err = newRowAsMap(rd)
// consider skip
// Next() will called before Read() so just skip cursor to the row before first data row.
// log.Println("Start for skip")
for i = 0; i < skip; i++ {
if !rd.Next() {
return rd, nil
}
}
rd.schameMap = make(map[reflect.Type]*schema)
return rd, err
}
// Make a base reader to sheet
func newBaseReaderByWorkSheetFile(cn *connect, rc io.ReadCloser, sheetName string) (*read, error) {
decoder := xml.NewDecoder(rc)
// step into root [xml.StartElement] token
func(decoder *xml.Decoder) {
for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
// [xml.ProcInst]
// [xml.CharData]
// [xml.StartElement]
switch t.(type) {
case xml.StartElement:
return
}
}
}(decoder)
err := func(decoder *xml.Decoder) error {
// use func block to break to 'for' range
for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
// log.Printf("%+v\n\n", t)
switch token := t.(type) {
case xml.StartElement:
switch token.Name.Local {
case _SheetData:
return nil
default:
if err := decoder.Skip(); err != nil {
return err
}
}
}
}
return nil
}(decoder)
if err != nil {
return nil, err
}
rd := &read{
connecter: cn,
decoder: decoder,
decoderReadCloseer: rc,
worksheetName: sheetName,
}
return rd, nil
}