package lib import ( "SciencesServer/utils" "errors" "fmt" "github.com/tealeg/xlsx" ) type Excel struct { File *xlsx.File name string sheet string title []string content *ExcelContent //Style } type ExcelContent struct { Kind ExcelContentKind Content []interface{} } type ExcelContentKind int const ( ExcelContentKindForStruct ExcelContentKind = iota + 1 ExcelContentKindForSlice ExcelContentKindForText ) type OptionExcel func(excel *Excel) func WithExcelName(name string) OptionExcel { return func(excel *Excel) { excel.name = name } } func WithExcelSheet(sheet string) OptionExcel { return func(excel *Excel) { excel.sheet = sheet } } func WithExcelTitle(title []string) OptionExcel { return func(excel *Excel) { excel.title = title } } func WithExcelContent(content *ExcelContent) OptionExcel { return func(excel *Excel) { excel.content = content } } func WithExcelStyle() OptionExcel { return func(excel *Excel) { } } // Export 导出 func (this *Excel) Export() error { this.File = xlsx.NewFile() sheet, _ := this.File.AddSheet(this.sheet) row := sheet.AddRow() cell := new(xlsx.Cell) style := &xlsx.Style{ //Fill: *xlsx.NewFill("solid", "EFEFDE", "EFEFDE"), Border: xlsx.Border{RightColor: "FF"}, } if this.title != nil && len(this.title) > 0 { for _, v := range this.title { cell = row.AddCell() cell.Value = v cell.SetStyle(style) } } if this.content != nil { for _, v := range this.content.Content { row = sheet.AddRow() if this.content.Kind == ExcelContentKindForStruct { row.WriteStruct(v, -1) continue } if this.content.Kind == ExcelContentKindForSlice { row.WriteSlice(v, -1) continue } for i := 0; i < len(this.title); i++ { cell = row.AddCell() // TODO:存在不同类型,请自行加判断 switch v.(type) { case []string: cell.Value = v.([]string)[i] break case []int: cell.Value = fmt.Sprintf("%v", v.([]int)[i]) break case []interface{}: cell.Value = fmt.Sprintf("%v", v.([]interface{})[i]) break default: return errors.New("未知数据类型") } } } } return nil } // Save 保存 func (this *Excel) Save(path string) error { return this.File.Save(this.name + ".xlsx") isExist, err := utils.PathExists(path) if err != nil { return err } if !isExist { if err = utils.MkdirAll(path); err != nil { return err } } fmt.Printf("%s/%s.xlsx", path, this.name) return nil //return this.Save(fmt.Sprintf("%s\%s.xlsx", path, this.name)) } func NewExcel(options ...OptionExcel) *Excel { out := new(Excel) for _, opt := range options { opt(out) } return out }