-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsheet.go
137 lines (109 loc) · 2.6 KB
/
sheet.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
package excelizex
import (
"reflect"
"strconv"
"github.com/xuri/excelize/v2"
)
type Sheet struct {
// 表名
name string
// 格式化后的数据
// 顶栏提示
notice string
// 表头
header []string
// 数据
data *[][]any
// 下拉选项 暂时只支持单列
pd *pullDown
// 列和style分配语句的映射存储
// v:Col -> k:style raw string list;col 为 -1时为notice/
styleRef map[int][]string
// 写入到第几行,主要用于标记生成excel中的表时,需要续写的位置
writeRow int
}
func NewSheet(sheetName string, a any) *Sheet {
if sheetName == "" {
panic("Sheet name cannot be empty")
}
s := newMetas(a).sheet(sheetName)
return s
}
func (s *Sheet) Excel() *File {
if s.name == "" {
panic("need a Sheet name at least")
}
return New().AddFormattedSheets(s)
}
func getRowData(row any) (list []any) {
typ := reflect.TypeOf(row)
val := reflect.ValueOf(row)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
val = val.Elem()
}
switch typ.Kind() {
case reflect.Struct:
for j := 0; j < typ.NumField(); j++ {
field := typ.Field(j)
hasTag := field.Tag.Get("excel")
if hasTag != "" && hasTag != "notice" {
list = append(list, val.Field(j).Interface())
}
}
case reflect.Slice:
for i := 0; i < val.Len(); i++ {
list = append(list, val.Index(i).Interface())
}
default:
panic("support struct only")
}
return
}
// findHeaderColumnNames 寻找表头名称或者是列名称
func (s *Sheet) findHeaderColumnNames(headName string) (columnNames []string, err error) {
var columnName string
for i, h := range s.header {
if h == headName {
if columnName, err = excelize.ColumnNumberToName(i + 1); err != nil {
return
}
columnNames = append(columnNames, columnName)
}
}
return
}
// SetOptions 设置下拉的选项
func (s *Sheet) SetOptions(headOrColName string, options any) *Sheet {
names, err := s.findHeaderColumnNames(headOrColName)
if err != nil {
panic(err)
}
pd := newPullDown()
for _, name := range names {
pd.addOptions(name, options)
}
if s.pd == nil {
s.pd = pd
} else {
s.pd.merge(pd)
}
return s
}
// nextWriteRow 会获取目前该写入的行
// 每次调用该方法表示行数增长 返回 A1 A2... 等名称
func (s *Sheet) nextWriteRow(num ...int) string {
if len(num) > 0 {
s.writeRow += num[0]
} else {
s.writeRow++
}
return "A" + strconv.FormatInt(int64(s.writeRow), 10)
}
func (s *Sheet) getWriteRow() string {
return "A" + strconv.FormatInt(int64(s.writeRow), 10)
}
func (s *Sheet) resetWriteRow() string {
s.writeRow = 1
return "A" + strconv.FormatInt(int64(s.writeRow), 10)
}