正在显示
2 个修改的文件
包含
86 行增加
和
0 行删除
pkg/lib/exceltool/reader.go
0 → 100644
1 | +package exceltool | ||
2 | + | ||
3 | +import ( | ||
4 | + "io" | ||
5 | + | ||
6 | + excelize "github.com/360EntSecGroup-Skylar/excelize/v2" | ||
7 | +) | ||
8 | + | ||
9 | +// ExcelListReader 读取基础excel表格, | ||
10 | +// 指定读取的列表区域的第一行作为表头字段处理,表头字段唯一 | ||
11 | +type ExcelListReader struct { | ||
12 | + RowStart int //从第几行开始,零值做为起始 | ||
13 | + RowEnd func(index int, rowsData []string) bool //第几行结束, | ||
14 | + ColStart int //第几列开始,零值做为起始 | ||
15 | + ColEnd int //第几列结束, | ||
16 | + Sheet string //获取的表格 | ||
17 | +} | ||
18 | + | ||
19 | +func NewExcelListReader() *ExcelListReader { | ||
20 | + rowEnd := func(index int, rowsData []string) bool { | ||
21 | + var allEmpty bool = true | ||
22 | + for _, v := range rowsData { | ||
23 | + if allEmpty && len(v) > 0 { | ||
24 | + allEmpty = false | ||
25 | + break | ||
26 | + } | ||
27 | + } | ||
28 | + return allEmpty | ||
29 | + } | ||
30 | + return &ExcelListReader{ | ||
31 | + RowEnd: rowEnd, | ||
32 | + } | ||
33 | +} | ||
34 | + | ||
35 | +func (eRead ExcelListReader) OpenReader(r io.Reader) ([]map[string]string, error) { | ||
36 | + xlsxFile, err := excelize.OpenReader(r) | ||
37 | + if err != nil { | ||
38 | + return nil, err | ||
39 | + } | ||
40 | + rows, err := xlsxFile.Rows(eRead.Sheet) | ||
41 | + if err != nil { | ||
42 | + return nil, err | ||
43 | + } | ||
44 | + var ( | ||
45 | + datas = make([]map[string]string, 0) //数据列表 | ||
46 | + listHead = make(map[int]string) //map[索引数字]列表头字符串 | ||
47 | + rowIndex int = 0 | ||
48 | + ) | ||
49 | + for rows.Next() { | ||
50 | + cols, err := rows.Columns() | ||
51 | + if err != nil { | ||
52 | + return nil, err | ||
53 | + } | ||
54 | + if readEnd := eRead.RowEnd(rowIndex, cols); readEnd { | ||
55 | + break | ||
56 | + } | ||
57 | + if rowIndex < eRead.RowStart { | ||
58 | + rowIndex++ | ||
59 | + continue | ||
60 | + } | ||
61 | + listRowData := make(map[string]string) | ||
62 | + for colK, colV := range cols { | ||
63 | + if eRead.ColEnd != 0 && colK > eRead.ColEnd { | ||
64 | + break | ||
65 | + } | ||
66 | + if colK < eRead.ColStart { | ||
67 | + continue | ||
68 | + } | ||
69 | + if rowIndex == eRead.RowStart { | ||
70 | + //指定的数据列表第一行作为列表头处理 | ||
71 | + listHead[colK] = colV | ||
72 | + } | ||
73 | + if rowIndex > eRead.RowStart { | ||
74 | + //指定的数据列表第二行开始作为列表数据内容处理 | ||
75 | + headK := listHead[colK] | ||
76 | + listRowData[headK] = colV | ||
77 | + } | ||
78 | + } | ||
79 | + if rowIndex > eRead.RowStart { | ||
80 | + //指定的数据列表第二行开始作为列表数据内容处理 | ||
81 | + datas = append(datas, listRowData) | ||
82 | + } | ||
83 | + rowIndex++ | ||
84 | + } | ||
85 | + return datas, nil | ||
86 | +} |
-
请 注册 或 登录 后发表评论