-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexcel.go
113 lines (103 loc) · 2.33 KB
/
excel.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
package exportToExcel
import (
"fmt"
"github.com/xuri/excelize/v2"
"log"
"os"
"path/filepath"
)
type Excel struct {
fileDir string
fileName string
sheets []*Sheet
file *excelize.File
}
func NewExcel(fileDir, filename string) *Excel {
return &Excel{fileName: filename, fileDir: fileDir, file: excelize.NewFile()}
}
func NewExcelFromTemplate(templatePath string, saveDir, saveName string) (*Excel, error) {
f, err := excelize.OpenFile(templatePath)
if err != nil {
return nil, err
}
ex := &Excel{fileName: saveName, fileDir: saveDir, file: f}
for _, stName := range f.GetSheetList() {
id, err := f.GetSheetIndex(stName)
if err != nil {
return ex, err
}
ex.sheets = append(ex.sheets, &Sheet{
file: f,
sheetId: id,
titleStyle: DefaultTitleStyle,
dataStyle: DefaultDataStyle,
minColWidth: DefaultColMinWidth,
maxColWidth: DefaultColMaxWidth,
})
}
return ex, nil
}
func (e *Excel) NewSheet(sheetName string, baseDataType any, opts ...Option) *Sheet {
st := newSheet(e.file, sheetName, baseDataType, opts...)
e.sheets = append(e.sheets, st)
return st
}
func (e *Excel) GetSheetByName(sheetName string) *Sheet {
for _, v := range e.sheets {
if v.SheetName() == sheetName {
return v
}
}
return nil
}
func (e *Excel) GetSheetById(sheetId int) *Sheet {
for _, v := range e.sheets {
if v.sheetId == sheetId {
return v
}
}
return nil
}
func (e *Excel) SetFileName(fileName string) *Excel {
e.fileName = fileName
return e
}
func (e *Excel) SetFileDir(fileDir string) *Excel {
e.fileDir = fileDir
return e
}
func (e *Excel) FileName() string {
return e.fileName
}
func (e *Excel) FileDir() string {
return e.fileDir
}
func (e *Excel) File() *excelize.File {
return e.file
}
func (e *Excel) Save() (err error) {
//generate directories
if err = os.MkdirAll(e.fileDir, os.ModePerm); err != nil {
return
}
//delete Sheet 1
var hasSheet1 bool
for _, v := range e.sheets {
if v.SheetName() == "Sheet1" {
hasSheet1 = true
break
}
}
if !hasSheet1 {
_ = e.file.DeleteSheet("Sheet1")
}
//save file
path := filepath.ToSlash(filepath.Join(e.fileDir, e.fileName))
if err = e.file.SaveAs(path); err != nil {
log.Println(fmt.Sprintf("save file error :%v", err))
}
return
}
func (e *Excel) NewStyle(newStyle *excelize.Style) (int, error) {
return e.file.NewStyle(newStyle)
}