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
package main
import "github.com/360EntSecGroup-Skylar/excelize"

func main(t *testing.T) {
var users []*UserInfo
users = append(users, &UserInfo{
Name: "小明",
Age: 11,
Mobile: "15392262003",
})
users = append(users, &UserInfo{
Name: "小华",
Age: 12,
Mobile:"15369965887",
})
// 反射写
RefactorWrite(users)

}

type UserInfo struct {
Name string `xlsx:"A-姓名"`
Age int32 `xlsx:"B-年龄"`
Mobile string `xlsx:"C-手机号"`
}

func RefactorWrite(users []*UserInfo) {
xlsx := excelize.NewFile()
index := xlsx.NewSheet("Sheet1")

for i, t := range users {
d := reflect.TypeOf(t).Elem()
for j := 0; j < d.NumField(); j++ {
// 设置表头
if i == 0 {
column := strings.Split(d.Field(j).Tag.Get("xlsx"), "-")[0]
name := strings.Split(d.Field(j).Tag.Get("xlsx"), "-")[1]
xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+1), name)
}
// 设置内容
column := strings.Split(d.Field(j).Tag.Get("xlsx"), "-")[0]
switch d.Field(j).Type.String() {
case "string":
xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+2), reflect.ValueOf(t).Elem().Field(j).String())
case "int32":
xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+2), reflect.ValueOf(t).Elem().Field(j).Int())
case "int64":
xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+2), reflect.ValueOf(t).Elem().Field(j).Int())
case "bool":
xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+2), reflect.ValueOf(t).Elem().Field(j).Bool())
case "float32":
xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+2), reflect.ValueOf(t).Elem().Field(j).Float())
case "float64":
xlsx.SetCellValue("Sheet1", fmt.Sprintf("%s%d", column, i+2), reflect.ValueOf(t).Elem().Field(j).Float())
}
}
}

xlsx.SetActiveSheet(index)
// 保存到xlsx中
err := xlsx.SaveAs("test.xlsx")
if err != nil {
fmt.Println(err)
}
}