-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
372 lines (347 loc) · 9.99 KB
/
parser.go
File metadata and controls
372 lines (347 loc) · 9.99 KB
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
package dgexcel
import (
"encoding/json"
"errors"
"fmt"
"os"
"path"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"unsafe"
"github.com/xuri/excelize/v2"
)
var AllowMaxRow = 10000
type parser struct {
file *excelize.File
fieldMapping map[string]map[string]string
sheetName string
body any
val reflect.Value
uniqueMap map[int][]string
}
func newParser(body any) (*parser, error) {
p := new(parser)
p.val = reflect.ValueOf(body)
if p.val.Kind() != reflect.Ptr {
return nil, errors.New("body must be pointer struct")
}
p.body = body
p.fieldMapping = make(map[string]map[string]string)
//生成结构体与excel头映射关系
p.generateMapping(p.val, "")
return p, nil
}
func (p *parser) generateMapping(val reflect.Value, baseField string) {
switch val.Kind() {
case reflect.Struct:
case reflect.Ptr:
//当结构体指针或字段指针为空,则创建一个指针指向
if val.IsNil() {
newValue := reflect.New(val.Type().Elem())
val = reflect.NewAt(val.Type().Elem(), unsafe.Pointer(newValue.Pointer()))
}
val = val.Elem()
p.generateMapping(val, baseField)
return
default:
return
}
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
fieldName := typ.Field(i).Name
if baseField != "" {
fieldName = fmt.Sprintf("%s.%s", baseField, fieldName)
}
excel, ok := typ.Field(i).Tag.Lookup(excelTag)
if !ok {
//生成嵌套结构体的映射关系
fieldVal := val.Field(i)
p.generateMapping(fieldVal, fieldName)
continue
}
m := map[string]string{nameTag: fieldName}
m[mappingTag], _ = stringMatchExport(excel, regexp.MustCompile(`mapping\((.*?)\)`))
m[uniqueTag], _ = stringMatchExport(excel, regexp.MustCompile(`unique\((.*?)\)`))
m[dateTag], _ = stringMatchExport(excel, regexp.MustCompile(`date\((.*?)\)`))
mappingName, _ := stringMatchExport(excel, regexp.MustCompile(`name\((.*?)\)`))
p.fieldMapping[strings.TrimSpace(mappingName)] = m
}
}
func stringMatchExport(str string, reg *regexp.Regexp) (res string, err error) {
defer func() {
if panicInfo := recover(); panicInfo != nil {
err = errors.New("not match regexp")
}
}()
return reg.FindStringSubmatch(str)[1], nil
}
func (p *parser) ParseContent(file *os.File, mappingHeaderRow int, dataStartRow int) (*Result, error) {
if mappingHeaderRow-1 < 0 {
return nil, errors.New("no excel mapping header position is specified")
}
if mappingHeaderRow >= dataStartRow {
return nil, errors.New("mapping header row position cannot be greater than or equal to the beginning of the data row")
}
if err := p.readExcel(file); err != nil {
return nil, err
}
p.uniqueMap = make(map[int][]string)
p.sheetName = p.file.GetSheetName(0)
rows, err := p.file.GetRows(p.sheetName)
if err != nil {
return nil, err
}
if len(rows) < dataStartRow {
return nil, errors.New("excel file valid data behavior is empty")
}
//excel数据行数限制
if len(rows)-(dataStartRow-1) > AllowMaxRow {
return nil, errors.New("data overrun")
}
res := new(Result)
res.mappingResults = make([]any, 0)
if err := p.rows(rows, mappingHeaderRow, dataStartRow, res); err != nil {
return nil, err
}
return res, nil
}
func (p *parser) readExcel(file *os.File) (err error) {
var allowExtMap = map[string]bool{
".xlsx": true,
}
ext := path.Ext(file.Name())
//判断文件后缀
if _, ok := allowExtMap[ext]; !ok {
return fmt.Errorf("file request format error,support XLSX")
}
p.file, err = excelize.OpenReader(file)
return err
}
func (p *parser) rows(rows [][]string, mappingHeaderRow, dataStartRow int, res *Result) error {
for rowIndex := dataStartRow - 1; rowIndex < len(rows); rowIndex++ {
res.rowIndex = rowIndex
errList := make([]string, 0)
newBodyVal := reflect.New(p.val.Type().Elem())
newBodyVal.Elem().Set(p.val.Elem())
for colIndex, col := range rows[rowIndex] {
if colIndex >= len(rows[mappingHeaderRow-1]) {
continue
}
mappingHeader := rows[mappingHeaderRow-1][colIndex]
//去除列的前后空格
colVal := strings.TrimSpace(col)
mappingField, ok := p.fieldMapping[strings.TrimSpace(mappingHeader)]
if !ok {
continue
}
// 列唯一性校验
errList = append(errList, p.uniqueFormat(rows, mappingHeader, &colVal, rowIndex, colIndex, mappingField)...)
//格式化时间
errList = append(errList, p.dateFormat(mappingHeader, &colVal, mappingField)...)
//值映射转换
mappingErrList := p.mappingFormat(mappingHeader, &colVal, mappingField)
errList = append(errList, mappingErrList...)
if len(mappingErrList) != 0 {
continue
}
//参数赋值
errs, err := p.parseValue(newBodyVal, mappingField[nameTag], mappingHeader, colVal)
if err != nil {
return err
}
errList = append(errList, errs...)
}
if len(errList) != 0 {
if res.errors == nil {
res.errors = map[int][]string{rowIndex + 1: errList}
} else {
res.errors[rowIndex+1] = errList
}
}
p.body = newBodyVal.Interface()
if _, ok := res.HasError(); ok {
continue
}
res.mappingResults = append(res.mappingResults, p.body)
}
return nil
}
func (p *parser) uniqueFormat(rows [][]string, mappingHeader string, col *string, rowIndex, colIndex int, mappingField map[string]string) []string {
errList := make([]string, 0)
format, ok := mappingField[uniqueTag]
if !ok || format != "true" {
return errList
}
_, ok = p.uniqueMap[colIndex]
if !ok {
p.uniqueMap[colIndex] = make([]string, 0)
for index := 0; index < len(rows); index++ {
if len(rows[index]) <= colIndex {
p.uniqueMap[colIndex] = append(p.uniqueMap[colIndex], rows[index][0])
continue
}
p.uniqueMap[colIndex] = append(p.uniqueMap[colIndex], rows[index][colIndex])
}
}
cols := p.uniqueMap[colIndex]
for i, val := range cols {
if i != rowIndex && val != "" && val == *col {
errList = append(errList, fmt.Sprintf("%s[%s]不可重复", mappingHeader, *col))
break
}
}
return errList
}
func (p *parser) dateFormat(mappingHeader string, col *string, mappingField map[string]string) []string {
errList := make([]string, 0)
format, ok := mappingField[dateTag]
if !ok || format == "" {
return errList
}
formats := strings.SplitN(format, ",", 2)
if *col == "" || len(formats) != 2 {
return errList
}
location, err := time.ParseInLocation(formats[0], *col, time.Local)
if err != nil {
errList = append(errList, fmt.Sprintf("%s单元格格式错误", mappingHeader))
return errList
}
*col = location.Format(formats[1])
return errList
}
func (p *parser) mappingFormat(mappingHeader string, col *string, mappingField map[string]string) []string {
errList := make([]string, 0)
format, ok := mappingField[mappingTag]
if !ok || format == "" {
return errList
}
mappingValues := make(map[string]string)
formatStr := strings.Split(format, ",")
for _, format := range formatStr {
n := strings.SplitN(format, ":", 2)
if len(n) != 2 {
continue
}
mappingValues[n[0]] = n[1]
}
val, ok := mappingValues[*col]
if ok {
*col = val
return errList
}
errList = append(errList, fmt.Sprintf("%s单元格存在非法输入", mappingHeader))
return errList
}
func (p *parser) parseValue(val reflect.Value, fieldAddr, mappingHeader, col string) ([]string, error) {
errList := make([]string, 0)
fields := strings.Split(fieldAddr, ".")
if len(fields) == 0 {
return errList, nil
}
for _, field := range fields {
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
val = val.FieldByName(field)
errs, err := p.parse(val, col, mappingHeader)
if err != nil {
return errList, err
}
errList = append(errList, errs...)
}
return errList, nil
}
func (p *parser) parse(val reflect.Value, col, mappingHeader string) ([]string, error) {
errList := make([]string, 0)
var err error
switch val.Kind() {
case reflect.String:
val.SetString(col)
case reflect.Bool:
parseBool, err := strconv.ParseBool(col)
if err != nil {
errList = append(errList, fmt.Sprintf("%s单元格非法输入,参数非bool类型值", mappingHeader))
}
val.SetBool(parseBool)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
var value int64
if col != "" {
value, err = strconv.ParseInt(col, 10, 64)
if err != nil {
errList = append(errList, fmt.Sprintf("%s单元格非法输入,参数非整形数值", mappingHeader))
}
}
val.SetInt(value)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
var value uint64
if col != "" {
value, err = strconv.ParseUint(col, 10, 64)
if err != nil {
errList = append(errList, fmt.Sprintf("%s单元格非法输入,参数非整形数值", mappingHeader))
}
}
val.SetUint(value)
case reflect.Float32, reflect.Float64:
var value float64
if col != "" {
value, err = strconv.ParseFloat(col, 64)
if err != nil {
errList = append(errList, fmt.Sprintf("%s单元格非法输入,参数非浮点型数值", mappingHeader))
}
}
val.SetFloat(value)
case reflect.Struct:
return errList, nil
case reflect.Ptr:
//初始化指针
value := reflect.New(val.Type().Elem())
val.Set(value)
var errs []string
errs, err = p.parse(val.Elem(), col, mappingHeader)
if err != nil {
break
}
errList = append(errList, errs...)
default:
return errList, fmt.Errorf("excel column[%s] parseValue unsupported type[%v] mappings", mappingHeader, val.Kind().String())
}
return errList, nil
}
type Result struct {
errors map[int][]string
mappingResults []any
rowIndex int
}
func (r *Result) HasError() (map[int][]string, bool) {
return r.errors, len(r.errors) != 0
}
func (r *Result) List() []any {
return r.mappingResults
}
func (r *Result) Format(ts any) error {
marshal, err := json.Marshal(r.mappingResults)
if err != nil {
return err
}
return json.Unmarshal(marshal, &ts)
}
func (r *Result) FormatBaseTargetBuilder(buildFn func() any) ([]any, error) {
var ret []any
for _, elem := range r.mappingResults {
marshal, err := json.Marshal(elem)
if err != nil {
return nil, err
}
v := buildFn()
err = json.Unmarshal(marshal, v)
if err != nil {
return nil, err
}
ret = append(ret, v)
}
return ret, nil
}