-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild_xlsx.go
95 lines (87 loc) · 2.1 KB
/
build_xlsx.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
package main
import (
"log"
"os"
"path"
"path/filepath"
"strings"
"github.com/xuri/excelize/v2"
)
type Field struct {
Index int
Name string
Type string
}
type StructInfo struct {
SheetName string
Name string
Fields []Field
}
type TemplateData struct {
StructInfos []StructInfo
FileName string
PakageName string
}
func Output(filePath string) {
// NOTICE 这里path.Base不支持windows路径 先转成linux路径形式
fileNameWithSuffix := path.Base(filepath.ToSlash(filePath))
fileType := path.Ext(fileNameWithSuffix)
fileName := strings.TrimSuffix(fileNameWithSuffix, fileType)
f, err := excelize.OpenFile(filePath)
if err != nil {
log.Println("xlsx文件读取异常: ", err)
return
}
defer f.Close()
sheets := f.GetSheetList()
var structInfos []StructInfo = make([]StructInfo, 0)
for _, sheet := range sheets {
structInfo := StructInfo{
SheetName: sheet,
Name: strings.Title(sheet),
Fields: []Field{},
}
rows, err := f.GetRows(sheet)
if err != nil {
log.Println("读取rows异常: ", err)
return
}
for i, row := range rows {
if i == 0 {
for idx, cell := range row {
field := Field{
Index: idx,
Name: strings.Title(cell),
}
structInfo.Fields = append(structInfo.Fields, field)
}
} else if i == 1 {
for j, cell := range row {
if j < len(structInfo.Fields) {
field := &structInfo.Fields[j]
field.Type = cell
}
}
}
}
structInfos = append(structInfos, structInfo)
}
outdir := GetExcelOutputDir()
outpath := filepath.Join(outdir, fileName+".cfg.go")
// 创建导出目录(不存在的话)
err = os.MkdirAll(outdir, os.ModePerm)
if err != nil {
log.Fatalln("创建目录失败: ", err)
}
outputFile, err := os.Create(outpath)
if err != nil {
log.Println("创建编译文件异常: ", err)
return
}
defer outputFile.Close()
GenerateTemplate(outputFile, TemplateData{
StructInfos: structInfos,
FileName: fileName,
PakageName: buildConfig.Xlsx.Package,
})
}