//package excelizeutil
package main
import (
"encoding/json"
"fmt"
"qshapi/utils/time_util"
"reflect"
"strconv"
"strings"
"time"
"github.com/bitly/go-simplejson"
"github.com/360EntSecGroup-Skylar/excelize"
)
//go get github.com/360EntSecGroup-Skylar/excelize/v2 excel操作库
//go get github.com/bitly/go-simplejson json操作库
//CellType 列名称
type CellType int
//TimeFormat 时间格式
type TimeFormat int
const (
a CellType = iota
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
aa
ab
ac
)
func (c CellType) String() string {
switch c {
case 0:
return "A"
case 1:
return "B"
case 2:
return "C"
case 3:
return "D"
case 4:
return "E"
case 5:
return "F"
case 6:
return "G"
case 7:
return "H"
case 8:
return "I"
case 9:
return "J"
case 10:
return "K"
case 11:
return "L"
case 12:
return "M"
case 13:
return "N"
case 14:
return "O"
case 15:
return "P"
case 16:
return "Q"
case 17:
return "R"
case 18:
return "S"
case 19:
return "T"
case 20:
return "U"
case 21:
return "V"
case 22:
return "W"
case 23:
return "X"
case 24:
return "Y"
case 25:
return "Z"
case 26:
return "AA"
case 27:
return "AB"
case 28:
return "AC"
default:
return "请先定义字段,请先定义"
}
}
//Excel xcel操作类
type Excel struct {
FileName string //文件名称
SheetName string //sheet名称
IsHasHead bool //是否拥有头部
CellOptions []CellOption //列对照表
}
//CellOption 列配置
type CellOption struct {
Name string //对应的字段名称
CName string //表头名称
CellType CellType //所在的行
//IsTime bool //是否为时间格式
Type string //格式(读取和时间格式写入需要设定)
TimeFormat time_util.TimeFormat //时间格式的话格式类型
}
//========================旧版使用反射处理=======================================================================
//OldWriteByEntitys 将Entity写入excel(需要转成[]interface{}),支持多个stuct
func (e Excel) OldWriteByEntitys(data []interface{}) {
f := excelize.NewFile()
index := f.NewSheet(e.SheetName)
f.SetActiveSheet(index)
e.headSave(f)
e.oldSave(f, data)
f.SaveAs(e.FileName)
}
func (e Excel) oldSave(f *excelize.File, data []interface{}) {
var headIndex = 0
if e.IsHasHead {
headIndex = 1
}
for rowIndex, d := range data {
v := reflect.ValueOf(d)
t := v.Type()
k := t.Kind()
switch k {
case reflect.Struct:
for i := 0; i < t.NumField(); i++ {
var isjb = false //是否匹配
for _, c := range e.CellOptions {
//匹配局部
if strings.ToLower(c.Name) == strings.ToLower(fmt.Sprintf("%s.%s", t.Name(), t.Field(i).Name)) { //这里先匹配对应struct的值
if c.CName == "" {
c.CName = c.Name
}
f.SetCellValue(e.SheetName, fmt.Sprintf("%s%d", c.CellType.String(), rowIndex+headIndex+1), v.Field(i).Interface())
isjb = true
break
}
}
if isjb { //如果局部匹配到了那么不需要做全局匹配了
continue
}
for _, c := range e.CellOptions {
//匹配全局
if strings.ToLower(c.Name) == strings.ToLower(t.Field(i).Name) {
if c.CName == "" {
c.CName = c.Name
}
f.SetCellValue(e.SheetName, fmt.Sprintf(&#
g使用excelize简单读写(将读写成struct)
本文介绍如何利用Go语言的excelize库来实现Excel文件的读取与写入,特别是将数据转换为struct结构,便于数据处理。
摘要由CSDN通过智能技术生成