-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsheet.go
282 lines (251 loc) · 7.77 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
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
package Record2Excel
import (
"fmt"
"github.com/xuri/excelize/v2"
"reflect"
)
type Sheet interface {
AddRecord(record any) error
AddRecords(records any) error
applyHeaderStyle() error
applyContentStyle() error
}
type sheet struct {
name string
template template
file *excelize.File
length int
width int
headerLength int
colIndex map[string]int
headerStyleID int
contentStyleID int
customStyleFunc func(record any) (style *excelize.Style)
}
func newSheet(name string, model any, file *excelize.File, option ...Option) (s Sheet, err error) {
o := &options{
headerStyle: defaultHeaderStyle,
contentStyle: defaultContentStyle,
customStyleFunc: nil,
}
for _, opt := range option {
opt.apply(o)
}
sh := &sheet{
name: name,
colIndex: make(map[string]int),
file: file,
customStyleFunc: o.customStyleFunc,
}
sh.headerStyleID, err = file.NewStyle(o.headerStyle)
if err != nil {
return nil, err
}
sh.contentStyleID, err = file.NewStyle(o.contentStyle)
if err != nil {
return nil, err
}
sh.template, err = newTemplate(model)
if err != nil {
return nil, err
}
_, err = file.NewSheet(name)
if err != nil {
return nil, err
}
err = sh.buildHeader()
if err != nil {
return nil, err
}
return sh, nil
}
func (s *sheet) buildHeader() (err error) {
s.length = s.template.depth()
s.headerLength = s.length
currentColumn := 1
var mergeRanges [][2]string // 用于记录需要合并的单元格范围
// 定义一个递归函数,用于构建表头并记录合并单元格的范围
var buildHeaderForRow func(node *itemNode, row int, parentColStart *int) error
buildHeaderForRow = func(node *itemNode, row int, parentColStart *int) error {
colStart := currentColumn // 当前节点开始的列
if parentColStart != nil {
colStart = *parentColStart // 如果有父节点,从父节点的列开始
}
// 设置单元格的值
cell, _ := excelize.CoordinatesToCellName(currentColumn, row)
err := s.file.SetCellValue(s.name, cell, node.tagName)
if err != nil {
return err
}
s.colIndex[node.fieldPath] = currentColumn
s.width = max(s.width, currentColumn)
if len(node.subItems) == 0 { // 如果是叶子节点
if s.length > row { // 需要跨行合并
cellEnd, _ := excelize.CoordinatesToCellName(currentColumn, s.length)
mergeRanges = append(mergeRanges, [2]string{cell, cellEnd})
}
currentColumn++ // 移动到下一个列
} else { // 如果有子节点
for _, child := range node.subItems {
err := buildHeaderForRow(child, row+1, &colStart) // 递归构建子节点表头
if err != nil {
return err
}
}
if row == 1 { // 如果是第一层嵌套,记录合并的单元格范围
cellEnd, _ := excelize.CoordinatesToCellName(currentColumn-1, row)
if cell != cellEnd { // 避免单列合并
mergeRanges = append(mergeRanges, [2]string{cell, cellEnd})
}
}
}
return nil
}
// 从根节点开始递归
for _, item := range s.template.items.subItems {
err = buildHeaderForRow(item, 1, nil)
if err != nil {
return
}
}
// 执行合并单元格操作
for _, mergeRange := range mergeRanges {
err = s.file.MergeCell(s.name, mergeRange[0], mergeRange[1])
if err != nil {
return
}
}
return
}
type (
// Overview 总览
Overview struct {
StaffId string `excel:"学号"`
StaffName string `excel:"姓名"`
ClassNo string `excel:"班级"`
Score float64 `excel:"总分"`
Tag []string `excel:"标签"`
Awards []string `excel:"奖项"`
Achievement []OverviewAchievement `excel:"达标情况"`
Pin []OverviewPin `excel:"重要成绩项"`
}
OverviewAchievement struct {
Name string `excel:"奖项"`
Score float64 `excel:"分数"`
AchieveScore float64 `excel:"达标分数"`
Achieved bool `excel:"已达标"`
}
OverviewPin struct {
Name string `excel:"名称"`
Score float64 `excel:"分数"`
}
// Achievement 达标情况
Achievement struct {
StaffId string `excel:"学号"`
StaffName string `excel:"姓名"`
ClassNo string `excel:"班级"`
Achievement map[string]bool `excel:"达标情况"`
}
// Pin 重要成绩项
Pin struct {
StaffId string `excel:"学号"`
StaffName string `excel:"姓名"`
ClassNo string `excel:"班级"`
Pin map[string]float64 `excel:"重要成绩项"`
}
)
func (s *sheet) AddRecords(records any) error {
if reflect.TypeOf(records).Kind() != reflect.Slice {
return fmt.Errorf("records must be a slice")
}
for i := 0; i < reflect.ValueOf(records).Len(); i++ {
err := s.addRecord(reflect.ValueOf(records).Index(i))
if err != nil {
return err
}
}
//v := records.([]Achievement)
//for i := 0; i < len(v); i++ {
// err := s.AddRecord(v[i])
// if err != nil {
// return err
// }
//
//}
return nil
}
func (s *sheet) addRecord(v reflect.Value) (err error) {
var insert func(v reflect.Value, node *itemNode, currIdx int) (err error, maxIdx int)
insert = func(v reflect.Value, node *itemNode, currIdx int) (err error, maxIdx int) {
maxIdx = max(currIdx, maxIdx)
switch v.Kind() {
case reflect.Struct:
for _, child := range node.subItems {
_, childMaxIdx := insert(v.FieldByName(child.name), child, currIdx)
maxIdx = max(maxIdx, childMaxIdx)
}
case reflect.Map:
mapKeys := v.MapKeys()
//sort.Slice(mapKeys, func(i, j int) bool {
// return mapKeys[i].String() < mapKeys[j].String()
//})
for _, key := range mapKeys {
_, childMaxIdx := insert(v.MapIndex(key), node.subItems[node.key2Index[key.String()]], currIdx)
maxIdx = max(maxIdx, childMaxIdx)
}
case reflect.Slice:
for i := 0; i < v.Len(); i++ {
_, childMaxIdx := insert(v.Index(i), node, currIdx+i)
maxIdx = max(maxIdx, childMaxIdx)
}
default:
s.writeCell(node.fieldPath, currIdx, v.Interface())
}
return
}
err, newLength := insert(v, s.template.items, s.length+1)
for _, child := range s.template.items.subItems {
if v.FieldByName(child.name).Kind() != reflect.Slice &&
v.FieldByName(child.name).Kind() != reflect.Map &&
v.FieldByName(child.name).Kind() != reflect.Struct {
s.mergeCell(child.fieldPath, s.length+1, newLength)
}
}
s.length = newLength
return
}
func (s *sheet) AddRecord(record any) (err error) {
if reflect.TypeOf(record) != s.template.t {
return fmt.Errorf("record type mismatch")
}
return s.addRecord(reflect.ValueOf(record))
}
func (s *sheet) writeCell(colName string, row int, value any) error {
cell, _ := excelize.CoordinatesToCellName(s.colIndex[colName], row)
log(colName, "->", s.colIndex[colName], row, cell, value)
return s.file.SetCellValue(s.name, cell, value)
}
func (s *sheet) mergeCell(colName string, rowStart, rowEnd int) error {
startCell, _ := excelize.CoordinatesToCellName(s.colIndex[colName], rowStart)
endCell, _ := excelize.CoordinatesToCellName(s.colIndex[colName], rowEnd)
return s.file.MergeCell(s.name, startCell, endCell)
}
func (s *sheet) applyHeaderStyle() error {
topLeftCell, _ := excelize.CoordinatesToCellName(1, 1)
bottomRightCell, _ := excelize.CoordinatesToCellName(s.width, s.headerLength)
return s.applyCellStyle(topLeftCell, bottomRightCell, s.headerStyleID)
}
func (s *sheet) applyContentStyle() error {
topLeftCell, _ := excelize.CoordinatesToCellName(1, s.headerLength+1)
bottomRightCell, _ := excelize.CoordinatesToCellName(s.width, s.length)
return s.applyCellStyle(topLeftCell, bottomRightCell, s.contentStyleID)
}
func (s *sheet) applyCellStyle(topLeftCell, bottomRightCell string, styleID int) error {
return s.file.SetCellStyle(s.name, topLeftCell, bottomRightCell, styleID)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}