You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
1.8 KiB
96 lines
1.8 KiB
package excel
|
|
|
|
import (
|
|
"fmt"
|
|
"reflect"
|
|
)
|
|
|
|
type styleFunc func(*Sheet) int
|
|
type authFunc func(*Sheet, string) bool
|
|
|
|
type Sheet struct {
|
|
Name string
|
|
Rows []interface{}
|
|
title []TagAttr
|
|
styleMap map[string]styleFunc
|
|
authMap map[string]authFunc
|
|
File *excel
|
|
SkipCol int
|
|
}
|
|
|
|
func CreateSheet(name string, rows []interface{}) *Sheet {
|
|
s := new(Sheet)
|
|
s.Name = name
|
|
s.Rows = rows
|
|
s.styleMap = make(map[string]styleFunc)
|
|
s.authMap = make(map[string]authFunc)
|
|
return s
|
|
}
|
|
|
|
func (o *Sheet) RegisterStyle(name string, f styleFunc) {
|
|
o.styleMap[name] = f
|
|
}
|
|
|
|
func (o *Sheet) RegisterAuth(name string, f authFunc) {
|
|
o.authMap[name] = f
|
|
}
|
|
|
|
func (o *Sheet) create() error {
|
|
o.File.NewSheet(o.Name)
|
|
o.File.DeleteSheet("Sheet1")
|
|
if err := o.initTitle(); err != nil {
|
|
return err
|
|
}
|
|
if err := o.initBody(); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (o *Sheet) initTitle() error {
|
|
err, title := o.reflectTitle()
|
|
o.title = title
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
skipCol := o.SkipCol + 1
|
|
|
|
_ = o.File.SetColWidth(o.Name, genFlag(skipCol), genFlag(len(title)+skipCol), float64(12))
|
|
counter := 0
|
|
for _, t := range title {
|
|
axis := fmt.Sprintf("%s1", genFlag(counter+skipCol))
|
|
if t.Auth != "" {
|
|
if value, ok := o.authMap[t.Auth]; ok {
|
|
if value(o, t.Name) {
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
|
|
_ = o.File.SetCellValue(o.Name, axis, t.Name)
|
|
if t.Style != "" {
|
|
if value, ok := o.styleMap[t.Style]; ok {
|
|
_ = o.File.SetCellStyle(o.Name, axis, axis, value(o))
|
|
}
|
|
}
|
|
counter += 1
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (o *Sheet) initBody() error {
|
|
for i, u := range o.Rows {
|
|
|
|
t := reflect.TypeOf(u)
|
|
v := reflect.ValueOf(u)
|
|
|
|
if t.Kind() == reflect.Ptr {
|
|
t = reflect.TypeOf(u).Elem()
|
|
v = reflect.ValueOf(u).Elem()
|
|
}
|
|
reflectRow(t, v, o.Name, 0, o.SkipCol, i, o)
|
|
}
|
|
return nil
|
|
}
|