Compare commits

..

No commits in common. "master" and "master_v2" have entirely different histories.

563 changed files with 1684 additions and 161917 deletions

View File

@ -7,7 +7,6 @@ import (
. "code.hoteas.com/golang/hotime/db"
. "code.hoteas.com/golang/hotime/log"
"database/sql"
"fmt"
"github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
@ -23,6 +22,7 @@ type Application struct {
MakeCodeRouter map[string]*code.MakeCode
MethodRouter
Router
ContextBase
Error
Log *logrus.Logger
WebConnectLog *logrus.Logger
@ -68,20 +68,18 @@ func (that *Application) Run(router Router) {
if that.Router == nil {
that.Router = Router{}
}
for k, _ := range router {
v := router[k]
for k, v := range router {
if that.Router[k] == nil {
that.Router[k] = v
}
//直达接口层复用
for k1, _ := range v {
v1 := v[k1]
for k1, v1 := range v {
if that.Router[k][k1] == nil {
that.Router[k][k1] = v1
}
for k2, _ := range v1 {
v2 := v1[k2]
for k2, v2 := range v1 {
that.Router[k][k1][k2] = v2
}
}
@ -239,8 +237,10 @@ func (that *Application) SetConfig(configPath ...string) {
}
if that.Error.GetError() != nil {
fmt.Println(that.Error.GetError().Error())
that.Log = GetLog(that.Config.GetString("logFile"), true)
that.Error = Error{Logger: that.Log}
if that.Config.Get("webConnectLogShow") == nil || that.Config.GetBool("webConnectLogShow") {
that.WebConnectLog = GetLog(that.Config.GetString("webConnectLogFile"), false)
}
//文件如果损坏则不写入配置防止配置文件数据丢失
@ -267,12 +267,6 @@ func (that *Application) SetConfig(configPath ...string) {
}
that.Log = GetLog(that.Config.GetString("logFile"), true)
that.Error = Error{Logger: that.Log}
if that.Config.Get("webConnectLogShow") == nil || that.Config.GetBool("webConnectLogShow") {
that.WebConnectLog = GetLog(that.Config.GetString("webConnectLogFile"), false)
}
}
// SetConnectListener 连接判断,返回false继续传输至控制层true则停止传输
@ -285,7 +279,7 @@ func (that *Application) SetConnectListener(lis func(that *Context) (isFinished
//
//}
// 序列化链接
//序列化链接
func (that *Application) urlSer(url string) (string, []string) {
q := strings.Index(url, "?")
if q == -1 {
@ -331,9 +325,6 @@ func (that *Application) handler(w http.ResponseWriter, req *http.Request) {
if len(token) == 32 {
sessionId = token
//没有token则查阅session
if cookie == nil || cookie.Value != sessionId {
needSetCookie = sessionId
}
} else if err == nil && cookie.Value != "" {
sessionId = cookie.Value
//session也没有则判断是否创建cookie
@ -362,18 +353,14 @@ func (that *Application) handler(w http.ResponseWriter, req *http.Request) {
defer func() {
//是否展示日志
if that.WebConnectLog != nil {
ipStr := Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))
//负载均衡优化
ipStr := ""
if req.Header.Get("X-Forwarded-For") != "" {
ipStr = req.Header.Get("X-Forwarded-For")
} else if req.Header.Get("X-Real-IP") != "" {
ipStr = req.Header.Get("X-Real-IP")
}
//负载均衡优化
if ipStr == "" {
//RemoteAddr := that.Req.RemoteAddr
ipStr = Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))
if ipStr == "127.0.0.1" {
if req.Header.Get("X-Forwarded-For") != "" {
ipStr = req.Header.Get("X-Forwarded-For")
} else if req.Header.Get("X-Real-IP") != "" {
ipStr = req.Header.Get("X-Real-IP")
}
}
that.WebConnectLog.Infoln(ipStr, context.Req.Method,
@ -383,17 +370,15 @@ func (that *Application) handler(w http.ResponseWriter, req *http.Request) {
}()
//访问拦截true继续false暂停
connectListenerLen := len(that.connectListener) - 1
connectListenerLen := len(that.connectListener)
for i := connectListenerLen - 1; i >= 0; i-- {
if that.connectListener[i](&context) {
for true {
if connectListenerLen < 0 {
break
}
if that.connectListener[connectListenerLen](&context) {
context.View()
return
}
connectListenerLen--
}
//接口服务
@ -467,7 +452,6 @@ func (that *Application) crossDomain(context *Context, sessionId string) {
if context.Config.GetString("crossDomain") == "" {
if sessionId != "" {
http.SetCookie(context.Resp, &http.Cookie{Name: that.Config.GetString("sessionName"), Value: sessionId, Path: "/"})
//context.Resp.Header().Set("Set-Cookie", that.Config.GetString("sessionName")+"="+sessionId+"; Path=/; SameSite=None; Secure")
}
return
@ -497,7 +481,7 @@ func (that *Application) crossDomain(context *Context, sessionId string) {
header.Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE")
header.Set("Access-Control-Allow-Credentials", "true")
header.Set("Access-Control-Expose-Headers", "*")
header.Set("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Access-Token,Authorization,Cookie,Set-Cookie")
header.Set("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Access-Token")
if sessionId != "" {
//跨域允许需要设置cookie的允许跨域https才有效果
@ -512,8 +496,7 @@ func (that *Application) crossDomain(context *Context, sessionId string) {
if (origin != "" && strings.Contains(origin, remoteHost)) || strings.Contains(refer, remoteHost) {
if sessionId != "" {
//http.SetCookie(context.Resp, &http.Cookie{Name: that.Config.GetString("sessionName"), Value: sessionId, Path: "/"})
context.Resp.Header().Set("Set-Cookie", that.Config.GetString("sessionName")+"="+sessionId+"; Path=/; SameSite=None; Secure")
http.SetCookie(context.Resp, &http.Cookie{Name: that.Config.GetString("sessionName"), Value: sessionId, Path: "/"})
}
return
@ -544,7 +527,7 @@ func (that *Application) crossDomain(context *Context, sessionId string) {
header.Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE")
header.Set("Access-Control-Allow-Credentials", "true")
header.Set("Access-Control-Expose-Headers", "*")
header.Set("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Access-Token,Authorization,Cookie,Set-Cookie")
header.Set("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Access-Token")
if sessionId != "" {
//跨域允许需要设置cookie的允许跨域https才有效果
@ -553,7 +536,7 @@ func (that *Application) crossDomain(context *Context, sessionId string) {
}
// Init 初始化application
//Init 初始化application
func Init(config string) *Application {
appIns := Application{}
//手动模式,
@ -579,9 +562,14 @@ func Init(config string) *Application {
codeMake["name"] = codeMake.GetString("table")
}
appIns.MakeCodeRouter[codeMake.GetString("name")] = &code.MakeCode{Error: appIns.Error}
appIns.MakeCodeRouter[codeMake.GetString("name")].Db2JSON(&appIns.Db, codeMake)
if appIns.Config.GetInt("mode") > 0 {
appIns.MakeCodeRouter[codeMake.GetString("name")] = &code.MakeCode{Error: appIns.Error}
appIns.MakeCodeRouter[codeMake.GetString("name")].Db2JSON(&appIns.Db, codeMake)
} else {
appIns.MakeCodeRouter[codeMake.GetString("name")] = &code.MakeCode{Error: appIns.Error}
appIns.MakeCodeRouter[codeMake.GetString("name")].Db2JSON(nil, codeMake)
}
//接入动态代码层
if appIns.Router == nil {
appIns.Router = Router{}
@ -589,30 +577,20 @@ func Init(config string) *Application {
//appIns.Router[codeMake.GetString("name")] = TptProject
appIns.Router[codeMake.GetString("name")] = Proj{}
for k2, _ := range TptProject {
if appIns.Router[codeMake.GetString("name")][k2] == nil {
appIns.Router[codeMake.GetString("name")][k2] = Ctr{}
}
for k3, _ := range TptProject[k2] {
v3 := TptProject[k2][k3]
appIns.Router[codeMake.GetString("name")][k2] = Ctr{}
for k3, v3 := range TptProject[k2] {
appIns.Router[codeMake.GetString("name")][k2][k3] = v3
}
}
for k1, _ := range appIns.MakeCodeRouter[codeMake.GetString("name")].TableColumns {
if appIns.Router[codeMake.GetString("name")][k1] == nil {
appIns.Router[codeMake.GetString("name")][k1] = Ctr{}
}
for k2, _ := range appIns.Router[codeMake.GetString("name")]["hotimeCommon"] {
//golang毛病
v2 := appIns.Router[codeMake.GetString("name")]["hotimeCommon"][k2]
appIns.Router[codeMake.GetString("name")][k1][k2] = v2
}
appIns.Router[codeMake.GetString("name")][k1] = appIns.Router[codeMake.GetString("name")]["hotimeCommon"]
}
setMakeCodeListener(codeMake.GetString("name"), &appIns)
go func() {
setMakeCodeLintener(codeMake.GetString("name"), &appIns)
}()
}
@ -682,7 +660,7 @@ func SetSqliteDB(appIns *Application, config Map) {
})
}
func setMakeCodeListener(name string, appIns *Application) {
func setMakeCodeLintener(name string, appIns *Application) {
appIns.SetConnectListener(func(context *Context) (isFinished bool) {
codeIns := appIns.MakeCodeRouter[name]
@ -702,9 +680,7 @@ func setMakeCodeListener(name string, appIns *Application) {
if context.RouterString[1] == "hotime" && context.RouterString[2] == "config" {
return isFinished
}
if context.RouterString[1] == "hotime" && context.RouterString[2] == "wallpaper" {
return isFinished
}
if context.Session(codeIns.FileConfig.GetString("table")+"_id").Data == nil {
context.Display(2, "你还没有登录")
return true
@ -747,16 +723,6 @@ func setMakeCodeListener(name string, appIns *Application) {
context.Req.Method == "POST" {
return isFinished
}
//分析
if len(context.RouterString) == 3 && context.RouterString[2] == "analyse" &&
context.Req.Method == "GET" {
if context.Router[context.RouterString[0]][context.RouterString[1]]["analyse"] == nil {
return isFinished
}
context.Router[context.RouterString[0]][context.RouterString[1]]["analyse"](context)
}
//查询单条
if len(context.RouterString) == 3 &&
context.Req.Method == "GET" {
@ -788,7 +754,7 @@ func setMakeCodeListener(name string, appIns *Application) {
context.Router[context.RouterString[0]][context.RouterString[1]]["remove"](context)
}
//context.View()
context.View()
return true
})
}

199
cache/cache_memory.go vendored
View File

@ -7,13 +7,14 @@ import (
"time"
)
// CacheMemory 基于 sync.Map 的缓存实现
type CacheMemory struct {
TimeOut int64
DbSet bool
SessionSet bool
Map
*Error
cache sync.Map // 替代传统的 Map
ContextBase
mutex *sync.RWMutex
}
func (that *CacheMemory) GetError() *Error {
@ -25,91 +26,133 @@ func (that *CacheMemory) GetError() *Error {
func (that *CacheMemory) SetError(err *Error) {
that.Error = err
}
func (c *CacheMemory) get(key string) (res *Obj) {
res = &Obj{
Error: *c.Error,
}
value, ok := c.cache.Load(key)
if !ok {
return res // 缓存不存在
//获取Cache键只能为string类型
func (that *CacheMemory) get(key string) interface{} {
that.Error.SetError(nil)
if that.Map == nil {
that.Map = Map{}
}
data := value.(cacheData)
// 检查是否过期
if data.time < time.Now().Unix() {
c.cache.Delete(key) // 删除过期缓存
return res
if that.Map[key] == nil {
return nil
}
res.Data = data.data
return res
}
func (c *CacheMemory) set(key string, value interface{}, expireAt int64) {
data := cacheData{
data: value,
time: expireAt,
}
c.cache.Store(key, data)
}
func (c *CacheMemory) delete(key string) {
if strings.Contains(key, "*") {
// 通配符删除
prefix := strings.TrimSuffix(key, "*")
c.cache.Range(func(k, v interface{}) bool {
if strings.HasPrefix(k.(string), prefix) {
c.cache.Delete(k)
}
return true
})
} else {
// 精确删除
c.cache.Delete(key)
}
}
func (c *CacheMemory) refreshMap() {
go func() {
now := time.Now().Unix()
c.cache.Range(func(key, value interface{}) bool {
data := value.(cacheData)
if data.time <= now {
c.cache.Delete(key) // 删除过期缓存
}
return true
})
}()
}
func (c *CacheMemory) Cache(key string, data ...interface{}) *Obj {
now := time.Now().Unix()
// 随机触发刷新
if x := RandX(1, 100000); x > 99950 {
c.refreshMap()
}
if len(data) == 0 {
// 读操作
return c.get(key)
}
if len(data) == 1 && data[0] == nil {
// 删除操作
c.delete(key)
data := that.Map.Get(key, that.Error).(cacheData)
if that.Error.GetError() != nil {
return nil
}
// 写操作
expireAt := now + c.TimeOut
if len(data) == 2 {
if customExpire, ok := data[1].(int64); ok {
if customExpire > now {
expireAt = customExpire
} else {
expireAt = now + customExpire
if data.time < time.Now().Unix() {
delete(that.Map, key)
return nil
}
return data.data
}
func (that *CacheMemory) refreshMap() {
go func() {
that.mutex.Lock()
defer that.mutex.Unlock()
for key, v := range that.Map {
data := v.(cacheData)
if data.time <= time.Now().Unix() {
delete(that.Map, key)
}
}
}()
}
//key value ,时间为时间戳
func (that *CacheMemory) set(key string, value interface{}, time int64) {
that.Error.SetError(nil)
var data cacheData
if that.Map == nil {
that.Map = Map{}
}
c.set(key, data[0], expireAt)
return nil
dd := that.Map[key]
if dd == nil {
data = cacheData{}
} else {
data = dd.(cacheData)
}
data.time = time
data.data = value
that.Map.Put(key, data)
}
func (that *CacheMemory) delete(key string) {
del := strings.Index(key, "*")
//如果通配删除
if del != -1 {
key = Substr(key, 0, del)
for k, _ := range that.Map {
if strings.Index(k, key) != -1 {
delete(that.Map, k)
}
}
} else {
delete(that.Map, key)
}
}
func (that *CacheMemory) Cache(key string, data ...interface{}) *Obj {
x := RandX(1, 100000)
if x > 99950 {
that.refreshMap()
}
if that.mutex == nil {
that.mutex = &sync.RWMutex{}
}
reData := &Obj{Data: nil}
if len(data) == 0 {
that.mutex.RLock()
reData.Data = that.get(key)
that.mutex.RUnlock()
return reData
}
tim := time.Now().Unix()
if len(data) == 1 && data[0] == nil {
that.mutex.Lock()
that.delete(key)
that.mutex.Unlock()
return reData
}
if len(data) == 1 {
tim = tim + that.TimeOut
}
if len(data) == 2 {
that.Error.SetError(nil)
tempt := ObjToInt64(data[1], that.Error)
if tempt > tim {
tim = tempt
} else if that.Error.GetError() == nil {
tim = tim + tempt
}
}
that.mutex.Lock()
that.set(key, data[0], tim)
that.mutex.Unlock()
return reData
}

1157
code.go

File diff suppressed because it is too large Load Diff

View File

@ -8,15 +8,6 @@ var Config = Map{
"name": "HoTimeDashBoard",
//"id": "2f92h3herh23rh2y8",
"label": "HoTime管理平台",
"stop": Slice{"role", "org"}, //不更新的,同时不允许修改用户自身对应的表数据
"labelConfig": Map{
"show": "开启",
"add": "添加",
"delete": "删除",
"edit": "编辑",
"info": "查看详情",
"download": "下载清单",
},
"menus": []Map{
//{"label": "平台首页", "name": "HelloWorld", "icon": "el-icon-s-home"},
//{"label": "测试表格", "table": "table", "icon": "el-icon-suitcase"},
@ -59,130 +50,62 @@ var ColumnDataType = map[string]string{
}
type ColumnShow struct {
Name string //名称
List bool //列表权限
Edit bool //新增和编辑权限
Info bool //详情权限
Must bool //字段全匹配
Name string
List bool
Edit bool
Info bool
Must bool
Type string //空字符串表示
Strict bool //name严格匹配必须是这个词才行
}
var RuleConfig = []Map{
{"name": "idcard", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "id", "add": false, "list": true, "edit": false, "info": true, "must": false, "strict": true, "type": ""},
{"name": "sn", "add": false, "list": true, "edit": false, "info": true, "must": false, "strict": false, "type": ""},
{"name": "parent_ids", "add": false, "list": false, "edit": false, "info": false, "must": false, "strict": true, "type": "index"},
{"name": "index", "add": false, "list": false, "edit": false, "info": false, "must": false, "strict": true, "type": "index"},
var ColumnNameType = []ColumnShow{
//通用
{"idcard", false, true, true, false, "", false},
{"id", true, false, true, false, "", true},
{"sn", true, false, true, false, "", false},
{"parent_ids", false, false, false, false, "index", true},
{"parent_id", true, true, true, false, "", true},
{"amount", true, true, true, false, "money", true},
{"info", false, true, true, false, "textArea", false},
//"sn"{true,true,true,""},
{"status", true, true, true, false, "select", false},
{"state", true, true, true, false, "select", false},
{"sex", true, true, true, false, "select", false},
{"delete", false, false, false, false, "", false},
{"name": "parent_id", "add": true, "list": true, "edit": true, "info": true, "must": false, "true": false, "type": ""},
{"lat", false, true, true, false, "", false},
{"lng", false, true, true, false, "", false},
{"latitude", false, true, true, false, "", false},
{"longitude", false, true, true, false, "", false},
{"name": "amount", "add": true, "list": true, "edit": true, "info": true, "must": false, "strict": true, "type": "money"},
{"index", false, false, false, false, "index", false},
{"name": "info", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": "textArea"},
{"password", false, true, false, false, "password", false},
{"pwd", false, true, false, false, "password", false},
{"name": "status", "add": true, "list": true, "edit": true, "info": true, "must": false, "strict": false, "type": "select"},
{"name": "state", "add": true, "list": true, "edit": true, "info": true, "must": false, "strict": false, "type": "select"},
{"name": "sex", "add": true, "list": true, "edit": true, "info": true, "must": false, "strict": false, "type": "select"},
{"name": "delete", "add": false, "list": false, "edit": false, "info": false, "must": false, "strict": false, "type": ""},
{"name": "lat", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "lng", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "latitude", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "longitude", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "password", "add": true, "list": false, "edit": true, "info": false, "must": false, "strict": false, "type": "password"},
{"name": "pwd", "add": true, "list": false, "edit": true, "info": false, "must": false, "strict": false, "type": "password"},
{"name": "version", "add": false, "list": false, "edit": false, "info": false, "must": false, "strict": false, "type": ""},
{"name": "seq", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "sort", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "note", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "description", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "abstract", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "content", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": "textArea"},
{"name": "address", "add": true, "list": true, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "full_name", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "create_time", "add": false, "list": false, "edit": false, "info": true, "must": false, "strict": true, "type": "time"},
{"name": "modify_time", "add": false, "list": true, "edit": false, "info": true, "must": false, "strict": true, "type": "time"},
{"name": "image", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": "image"},
{"name": "img", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": "image"},
{"name": "avatar", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": "image"},
{"name": "icon", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": "image"},
{"name": "file", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": "file"},
{"name": "age", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "email", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": ""},
{"name": "time", "add": true, "list": true, "edit": true, "info": true, "must": false, "strict": false, "type": "time"},
{"name": "level", "add": false, "list": false, "edit": false, "info": true, "must": false, "strict": false, "type": ""},
{"name": "rule", "add": true, "list": true, "edit": true, "info": true, "must": false, "strict": false, "type": "form"},
{"name": "auth", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": "auth"},
{"name": "table", "add": false, "list": true, "edit": false, "info": true, "must": false, "strict": false, "type": "table"},
{"name": "table_id", "add": false, "list": true, "edit": false, "info": true, "must": false, "strict": false, "type": "table_id"},
{"version", false, false, false, false, "", false},
{"seq", false, true, true, false, "", false},
{"sort", false, true, true, false, "", false},
{"note", false, true, true, false, "", false},
{"description", false, true, true, false, "", false},
{"abstract", false, true, true, false, "", false},
{"content", false, true, true, false, "textArea", false},
{"address", true, true, true, false, "", false},
{"full_name", false, true, true, false, "", false},
{"create_time", false, false, true, false, "time", true},
{"modify_time", true, false, true, false, "time", true},
{"image", false, true, true, false, "image", false},
{"img", false, true, true, false, "image", false},
{"icon", false, true, true, false, "image", false},
{"avatar", false, true, true, false, "image", false},
{"file", false, true, true, false, "file", false},
{"age", false, true, true, false, "", false},
{"email", false, true, true, false, "", false},
{"time", true, true, true, false, "time", false},
{"level", false, false, true, false, "", false},
{"rule", true, true, true, false, "form", false},
{"auth", false, true, true, false, "auth", true},
{"table", true, false, true, false, "table", false},
{"table_id", true, false, true, false, "table_id", false},
}
//var ColumnNameType = []ColumnShow{
// //通用
// {"idcard", false, true, true, false, "", false},
// {"id", true, false, true, false, "", true},
// {"sn", true, false, true, false, "", false},
// {"parent_ids", false, false, false, false, "index", true},
// {"parent_id", true, true, true, false, "", true},
// {"amount", true, true, true, false, "money", true},
// {"info", false, true, true, false, "textArea", false},
// //"sn"{true,true,true,""},
// {"status", true, true, true, false, "select", false},
// {"state", true, true, true, false, "select", false},
// {"sex", true, true, true, false, "select", false},
// {"delete", false, false, false, false, "", false},
//
// {"lat", false, true, true, false, "", false},
// {"lng", false, true, true, false, "", false},
// {"latitude", false, true, true, false, "", false},
// {"longitude", false, true, true, false, "", false},
//
// {"index", false, false, false, false, "index", false},
//
// {"password", false, true, false, false, "password", false},
// {"pwd", false, true, false, false, "password", false},
//
// {"version", false, false, false, false, "", false},
// {"seq", false, true, true, false, "", false},
// {"sort", false, true, true, false, "", false},
// {"note", false, true, true, false, "", false},
// {"description", false, true, true, false, "", false},
// {"abstract", false, true, true, false, "", false},
// {"content", false, true, true, false, "textArea", false},
// {"address", true, true, true, false, "", false},
// {"full_name", false, true, true, false, "", false},
// {"create_time", false, false, true, false, "time", true},
// {"modify_time", true, false, true, false, "time", true},
// {"image", false, true, true, false, "image", false},
// {"img", false, true, true, false, "image", false},
// {"icon", false, true, true, false, "image", false},
// {"avatar", false, true, true, false, "image", false},
// {"file", false, true, true, false, "file", false},
// {"age", false, true, true, false, "", false},
// {"email", false, true, true, false, "", false},
// {"time", true, true, true, false, "time", false},
// {"level", false, false, true, false, "", false},
// {"rule", true, true, true, false, "form", false},
// {"auth", false, true, true, false, "auth", true},
// {"table", true, false, true, false, "table", false},
// {"table_id", true, false, true, false, "table_id", false},
//}

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,6 @@ import (
"encoding/hex"
"math"
"strings"
"time"
)
//安全锁
@ -37,42 +36,6 @@ func StrFirstToUpper(str string) string {
return strings.ToUpper(first) + other
}
// 时间转字符串第二个参数支持1-5对应显示年月日时分秒
func Time2Str(t time.Time, qu ...interface{}) string {
if t.Unix() < 0 {
return ""
}
tp := 5
if len(qu) != 0 {
tp = (qu[0]).(int)
}
switch tp {
case 1:
return t.Format("2006-01")
case 2:
return t.Format("2006-01-02")
case 3:
return t.Format("2006-01-02 15")
case 4:
return t.Format("2006-01-02 15:04")
case 5:
return t.Format("2006-01-02 15:04:05")
case 12:
return t.Format("01-02")
case 14:
return t.Format("01-02 15:04")
case 15:
return t.Format("01-02 15:04:05")
case 34:
return t.Format("15:04")
case 35:
return t.Format("15:04:05")
}
return t.Format("2006-01-02 15:04:05")
}
// StrLd 相似度计算 ld compares two strings and returns the levenshtein distance between them.
func StrLd(s, t string, ignoreCase bool) int {
if ignoreCase {

View File

@ -8,10 +8,10 @@ import (
"time"
)
// hotime的常用map
//hotime的常用map
type Map map[string]interface{}
// 获取string
//获取string
func (that Map) GetString(key string, err ...*Error) string {
if len(err) != 0 {
@ -26,7 +26,7 @@ func (that *Map) Pointer() *Map {
return that
}
// 增加接口
//增加接口
func (that Map) Put(key string, value interface{}) {
//if that==nil{
// that=Map{}
@ -34,13 +34,13 @@ func (that Map) Put(key string, value interface{}) {
that[key] = value
}
// 删除接口
//删除接口
func (that Map) Delete(key string) {
delete(that, key)
}
// 获取Int
//获取Int
func (that Map) GetInt(key string, err ...*Error) int {
v := ObjToInt((that)[key], err...)
@ -48,35 +48,35 @@ func (that Map) GetInt(key string, err ...*Error) int {
}
// 获取Int
//获取Int
func (that Map) GetInt64(key string, err ...*Error) int64 {
v := ObjToInt64((that)[key], err...)
return v
}
// 获取向上取整Int64
//获取向上取整Int64
func (that Map) GetCeilInt64(key string, err ...*Error) int64 {
v := ObjToCeilInt64((that)[key], err...)
return v
}
// 获取向上取整Int
//获取向上取整Int
func (that Map) GetCeilInt(key string, err ...*Error) int {
v := ObjToCeilInt((that)[key], err...)
return v
}
// 获取向上取整float64
//获取向上取整float64
func (that Map) GetCeilFloat64(key string, err ...*Error) float64 {
v := ObjToCeilFloat64((that)[key], err...)
return v
}
// 获取Float64
//获取Float64
func (that Map) GetFloat64(key string, err ...*Error) float64 {
v := ObjToFloat64((that)[key], err...)
@ -149,7 +149,7 @@ func (that Map) Get(key string, err ...*Error) interface{} {
return nil
}
// 请传递指针过来
//请传递指针过来
func (that Map) ToStruct(stct interface{}) {
data := reflect.ValueOf(stct).Elem()

View File

@ -2,7 +2,7 @@ package common
import "time"
// 对象封装方便取用
//对象封装方便取用
type Obj struct {
Data interface{}
Error
@ -82,7 +82,7 @@ func (that *Obj) ToObj() interface{} {
return that.Data
}
// 获取向上取整Int64
//获取向上取整Int64
func (that *Obj) ToCeilInt64(err ...*Error) int64 {
if len(err) != 0 {
that.Error = *err[0]
@ -92,7 +92,7 @@ func (that *Obj) ToCeilInt64(err ...*Error) int64 {
}
// 获取向上取整Int
//获取向上取整Int
func (that *Obj) ToCeilInt(err ...*Error) int {
if len(err) != 0 {
that.Error = *err[0]

View File

@ -5,11 +5,10 @@ import (
"errors"
"math"
"strconv"
"strings"
"time"
)
// 仅限于hotime.Slice
//仅限于hotime.Slice
func ObjToMap(obj interface{}, e ...*Error) Map {
var err error
var v Map
@ -60,7 +59,7 @@ func ObjToMapArray(obj interface{}, e ...*Error) []Map {
return res
}
// 仅限于hotime.Slice
//仅限于hotime.Slice
func ObjToSlice(obj interface{}, e ...*Error) Slice {
var err error
var v Slice
@ -104,22 +103,7 @@ func ObjToTime(obj interface{}, e ...*Error) *time.Time {
//字符串类型只支持标准mysql datetime格式
if tInt == 0 {
tStr := ObjToStr(obj)
timeNewStr := ""
timeNewStrs := strings.Split(tStr, "-")
for _, v := range timeNewStrs {
if v == "" {
continue
}
if len(v) == 1 {
v = "0" + v
}
if timeNewStr == "" {
timeNewStr = v
continue
}
timeNewStr = timeNewStr + "-" + v
}
tStr = timeNewStr
if len(tStr) > 18 {
t, e := time.Parse("2006-01-02 15:04:05", tStr)
if e == nil {
@ -151,23 +135,19 @@ func ObjToTime(obj interface{}, e ...*Error) *time.Time {
//纳秒级别
if len(ObjToStr(tInt)) > 16 {
//t := time.Time{}.Add(time.Nanosecond * time.Duration(tInt))
t := time.UnixMicro(tInt / 1000)
t := time.Time{}.Add(time.Nanosecond * time.Duration(tInt))
return &t
//微秒级别
} else if len(ObjToStr(tInt)) > 13 {
//t := time.Time{}.Add(time.Microsecond * time.Duration(tInt))
t := time.UnixMicro(tInt)
t := time.Time{}.Add(time.Microsecond * time.Duration(tInt))
return &t
//毫秒级别
} else if len(ObjToStr(tInt)) > 10 {
//t := time.Time{}.Add(time.Millisecond * time.Duration(tInt))
t := time.UnixMilli(tInt)
t := time.Time{}.Add(time.Millisecond * time.Duration(tInt))
return &t
//秒级别
} else if len(ObjToStr(tInt)) > 9 {
//t := time.Time{}.Add(time.Second * time.Duration(tInt))
t := time.Unix(tInt, 0)
t := time.Time{}.Add(time.Second * time.Duration(tInt))
return &t
} else if len(ObjToStr(tInt)) > 3 {
t, e := time.Parse("2006", ObjToStr(tInt))
@ -234,21 +214,21 @@ func ObjToFloat64(obj interface{}, e ...*Error) float64 {
return v
}
// 向上取整
//向上取整
func ObjToCeilInt64(obj interface{}, e ...*Error) int64 {
f := ObjToCeilFloat64(obj, e...)
return ObjToInt64(math.Ceil(f))
}
// 向上取整
//向上取整
func ObjToCeilFloat64(obj interface{}, e ...*Error) float64 {
f := ObjToFloat64(obj, e...)
return math.Ceil(f)
}
// 向上取整
//向上取整
func ObjToCeilInt(obj interface{}, e ...*Error) int {
f := ObjToCeilFloat64(obj, e...)
return ObjToInt(f)
@ -360,7 +340,7 @@ func ObjToStr(obj interface{}) string {
return str
}
// 转换为Map
//转换为Map
func StrToMap(string string) Map {
data := Map{}
data.JsonToMap(string)
@ -368,7 +348,7 @@ func StrToMap(string string) Map {
return data
}
// 转换为Slice
//转换为Slice
func StrToSlice(string string) Slice {
data := ObjToSlice(string)
@ -376,7 +356,7 @@ func StrToSlice(string string) Slice {
return data
}
// 字符串数组: a1,a2,a3转["a1","a2","a3"]
//字符串数组: a1,a2,a3转["a1","a2","a3"]
func StrArrayToJsonStr(a string) string {
if len(a) > 2 {
@ -394,7 +374,7 @@ func StrArrayToJsonStr(a string) string {
return a
}
// 字符串数组: a1,a2,a3转["a1","a2","a3"]
//字符串数组: a1,a2,a3转["a1","a2","a3"]
func JsonStrToStrArray(a string) string {
//a = strings.Replace(a, `"`, "", -1)
if len(a) != 0 {
@ -404,7 +384,7 @@ func JsonStrToStrArray(a string) string {
return "," + a + ","
}
// 字符串转int
//字符串转int
func StrToInt(s string) (int, error) {
i, err := strconv.Atoi(s)
return i, err

View File

@ -1,11 +1,11 @@
package hotime
import (
. "code.hoteas.com/golang/hotime/cache"
. "code.hoteas.com/golang/hotime/common"
. "code.hoteas.com/golang/hotime/db"
"encoding/json"
"net/http"
"strings"
"time"
)
@ -19,7 +19,7 @@ type Context struct {
Db *HoTimeDB
RespData Map
RespFunc func()
//CacheIns
CacheIns
SessionIns
DataSize int
HandlerStr string //复写请求url
@ -75,19 +75,6 @@ func (that *Context) View() {
if that.Session("user_id").Data != nil {
that.Log["user_id"] = that.Session("user_id").ToCeilInt()
}
//负载均衡优化
ipStr := ""
if that.Req.Header.Get("X-Forwarded-For") != "" {
ipStr = that.Req.Header.Get("X-Forwarded-For")
} else if that.Req.Header.Get("X-Real-IP") != "" {
ipStr = that.Req.Header.Get("X-Real-IP")
}
//负载均衡优化
if ipStr == "" {
//RemoteAddr := that.Req.RemoteAddr
ipStr = Substr(that.Req.RemoteAddr, 0, strings.Index(that.Req.RemoteAddr, ":"))
}
that.Log["ip"] = ipStr
that.Db.Insert("logs", that.Log)
}

View File

@ -1,431 +0,0 @@
# HoTimeDB API 快速参考
## ⚠️ 重要语法说明
**条件查询语法规则:**
- 单个条件可以直接写在Map中
- 多个条件:必须使用`AND``OR`包装
- 特殊条件:`ORDER``GROUP``LIMIT`与条件同级
```go
// ✅ 正确:单个条件
Map{"status": 1}
// ✅ 正确多个条件用AND包装
Map{
"AND": Map{
"status": 1,
"age[>]": 18,
},
}
// ✅ 正确:条件 + 特殊参数
Map{
"AND": Map{
"status": 1,
"age[>]": 18,
},
"ORDER": "id DESC",
"LIMIT": 10,
}
// ❌ 错误多个条件不用AND包装
Map{
"status": 1,
"age[>]": 18, // 这样写不支持!
}
```
## 基本方法
### 数据库连接
```go
db.SetConnect(func() (master, slave *sql.DB) { ... })
db.InitDb()
```
### 链式查询构建器
```go
// 创建查询构建器
builder := db.Table("tablename")
// 设置条件
builder.Where(key, value)
builder.And(key, value) 或 builder.And(map)
builder.Or(key, value) 或 builder.Or(map)
// JOIN操作
builder.LeftJoin(table, condition)
builder.RightJoin(table, condition)
builder.InnerJoin(table, condition)
builder.FullJoin(table, condition)
builder.Join(map) // 通用JOIN
// 排序和分组
builder.Order(fields...)
builder.Group(fields...)
builder.Limit(args...)
// 分页
builder.Page(page, pageSize)
// 执行查询
builder.Select(fields...) // 返回 []Map
builder.Get(fields...) // 返回 Map
builder.Count() // 返回 int
builder.Update(data) // 返回 int64
builder.Delete() // 返回 int64
```
## CRUD 操作
### 查询 (Select)
```go
// 基本查询
data := db.Select("table")
data := db.Select("table", "field1,field2")
data := db.Select("table", []string{"field1", "field2"})
data := db.Select("table", "*", whereMap)
// 带JOIN查询
data := db.Select("table", joinSlice, "fields", whereMap)
```
### 获取单条 (Get)
```go
// 自动添加 LIMIT 1
row := db.Get("table", "fields", whereMap)
```
### 插入 (Insert)
```go
id := db.Insert("table", dataMap)
// 返回新插入记录的ID
```
### 更新 (Update)
```go
affected := db.Update("table", dataMap, whereMap)
// 返回受影响的行数
```
### 删除 (Delete)
```go
affected := db.Delete("table", whereMap)
// 返回删除的行数
```
## 聚合函数
### 计数
```go
count := db.Count("table")
count := db.Count("table", whereMap)
count := db.Count("table", joinSlice, whereMap)
```
### 求和
```go
sum := db.Sum("table", "column")
sum := db.Sum("table", "column", whereMap)
sum := db.Sum("table", "column", joinSlice, whereMap)
```
## 分页查询
```go
// 设置分页
db.Page(page, pageSize)
// 分页查询
data := db.Page(page, pageSize).PageSelect("table", "fields", whereMap)
```
## 条件语法参考
### 比较操作符
| 写法 | SQL | 说明 |
|------|-----|------|
| `"field": value` | `field = ?` | 等于 |
| `"field[!]": value` | `field != ?` | 不等于 |
| `"field[>]": value` | `field > ?` | 大于 |
| `"field[>=]": value` | `field >= ?` | 大于等于 |
| `"field[<]": value` | `field < ?` | 小于 |
| `"field[<=]": value` | `field <= ?` | 小于等于 |
### 模糊查询
| 写法 | SQL | 说明 |
|------|-----|------|
| `"field[~]": "keyword"` | `field LIKE '%keyword%'` | 包含 |
| `"field[~!]": "keyword"` | `field LIKE 'keyword%'` | 以...开头 |
| `"field[!~]": "keyword"` | `field LIKE '%keyword'` | 以...结尾 |
| `"field[~~]": "%keyword%"` | `field LIKE '%keyword%'` | 手动LIKE |
### 范围查询
| 写法 | SQL | 说明 |
|------|-----|------|
| `"field[<>]": [min, max]` | `field BETWEEN ? AND ?` | 区间内 |
| `"field[><]": [min, max]` | `field NOT BETWEEN ? AND ?` | 区间外 |
### 集合查询
| 写法 | SQL | 说明 |
|------|-----|------|
| `"field": [v1, v2, v3]` | `field IN (?, ?, ?)` | 在集合中 |
| `"field[!]": [v1, v2, v3]` | `field NOT IN (?, ?, ?)` | 不在集合中 |
### NULL查询
| 写法 | SQL | 说明 |
|------|-----|------|
| `"field": nil` | `field IS NULL` | 为空 |
| `"field[!]": nil` | `field IS NOT NULL` | 不为空 |
### 直接SQL
| 写法 | SQL | 说明 |
|------|-----|------|
| `"field[#]": "NOW()"` | `field = NOW()` | 直接SQL函数 |
| `"[##]": "a > b"` | `a > b` | 直接SQL片段 |
| `"field[#!]": "1"` | `field != 1` | 不等于(不参数化) |
## 逻辑连接符
### AND 条件
```go
whereMap := Map{
"AND": Map{
"status": 1,
"age[>]": 18,
},
}
```
### OR 条件
```go
whereMap := Map{
"OR": Map{
"status": 1,
"type": 2,
},
}
```
### 嵌套条件
```go
whereMap := Map{
"AND": Map{
"status": 1,
"OR": Map{
"age[<]": 30,
"level[>]": 5,
},
},
}
```
## JOIN 语法
### 传统语法
```go
joinSlice := Slice{
Map{"[>]profile": "user.id = profile.user_id"}, // LEFT JOIN
Map{"[<]department": "user.dept_id = department.id"}, // RIGHT JOIN
Map{"[><]role": "user.role_id = role.id"}, // INNER JOIN
Map{"[<>]group": "user.group_id = group.id"}, // FULL JOIN
}
```
### 链式语法
```go
builder.LeftJoin("profile", "user.id = profile.user_id")
builder.RightJoin("department", "user.dept_id = department.id")
builder.InnerJoin("role", "user.role_id = role.id")
builder.FullJoin("group", "user.group_id = group.id")
```
## 特殊字段语法
### ORDER BY
```go
Map{
"ORDER": []string{"created_time DESC", "id ASC"},
}
// 或
Map{
"ORDER": "created_time DESC",
}
```
### GROUP BY
```go
Map{
"GROUP": []string{"department", "level"},
}
// 或
Map{
"GROUP": "department",
}
```
### LIMIT
```go
Map{
"LIMIT": []int{10, 20}, // offset 10, limit 20
}
// 或
Map{
"LIMIT": 20, // limit 20
}
```
## 事务处理
```go
success := db.Action(func(tx HoTimeDB) bool {
// 在这里执行数据库操作
// 返回 true 提交事务
// 返回 false 回滚事务
id := tx.Insert("table", data)
if id == 0 {
return false // 回滚
}
affected := tx.Update("table2", data2, where2)
if affected == 0 {
return false // 回滚
}
return true // 提交
})
```
## 原生SQL执行
### 查询
```go
results := db.Query("SELECT * FROM user WHERE age > ?", 18)
```
### 执行
```go
result, err := db.Exec("UPDATE user SET status = ? WHERE id = ?", 1, 100)
affected, _ := result.RowsAffected()
```
## 错误处理
```go
// 检查最后的错误
if db.LastErr.GetError() != nil {
fmt.Println("错误:", db.LastErr.GetError())
}
// 查看最后执行的SQL
fmt.Println("SQL:", db.LastQuery)
fmt.Println("参数:", db.LastData)
```
## 工具方法
### 数据库信息
```go
prefix := db.GetPrefix() // 获取表前缀
dbType := db.GetType() // 获取数据库类型
```
### 设置模式
```go
db.Mode = 0 // 生产模式
db.Mode = 1 // 测试模式
db.Mode = 2 // 开发模式输出SQL日志
```
## 常用查询模式
### 分页列表查询
```go
// 获取总数
total := db.Count("user", Map{"status": 1})
// 分页数据
users := db.Table("user").
Where("status", 1).
Order("created_time DESC").
Page(page, pageSize).
Select("id,name,email,created_time")
// 计算分页信息
totalPages := (total + pageSize - 1) / pageSize
```
### 关联查询
```go
orders := db.Table("order").
LeftJoin("user", "order.user_id = user.id").
LeftJoin("product", "order.product_id = product.id").
Where("order.status", "paid").
Select(`
order.*,
user.name as user_name,
product.title as product_title
`)
```
### 统计查询
```go
stats := db.Select("order",
"user_id, COUNT(*) as order_count, SUM(amount) as total_amount",
Map{
"AND": Map{
"status": "paid",
"created_time[>]": "2023-01-01",
},
"GROUP": "user_id",
"ORDER": "total_amount DESC",
})
```
### 条件组合查询
```go
products := db.Table("product").
Where("status", 1).
And(Map{
"OR": Map{
"category_id": []int{1, 2, 3},
"tags[~]": "热销",
},
}).
And(Map{
"price[<>]": []float64{10.0, 1000.0},
}).
Order("sort DESC", "created_time DESC").
Limit(0, 20).
Select()
```
## 链式调用完整示例
```go
// 复杂查询链式调用
result := db.Table("order").
LeftJoin("user", "order.user_id = user.id").
LeftJoin("product", "order.product_id = product.id").
Where("order.status", "paid").
And("order.created_time[>]", "2023-01-01").
And(Map{
"OR": Map{
"user.level": "vip",
"order.amount[>]": 1000,
},
}).
Group("user.id").
Order("total_amount DESC").
Page(1, 20).
Select(`
user.id,
user.name,
user.email,
COUNT(order.id) as order_count,
SUM(order.amount) as total_amount
`)
```
---
*快速参考版本: 1.0*

View File

@ -1,890 +0,0 @@
# HoTimeDB ORM 使用说明书
## 概述
HoTimeDB是一个基于Golang实现的轻量级ORM框架参考PHP Medoo设计提供简洁的数据库操作接口。支持MySQL、SQLite等数据库并集成了缓存、事务、链式查询等功能。
## 目录
- [快速开始](#快速开始)
- [数据库配置](#数据库配置)
- [基本操作](#基本操作)
- [查询(Select)](#查询select)
- [获取单条记录(Get)](#获取单条记录get)
- [插入(Insert)](#插入insert)
- [更新(Update)](#更新update)
- [删除(Delete)](#删除delete)
- [链式查询构建器](#链式查询构建器)
- [条件查询语法](#条件查询语法)
- [JOIN操作](#join操作)
- [分页查询](#分页查询)
- [聚合函数](#聚合函数)
- [事务处理](#事务处理)
- [缓存机制](#缓存机制)
- [高级特性](#高级特性)
## 快速开始
### 初始化数据库连接
```go
import (
"code.hoteas.com/golang/hotime/db"
"code.hoteas.com/golang/hotime/common"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
// 创建连接函数
func createConnection() (master, slave *sql.DB) {
master, _ = sql.Open("mysql", "user:password@tcp(localhost:3306)/database")
// slave是可选的用于读写分离
slave = master // 或者连接到从数据库
return
}
// 初始化HoTimeDB
db := &db.HoTimeDB{}
db.SetConnect(createConnection)
```
## 数据库配置
### 基本配置
```go
type HoTimeDB struct {
*sql.DB
ContextBase
DBName string
*cache.HoTimeCache
Log *logrus.Logger
Type string // 数据库类型
Prefix string // 表前缀
LastQuery string // 最后执行的SQL
LastData []interface{} // 最后的参数
ConnectFunc func(err ...*Error) (*sql.DB, *sql.DB)
LastErr *Error
limit Slice
*sql.Tx // 事务对象
SlaveDB *sql.DB // 从数据库
Mode int // 0生产模式,1测试模式,2开发模式
}
```
### 设置表前缀
```go
db.Prefix = "app_"
```
### 设置运行模式
```go
db.Mode = 2 // 开发模式会输出SQL日志
```
## 基本操作
### 查询(Select)
#### 基本查询
```go
// 查询所有字段
users := db.Select("user")
// 查询指定字段
users := db.Select("user", "id,name,email")
// 查询指定字段(数组形式)
users := db.Select("user", []string{"id", "name", "email"})
// 单条件查询
users := db.Select("user", "*", common.Map{
"status": 1,
})
// 多条件查询必须使用AND包装
users = db.Select("user", "*", common.Map{
"AND": common.Map{
"status": 1,
"age[>]": 18,
},
})
```
#### 复杂条件查询
**重要说明多个条件必须使用AND或OR包装不能直接在根Map中写多个字段条件**
```go
// AND条件多个条件必须用AND包装
users := db.Select("user", "*", common.Map{
"AND": common.Map{
"status": 1,
"age[>]": 18,
"name[~]": "张",
},
})
// OR条件
users := db.Select("user", "*", common.Map{
"OR": common.Map{
"status": 1,
"type": 2,
},
})
// 混合条件嵌套AND/OR
users := db.Select("user", "*", common.Map{
"AND": common.Map{
"status": 1,
"OR": common.Map{
"age[<]": 30,
"level[>]": 5,
},
},
})
// 带ORDER BY、LIMIT等特殊条件
users := db.Select("user", "*", common.Map{
"AND": common.Map{
"status": 1,
"age[>]": 18,
},
"ORDER": "id DESC",
"LIMIT": 10,
})
// 带多个特殊条件
users := db.Select("user", "*", common.Map{
"OR": common.Map{
"level": "vip",
"balance[>]": 1000,
},
"ORDER": []string{"created_time DESC", "id ASC"},
"GROUP": "department",
"LIMIT": []int{0, 20}, // offset 0, limit 20
})
```
### 获取单条记录(Get)
```go
// 获取单个用户
user := db.Get("user", "*", common.Map{
"id": 1,
})
// 获取指定字段
user := db.Get("user", "id,name,email", common.Map{
"status": 1,
})
```
### 插入(Insert)
```go
// 基本插入
id := db.Insert("user", common.Map{
"name": "张三",
"email": "zhangsan@example.com",
"age": 25,
"status": 1,
"created_time[#]": "NOW()", // [#]表示直接插入SQL函数
})
// 返回插入的ID
fmt.Println("插入的用户ID:", id)
```
### 更新(Update)
```go
// 基本更新
affected := db.Update("user", common.Map{
"name": "李四",
"email": "lisi@example.com",
"updated_time[#]": "NOW()",
}, common.Map{
"id": 1,
})
// 条件更新
affected := db.Update("user", common.Map{
"status": 0,
}, common.Map{
"age[<]": 18,
"status": 1,
})
fmt.Println("更新的记录数:", affected)
```
### 删除(Delete)
```go
// 根据ID删除
affected := db.Delete("user", common.Map{
"id": 1,
})
// 条件删除
affected := db.Delete("user", common.Map{
"status": 0,
"created_time[<]": "2023-01-01",
})
fmt.Println("删除的记录数:", affected)
```
## 链式查询构建器
HoTimeDB提供了链式查询构建器让查询更加直观
```go
// 基本链式查询
users := db.Table("user").
Where("status", 1).
And("age[>]", 18).
Order("created_time DESC").
Limit(10, 20). // offset, limit
Select()
// 链式获取单条记录
user := db.Table("user").
Where("id", 1).
Get()
// 链式更新
affected := db.Table("user").
Where("id", 1).
Update(common.Map{
"name": "新名称",
"updated_time[#]": "NOW()",
})
// 链式删除
affected := db.Table("user").
Where("status", 0).
Delete()
// 链式统计
count := db.Table("user").
Where("status", 1).
Count()
```
### 链式条件组合
```go
// 复杂条件组合
users := db.Table("user").
Where("status", 1).
And("age[>=]", 18).
Or(common.Map{
"level[>]": 5,
"vip": 1,
}).
Order("created_time DESC", "id ASC").
Group("department").
Limit(0, 20).
Select("id,name,email,age")
```
## 条件查询语法
HoTimeDB支持丰富的条件查询语法类似于Medoo
### 基本比较
```go
// 等于
"id": 1
// 不等于
"id[!]": 1
// 大于
"age[>]": 18
// 大于等于
"age[>=]": 18
// 小于
"age[<]": 60
// 小于等于
"age[<=]": 60
```
### 模糊查询
```go
// LIKE %keyword%
"name[~]": "张"
// LIKE keyword% (右边任意)
"name[~!]": "张"
// LIKE %keyword (左边任意)
"name[!~]": "san"
// 手动LIKE需要手动添加%
"name[~~]": "%张%"
```
### 区间查询
```go
// BETWEEN
"age[<>]": []int{18, 60}
// NOT BETWEEN
"age[><]": []int{18, 25}
```
### IN查询
```go
// IN
"id": []int{1, 2, 3, 4, 5}
// NOT IN
"id[!]": []int{1, 2, 3}
```
### NULL查询
```go
// IS NULL
"deleted_at": nil
// IS NOT NULL
"deleted_at[!]": nil
```
### 直接SQL
```go
// 直接插入SQL表达式注意防注入
"created_time[#]": "> DATE_SUB(NOW(), INTERVAL 1 DAY)"
// 字段直接赋值(不使用参数化查询)
"update_time[#]": "NOW()"
// 直接SQL片段
"[##]": "user.status = 1 AND user.level > 0"
```
## JOIN操作
### 链式JOIN
```go
// LEFT JOIN
users := db.Table("user").
LeftJoin("profile", "user.id = profile.user_id").
LeftJoin("department", "user.dept_id = department.id").
Where("user.status", 1).
Select("user.*, profile.avatar, department.name AS dept_name")
// RIGHT JOIN
users := db.Table("user").
RightJoin("order", "user.id = order.user_id").
Select()
// INNER JOIN
users := db.Table("user").
InnerJoin("profile", "user.id = profile.user_id").
Select()
// FULL JOIN
users := db.Table("user").
FullJoin("profile", "user.id = profile.user_id").
Select()
```
### 传统JOIN语法
```go
users := db.Select("user",
common.Slice{
common.Map{"[>]profile": "user.id = profile.user_id"},
common.Map{"[>]department": "user.dept_id = department.id"},
},
"user.*, profile.avatar, department.name AS dept_name",
common.Map{
"user.status": 1,
},
)
```
### JOIN类型说明
- `[>]`: LEFT JOIN
- `[<]`: RIGHT JOIN
- `[><]`: INNER JOIN
- `[<>]`: FULL JOIN
## 分页查询
### 基本分页
```go
// 设置分页页码3每页20条
users := db.Page(3, 20).PageSelect("user", "*", common.Map{
"status": 1,
})
// 链式分页
users := db.Table("user").
Where("status", 1).
Page(2, 15). // 第2页每页15条
Select()
```
### 分页信息获取
```go
// 获取总数
total := db.Count("user", common.Map{
"status": 1,
})
// 计算分页信息
page := 2
pageSize := 20
offset := (page - 1) * pageSize
totalPages := (total + pageSize - 1) / pageSize
fmt.Printf("总记录数: %d, 总页数: %d, 当前页: %d\n", total, totalPages, page)
```
## 聚合函数
### 计数
```go
// 总数统计
total := db.Count("user")
// 条件统计
activeUsers := db.Count("user", common.Map{
"status": 1,
})
// JOIN统计
count := db.Count("user",
common.Slice{
common.Map{"[>]profile": "user.id = profile.user_id"},
},
common.Map{
"user.status": 1,
"profile.verified": 1,
},
)
```
### 求和
```go
// 基本求和
totalAmount := db.Sum("order", "amount")
// 条件求和
paidAmount := db.Sum("order", "amount", common.Map{
"status": "paid",
"created_time[>]": "2023-01-01",
})
// JOIN求和
sum := db.Sum("order", "amount",
common.Slice{
common.Map{"[>]user": "order.user_id = user.id"},
},
common.Map{
"user.level": "vip",
"order.status": "paid",
},
)
```
## 事务处理
```go
// 事务操作
success := db.Action(func(tx db.HoTimeDB) bool {
// 在事务中执行多个操作
// 扣减用户余额
affected1 := tx.Update("user", common.Map{
"balance[#]": "balance - 100",
}, common.Map{
"id": 1,
})
if affected1 == 0 {
return false // 回滚
}
// 创建订单
orderId := tx.Insert("order", common.Map{
"user_id": 1,
"amount": 100,
"status": "paid",
"created_time[#]": "NOW()",
})
if orderId == 0 {
return false // 回滚
}
// 添加订单详情
detailId := tx.Insert("order_detail", common.Map{
"order_id": orderId,
"product_id": 1001,
"quantity": 1,
"price": 100,
})
if detailId == 0 {
return false // 回滚
}
return true // 提交
})
if success {
fmt.Println("事务执行成功")
} else {
fmt.Println("事务回滚")
fmt.Println("错误:", db.LastErr.GetError())
}
```
## 缓存机制
HoTimeDB集成了缓存功能可以自动缓存查询结果
### 缓存配置
```go
import "code.hoteas.com/golang/hotime/cache"
// 设置缓存
db.HoTimeCache = &cache.HoTimeCache{
// 缓存配置
}
```
### 缓存行为
- 查询操作会自动检查缓存
- 增删改操作会自动清除相关缓存
- 缓存键格式:`表名:查询MD5`
- `cached`表不会被缓存
### 缓存清理
```go
// 手动清除表缓存
db.HoTimeCache.Db("user*", nil) // 清除user表所有缓存
```
## 高级特性
### 调试模式
```go
// 设置调试模式
db.Mode = 2
// 查看最后执行的SQL
fmt.Println("最后的SQL:", db.LastQuery)
fmt.Println("参数:", db.LastData)
fmt.Println("错误:", db.LastErr.GetError())
```
### 主从分离
```go
func createConnection() (master, slave *sql.DB) {
// 主库连接
master, _ = sql.Open("mysql", "user:password@tcp(master:3306)/database")
// 从库连接
slave, _ = sql.Open("mysql", "user:password@tcp(slave:3306)/database")
return master, slave
}
db.SetConnect(createConnection)
// 查询会自动使用从库,增删改使用主库
```
### 原生SQL执行
```go
// 执行查询SQL
results := db.Query("SELECT * FROM user WHERE age > ? AND status = ?", 18, 1)
// 执行更新SQL
result, err := db.Exec("UPDATE user SET last_login = NOW() WHERE id = ?", 1)
if err.GetError() == nil {
affected, _ := result.RowsAffected()
fmt.Println("影响行数:", affected)
}
```
### 数据类型处理
```go
// 时间戳插入
db.Insert("log", common.Map{
"user_id": 1,
"action": "login",
"created_time[#]": "UNIX_TIMESTAMP()",
})
// JSON数据
db.Insert("user", common.Map{
"name": "张三",
"preferences": `{"theme": "dark", "language": "zh-CN"}`,
})
```
### 数据行处理
HoTimeDB内部的`Row`方法会自动处理不同数据类型:
```go
// 自动转换[]uint8为字符串
// 保持其他类型的原始值
// 处理NULL值
```
## 错误处理
```go
// 检查错误
users := db.Select("user", "*", common.Map{"status": 1})
if db.LastErr.GetError() != nil {
fmt.Println("查询错误:", db.LastErr.GetError())
return
}
// 插入时检查错误
id := db.Insert("user", common.Map{
"name": "test",
"email": "test@example.com",
})
if id == 0 && db.LastErr.GetError() != nil {
fmt.Println("插入失败:", db.LastErr.GetError())
}
```
## 性能优化
### IN查询优化
HoTimeDB会自动优化IN查询将连续的数字转换为BETWEEN查询以提高性能
```go
// 这个查询会被自动优化单个IN条件
users := db.Select("user", "*", common.Map{
"id": []int{1, 2, 3, 4, 5, 10, 11, 12},
// 自动转为 (id BETWEEN 1 AND 5) OR (id BETWEEN 10 AND 12)
})
```
### 批量操作
```go
// 使用事务进行批量插入
success := db.Action(func(tx db.HoTimeDB) bool {
for i := 0; i < 1000; i++ {
id := tx.Insert("user", common.Map{
"name": fmt.Sprintf("User%d", i),
"email": fmt.Sprintf("user%d@example.com", i),
"created_time[#]": "NOW()",
})
if id == 0 {
return false
}
}
return true
})
```
## 特殊语法详解
### 条件标记符说明
| 标记符 | 功能 | 示例 | 生成SQL |
|--------|------|------|---------|
| `[>]` | 大于 | `"age[>]": 18` | `age > 18` |
| `[<]` | 小于 | `"age[<]": 60` | `age < 60` |
| `[>=]` | 大于等于 | `"age[>=]": 18` | `age >= 18` |
| `[<=]` | 小于等于 | `"age[<=]": 60` | `age <= 60` |
| `[!]` | 不等于/NOT IN | `"id[!]": 1` | `id != 1` |
| `[~]` | LIKE模糊查询 | `"name[~]": "张"` | `name LIKE '%张%'` |
| `[!~]` | 左模糊 | `"name[!~]": "张"` | `name LIKE '%张'` |
| `[~!]` | 右模糊 | `"name[~!]": "张"` | `name LIKE '张%'` |
| `[~~]` | 手动LIKE | `"name[~~]": "%张%"` | `name LIKE '%张%'` |
| `[<>]` | BETWEEN | `"age[<>]": [18,60]` | `age BETWEEN 18 AND 60` |
| `[><]` | NOT BETWEEN | `"age[><]": [18,25]` | `age NOT BETWEEN 18 AND 25` |
| `[#]` | 直接SQL | `"time[#]": "NOW()"` | `time = NOW()` |
| `[##]` | SQL片段 | `"[##]": "a > b"` | `a > b` |
| `[#!]` | 不等于直接SQL | `"status[#!]": "1"` | `status != 1` |
| `[!#]` | 不等于直接SQL | `"status[!#]": "1"` | `status != 1` |
## 与PHP Medoo的差异
1. **类型系统**: Golang的强类型要求使用`common.Map``common.Slice`
2. **语法差异**: 某些条件语法可能略有不同
3. **错误处理**: 使用Golang的错误处理模式
4. **并发安全**: 需要注意并发使用时的安全性
5. **缓存集成**: 内置了缓存功能
6. **链式调用**: 提供了更丰富的链式API
## 完整示例
```go
package main
import (
"fmt"
"database/sql"
"code.hoteas.com/golang/hotime/db"
"code.hoteas.com/golang/hotime/common"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// 初始化数据库
database := &db.HoTimeDB{
Prefix: "app_",
Mode: 2, // 开发模式
}
database.SetConnect(func(err ...*common.Error) (master, slave *sql.DB) {
master, _ = sql.Open("mysql", "root:password@tcp(localhost:3306)/testdb")
return master, master
})
// 查询用户列表
users := database.Table("user").
Where("status", 1).
And("age[>=]", 18).
Order("created_time DESC").
Limit(0, 10).
Select("id,name,email,age")
for _, user := range users {
fmt.Printf("用户: %s, 邮箱: %s, 年龄: %v\n",
user.GetString("name"),
user.GetString("email"),
user.Get("age"))
}
// 创建新用户
userId := database.Insert("user", common.Map{
"name": "新用户",
"email": "new@example.com",
"age": 25,
"status": 1,
"created_time[#]": "NOW()",
})
fmt.Printf("创建用户ID: %d\n", userId)
// 更新用户
affected := database.Table("user").
Where("id", userId).
Update(common.Map{
"last_login[#]": "NOW()",
"login_count[#]": "login_count + 1",
})
fmt.Printf("更新记录数: %d\n", affected)
// 复杂查询示例
orders := database.Table("order").
LeftJoin("user", "order.user_id = user.id").
LeftJoin("product", "order.product_id = product.id").
Where("order.status", "paid").
And("order.created_time[>]", "2023-01-01").
And(common.Map{
"OR": common.Map{
"user.level": "vip",
"order.amount[>]": 1000,
},
}).
Order("order.created_time DESC").
Group("user.id").
Select("user.name, user.email, SUM(order.amount) as total_amount, COUNT(*) as order_count")
// 事务示例
success := database.Action(func(tx db.HoTimeDB) bool {
// 在事务中执行操作
orderId := tx.Insert("order", common.Map{
"user_id": userId,
"total": 100.50,
"status": "pending",
"created_time[#]": "NOW()",
})
if orderId == 0 {
return false
}
detailId := tx.Insert("order_detail", common.Map{
"order_id": orderId,
"product_id": 1,
"quantity": 2,
"price": 50.25,
})
return detailId > 0
})
if success {
fmt.Println("订单创建成功")
} else {
fmt.Println("订单创建失败:", database.LastErr.GetError())
}
// 统计示例
totalUsers := database.Count("user", common.Map{"status": 1})
totalAmount := database.Sum("order", "amount", common.Map{"status": "paid"})
fmt.Printf("活跃用户数: %d, 总交易额: %.2f\n", totalUsers, totalAmount)
}
```
## 常见问题
### Q1: 如何处理事务中的错误?
A1: 在`Action`函数中返回`false`即可触发回滚,所有操作都会被撤销。
### Q2: 缓存何时会被清除?
A2: 执行`Insert``Update``Delete`操作时会自动清除对应表的缓存。
### Q3: 如何执行复杂的原生SQL
A3: 使用`Query`方法执行查询,使用`Exec`方法执行更新操作。
### Q4: 主从分离如何工作?
A4: 查询操作自动使用从库(如果配置了),增删改操作使用主库。
### Q5: 如何处理NULL值
A5: 使用`nil`作为值,查询时使用`"field": nil`表示`IS NULL`
---
*文档版本: 1.0*
*最后更新: 2024年*
> 本文档基于HoTimeDB源码分析生成如有疑问请参考源码实现。该ORM框架参考了PHP Medoo的设计理念但根据Golang语言特性进行了适配和优化。

View File

@ -1,252 +0,0 @@
# HoTimeDB ORM 文档集合
这是HoTimeDB ORM框架的完整文档集合包含使用说明、API参考、示例代码和测试数据。
## ⚠️ 重要更新说明
**语法修正通知**经过对源码的深入分析发现HoTimeDB的条件查询语法有特定规则
- ✅ **单个条件**可以直接写在Map中
- ⚠️ **多个条件**:必须使用`AND``OR`包装
- 📝 所有文档和示例代码已按正确语法更新
## 📚 文档列表
### 1. [HoTimeDB_使用说明.md](./HoTimeDB_使用说明.md)
**完整使用说明书** - 详细的功能介绍和使用指南
- 🚀 快速开始
- ⚙️ 数据库配置
- 🔧 基本操作 (CRUD)
- 🔗 链式查询构建器
- 🔍 条件查询语法
- 🔄 JOIN操作
- 📄 分页查询
- 📊 聚合函数
- 🔐 事务处理
- 💾 缓存机制
- ⚡ 高级特性
### 2. [HoTimeDB_API参考.md](./HoTimeDB_API参考.md)
**快速API参考手册** - 开发时的速查手册
- 📖 基本方法
- 🔧 CRUD操作
- 📊 聚合函数
- 📄 分页查询
- 🔍 条件语法参考
- 🔗 JOIN语法
- 🔐 事务处理
- 🛠️ 工具方法
### 3. [示例代码文件](../examples/hotimedb_examples.go)
**完整示例代码集合** - 可运行的实际应用示例(语法已修正)
- 🏗️ 基本初始化和配置
- 📝 基本CRUD操作
- 🔗 链式查询操作
- 🤝 JOIN查询操作
- 🔍 条件查询语法
- 📄 分页查询
- 📊 聚合函数查询
- 🔐 事务处理
- 💾 缓存机制
- 🔧 原生SQL执行
- 🚨 错误处理和调试
- ⚡ 性能优化技巧
- 🎯 完整应用示例
### 4. [test_tables.sql](./test_tables.sql)
**测试数据库结构** - 快速搭建测试环境
- 🏗️ 完整的表结构定义
- 📊 测试数据插入
- 🔍 索引优化
- 👁️ 视图示例
- 🔧 存储过程示例
## 🎯 核心特性
### 🌟 主要优势
- **类Medoo语法**: 参考PHP Medoo设计语法简洁易懂
- **链式查询**: 支持流畅的链式查询构建器
- **条件丰富**: 支持丰富的条件查询语法
- **事务支持**: 完整的事务处理机制
- **缓存集成**: 内置查询结果缓存
- **读写分离**: 支持主从数据库配置
- **类型安全**: 基于Golang的强类型系统
### 🔧 支持的数据库
- ✅ MySQL
- ✅ SQLite
- ✅ 其他标准SQL数据库
## 🚀 快速开始
### 1. 安装依赖
```bash
go mod init your-project
go get github.com/go-sql-driver/mysql
go get github.com/sirupsen/logrus
```
### 2. 创建测试数据库
```bash
mysql -u root -p < test_tables.sql
```
### 3. 基本使用
```go
import (
"code.hoteas.com/golang/hotime/db"
"code.hoteas.com/golang/hotime/common"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
// 初始化数据库
database := &db.HoTimeDB{
Prefix: "app_",
Mode: 2, // 开发模式
}
database.SetConnect(func() (master, slave *sql.DB) {
master, _ = sql.Open("mysql", "user:pass@tcp(localhost:3306)/dbname")
return master, master
})
// 链式查询链式语法支持单独Where然后用And添加条件
users := database.Table("user").
Where("status", 1). // 链式中可以单独Where
And("age[>]", 18). // 用And添加更多条件
Order("created_time DESC").
Limit(0, 10).
Select("id,name,email")
// 或者使用传统语法多个条件必须用AND包装
users2 := database.Select("user", "id,name,email", common.Map{
"AND": common.Map{
"status": 1,
"age[>]": 18,
},
"ORDER": "created_time DESC",
"LIMIT": []int{0, 10},
})
```
## ⚠️ 重要语法规则
**条件查询语法规则:**
- ✅ **单个条件**可以直接写在Map中
- ✅ **多个条件**:必须使用`AND``OR`包装
- ✅ **特殊参数**`ORDER``GROUP``LIMIT`与条件同级
```go
// ✅ 正确:单个条件
Map{"status": 1}
// ✅ 正确多个条件用AND包装
Map{
"AND": Map{
"status": 1,
"age[>]": 18,
},
"ORDER": "id DESC",
}
// ❌ 错误多个条件不用AND包装
Map{
"status": 1,
"age[>]": 18, // 不支持!
}
```
## 📝 条件查询语法速查
| 语法 | SQL | 说明 |
|------|-----|------|
| `"field": value` | `field = ?` | 等于 |
| `"field[!]": value` | `field != ?` | 不等于 |
| `"field[>]": value` | `field > ?` | 大于 |
| `"field[>=]": value` | `field >= ?` | 大于等于 |
| `"field[<]": value` | `field < ?` | 小于 |
| `"field[<=]": value` | `field <= ?` | 小于等于 |
| `"field[~]": "keyword"` | `field LIKE '%keyword%'` | 包含 |
| `"field[<>]": [min, max]` | `field BETWEEN ? AND ?` | 区间内 |
| `"field": [v1, v2, v3]` | `field IN (?, ?, ?)` | 在集合中 |
| `"field": nil` | `field IS NULL` | 为空 |
| `"field[#]": "NOW()"` | `field = NOW()` | 直接SQL |
## 🔗 JOIN语法速查
| 语法 | SQL | 说明 |
|------|-----|------|
| `"[>]table"` | `LEFT JOIN` | 左连接 |
| `"[<]table"` | `RIGHT JOIN` | 右连接 |
| `"[><]table"` | `INNER JOIN` | 内连接 |
| `"[<>]table"` | `FULL JOIN` | 全连接 |
## 🛠️ 链式方法速查
```go
db.Table("table") // 指定表名
.Where(key, value) // WHERE条件
.And(key, value) // AND条件
.Or(map) // OR条件
.LeftJoin(table, on) // LEFT JOIN
.Order(fields...) // ORDER BY
.Group(fields...) // GROUP BY
.Limit(offset, limit) // LIMIT
.Page(page, pageSize) // 分页
.Select(fields...) // 查询
.Get(fields...) // 获取单条
.Count() // 计数
.Update(data) // 更新
.Delete() // 删除
```
## ⚡ 性能优化建议
### 🔍 查询优化
- 使用合适的索引字段作为查询条件
- IN查询会自动优化为BETWEEN连续数字
- 避免SELECT *,指定需要的字段
- 合理使用LIMIT限制结果集大小
### 💾 缓存使用
- 查询结果会自动缓存
- 增删改操作会自动清除缓存
- `cached`表不参与缓存
### 🔐 事务处理
- 批量操作使用事务提高性能
- 事务中避免长时间操作
- 合理设置事务隔离级别
## 🚨 注意事项
### 🔒 安全相关
- 使用参数化查询防止SQL注入
- `[#]`语法需要注意防止注入
- 敏感数据加密存储
### 🎯 最佳实践
- 开发时设置`Mode = 2`便于调试
- 生产环境设置`Mode = 0`
- 合理设置表前缀
- 定期检查慢查询日志
## 🤝 与PHP Medoo的差异
1. **类型系统**: 使用`common.Map``common.Slice`
2. **错误处理**: Golang风格的错误处理
3. **链式调用**: 提供更丰富的链式API
4. **缓存集成**: 内置缓存功能
5. **并发安全**: 需要注意并发使用
## 📞 技术支持
- 📧 查看源码:`hotimedb.go`
- 📖 参考文档:本目录下的各个文档文件
- 🔧 示例代码:运行`HoTimeDB_示例代码.go`中的示例
---
**HoTimeDB ORM框架 - 让数据库操作更简单!** 🎉
> 本文档基于HoTimeDB源码分析生成参考了PHP Medoo的设计理念并根据Golang语言特性进行了优化。

View File

@ -34,7 +34,7 @@ type HoTimeDB struct {
}
type HotimeDBBuilder struct {
HoTimeDB *HoTimeDB
*HoTimeDB
table string
selects []interface{}
join Slice
@ -70,21 +70,7 @@ func (that *HotimeDBBuilder) Select(qu ...interface{}) []Map {
return that.HoTimeDB.Select(that.table, that.join, qu, that.where)
}
func (that *HotimeDBBuilder) Update(qu ...interface{}) int64 {
lth := len(qu)
if lth == 0 {
return 0
}
data := Map{}
if lth == 1 {
data = ObjToMap(qu[0])
}
if lth > 1 {
for k := 1; k < lth; k++ {
data[ObjToStr(qu[k-1])] = qu[k]
k++
}
}
func (that *HotimeDBBuilder) Update(data Map) int64 {
return that.HoTimeDB.Update(that.table, data, that.where)
}
@ -115,51 +101,19 @@ func (that *HotimeDBBuilder) FullJoin(table, joinStr string) *HotimeDBBuilder {
return that
}
func (that *HotimeDBBuilder) Join(qu ...interface{}) *HotimeDBBuilder {
lth := len(qu)
if lth == 0 {
return that
}
data := Map{}
if lth == 1 {
data = ObjToMap(qu[0])
}
if lth > 1 {
for k := 1; k < lth; k++ {
data[ObjToStr(qu[k-1])] = qu[k]
k++
}
}
func (that *HotimeDBBuilder) Join(join Map) *HotimeDBBuilder {
if that.join == nil {
that.join = Slice{}
}
if data == nil {
if join == nil {
return that
}
that.join = append(that.join, data)
that.join = append(that.join, join)
return that
}
func (that *HotimeDBBuilder) And(qu ...interface{}) *HotimeDBBuilder {
lth := len(qu)
if lth == 0 {
return that
}
var where Map
if lth == 1 {
where = ObjToMap(qu[0])
}
if lth > 1 {
where = Map{}
for k := 1; k < lth; k++ {
where[ObjToStr(qu[k-1])] = qu[k]
k++
}
}
func (that *HotimeDBBuilder) And(where Map) *HotimeDBBuilder {
if where == nil {
return that
}
@ -175,22 +129,7 @@ func (that *HotimeDBBuilder) And(qu ...interface{}) *HotimeDBBuilder {
return that
}
func (that *HotimeDBBuilder) Or(qu ...interface{}) *HotimeDBBuilder {
lth := len(qu)
if lth == 0 {
return that
}
var where Map
if lth == 1 {
where = ObjToMap(qu[0])
}
if lth > 1 {
where = Map{}
for k := 1; k < lth; k++ {
where[ObjToStr(qu[k-1])] = qu[k]
k++
}
}
func (that *HotimeDBBuilder) Or(where Map) *HotimeDBBuilder {
if where == nil {
return that
}
@ -205,24 +144,7 @@ func (that *HotimeDBBuilder) Or(qu ...interface{}) *HotimeDBBuilder {
return that
}
func (that *HotimeDBBuilder) Where(qu ...interface{}) *HotimeDBBuilder {
lth := len(qu)
if lth == 0 {
return that
}
var where Map
if lth == 1 {
where = ObjToMap(qu[0])
}
if lth > 1 {
where = Map{}
for k := 1; k < lth; k++ {
where[ObjToStr(qu[k-1])] = qu[k]
k++
}
}
func (that *HotimeDBBuilder) Where(where Map) *HotimeDBBuilder {
if where == nil {
return that
}
@ -271,15 +193,8 @@ func (that *HoTimeDB) GetType() string {
// Action 事务如果action返回true则执行成功false则回滚
func (that *HoTimeDB) Action(action func(db HoTimeDB) (isSuccess bool)) (isSuccess bool) {
db := HoTimeDB{that.DB, that.ContextBase, that.DBName,
that.HoTimeCache, that.Log, that.Type,
that.Prefix, that.LastQuery, that.LastData,
that.ConnectFunc, that.LastErr, that.limit, that.Tx,
that.SlaveDB, that.Mode}
//tx, err := db.BeginTx(context.Background(), &sql.TxOptions{Isolation: sql.LevelReadCommitted})
db := HoTimeDB{DB: that.DB, HoTimeCache: that.HoTimeCache, Prefix: that.Prefix}
tx, err := db.Begin()
if err != nil {
that.LastErr.SetError(err)
return isSuccess
@ -321,7 +236,7 @@ func (that *HoTimeDB) InitDb(err ...*Error) *Error {
e := that.SlaveDB.Ping()
that.LastErr.SetError(e)
}
//that.DB.SetConnMaxLifetime(time.Second)
return that.LastErr
}
@ -541,7 +456,7 @@ func (that *HoTimeDB) md5(query string, args ...interface{}) string {
func (that *HoTimeDB) Query(query string, args ...interface{}) []Map {
defer func() {
if that.Mode != 0 {
if that.Mode == 2 {
that.Log.Info("SQL:"+that.LastQuery, " DATA:", that.LastData, " ERROR:", that.LastErr.GetError())
}
}()
@ -562,24 +477,6 @@ func (that *HoTimeDB) Query(query string, args ...interface{}) []Map {
that.LastErr.SetError(err)
return nil
}
for key, _ := range args {
arg := args[key]
argType := reflect.ValueOf(arg).Type().String()
if strings.Contains(argType, "[]") || strings.Contains(argType, "Slice") {
argLis := ObjToSlice(arg)
//将slice转为分割字符串
argStr := ""
for i := 0; i < len(argLis); i++ {
if i == len(argLis)-1 {
argStr += ObjToStr(argLis[i])
} else {
argStr += ObjToStr(argLis[i]) + ","
}
}
args[key] = argStr
}
}
if that.Tx != nil {
resl, err = that.Tx.Query(query, args...)
@ -587,18 +484,16 @@ func (that *HoTimeDB) Query(query string, args ...interface{}) []Map {
resl, err = db.Query(query, args...)
}
if err != nil && that.LastErr.GetError() != nil &&
that.LastErr.GetError().Error() == err.Error() {
return nil
}
that.LastErr.SetError(err)
if err != nil {
if err = db.Ping(); err == nil {
if err = db.Ping(); err != nil {
that.LastErr.SetError(err)
_ = that.InitDb()
if that.LastErr.GetError() != nil {
return nil
}
return that.Query(query, args...)
}
that.LastErr.SetError(err)
return nil
}
@ -607,7 +502,7 @@ func (that *HoTimeDB) Query(query string, args ...interface{}) []Map {
func (that *HoTimeDB) Exec(query string, args ...interface{}) (sql.Result, *Error) {
defer func() {
if that.Mode != 0 {
if that.Mode == 2 {
that.Log.Info("SQL: "+that.LastQuery, " DATA: ", that.LastData, " ERROR: ", that.LastErr.GetError())
}
}()
@ -622,47 +517,25 @@ func (that *HoTimeDB) Exec(query string, args ...interface{}) (sql.Result, *Erro
return nil, that.LastErr
}
for key, _ := range args {
arg := args[key]
argType := ""
if arg != nil {
argType = reflect.ValueOf(arg).Type().String()
}
if strings.Contains(argType, "[]") || strings.Contains(argType, "Slice") {
argLis := ObjToSlice(arg)
//将slice转为分割字符串
argStr := ""
for i := 0; i < len(argLis); i++ {
if i == len(argLis)-1 {
argStr += ObjToStr(argLis[i])
} else {
argStr += ObjToStr(argLis[i]) + ","
}
}
args[key] = argStr
}
}
if that.Tx != nil {
resl, e = that.Tx.Exec(query, args...)
} else {
resl, e = that.DB.Exec(query, args...)
}
if e != nil && that.LastErr.GetError() != nil &&
that.LastErr.GetError().Error() == e.Error() {
return resl, that.LastErr
}
that.LastErr.SetError(e)
//判断是否连接断开了
if e != nil {
if e = that.DB.Ping(); e == nil {
if e = that.DB.Ping(); e != nil {
that.LastErr.SetError(e)
_ = that.InitDb()
if that.LastErr.GetError() != nil {
return resl, that.LastErr
}
return that.Exec(query, args...)
}
that.LastErr.SetError(e)
return resl, that.LastErr
}
@ -709,13 +582,11 @@ func (that *HoTimeDB) Select(table string, qu ...interface{}) []Map {
data := ObjToSlice(qu[intQs])
for i := 0; i < len(data); i++ {
k := data.GetString(i)
if strings.Contains(k, " AS ") ||
strings.Contains(k, ".") {
if strings.Contains(k, " AS ") {
query += " " + k + " "
} else {
query += " `" + k + "` "
}
@ -746,10 +617,10 @@ func (that *HoTimeDB) Select(table string, qu ...interface{}) []Map {
}
}
if reflect.ValueOf(qu[0]).Type().String() == "common.Slice" || strings.Contains(reflect.ValueOf(qu[0]).Type().String(), "[]") {
qu0 := ObjToSlice(qu[0])
for key, _ := range qu0 {
v := qu0.GetMap(key)
if reflect.ValueOf(qu[0]).Type().String() == "common.Slice" {
for key, _ := range testQuData {
v := testQuData.GetMap(key)
for k1, v1 := range v {
testQu = append(testQu, k1)
testQuData[k1] = v1
@ -763,42 +634,15 @@ func (that *HoTimeDB) Select(table string, qu ...interface{}) []Map {
v := testQuData[k]
switch Substr(k, 0, 3) {
case "[>]":
func() {
table := Substr(k, 3, len(k)-3)
if !strings.Contains(table, " ") {
table = "`" + table + "`"
}
query += " LEFT JOIN " + table + " ON " + v.(string) + " "
}()
query += " LEFT JOIN `" + Substr(k, 3, len(k)-3) + "` ON " + v.(string) + " "
case "[<]":
func() {
table := Substr(k, 3, len(k)-3)
if !strings.Contains(table, " ") {
table = "`" + table + "`"
}
query += " RIGHT JOIN " + table + " ON " + v.(string) + " "
}()
query += " RIGHT JOIN `" + Substr(k, 3, len(k)-3) + "` ON " + v.(string) + " "
}
switch Substr(k, 0, 4) {
case "[<>]":
func() {
table := Substr(k, 4, len(k)-4)
if !strings.Contains(table, " ") {
table = "`" + table + "`"
}
query += " FULL JOIN " + table + " ON " + v.(string) + " "
}()
query += " FULL JOIN `" + Substr(k, 4, len(k)-4) + "` ON " + v.(string) + " "
case "[><]":
func() {
table := Substr(k, 4, len(k)-4)
if !strings.Contains(table, " ") {
table = "`" + table + "`"
}
query += " INNER JOIN " + table + " ON " + v.(string) + " "
}()
query += " INNER JOIN `" + Substr(k, 4, len(k)-4) + "` ON " + v.(string) + " "
}
}
}
@ -893,32 +737,7 @@ func (that *HoTimeDB) Count(table string, qu ...interface{}) int {
var condition = []string{"AND", "OR"}
var vcond = []string{"GROUP", "ORDER", "LIMIT"}
// Count 计数
func (that *HoTimeDB) Sum(table string, column string, qu ...interface{}) float64 {
var req = []interface{}{}
if len(qu) == 2 {
req = append(req, qu[0])
req = append(req, "SUM("+column+")")
req = append(req, qu[1])
} else {
req = append(req, "SUM("+column+")")
req = append(req, qu...)
}
//req=append(req,qu...)
data := that.Select(table, req...)
//fmt.Println(data)
if len(data) == 0 {
return 0
}
//res,_:=StrToInt(data[0]["COUNT(*)"].(string))
res := ObjToStr(data[0]["SUM("+column+")"])
count := ObjToFloat64(res)
return count
}
// where语句解析
//where语句解析
func (that *HoTimeDB) where(data Map) (string, []interface{}) {
where := ""
@ -1011,12 +830,11 @@ func (that *HoTimeDB) where(data Map) (string, []interface{}) {
where += k
}
if reflect.ValueOf(v).Type().String() == "common.Slice" || strings.Contains(reflect.ValueOf(v).Type().String(), "[]") {
vs := ObjToSlice(v)
for i := 0; i < len(vs); i++ {
where += " " + vs.GetString(i) + " "
if reflect.ValueOf(v).Type().String() == "common.Slice" {
for i := 0; i < len(v.(Slice)); i++ {
where += " " + ObjToStr(v.(Slice)[i]) + " "
if len(vs) != i+1 {
if len(v.(Slice)) != i+1 {
where += ", "
}
@ -1099,7 +917,7 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
v = "%" + ObjToStr(v) + "%"
res = append(res, v)
case "[!~]": //左边任意
k = strings.Replace(k, "[!~]", "", -1)
k = strings.Replace(k, "[~]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "` "
}
@ -1107,7 +925,7 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
v = "%" + ObjToStr(v) + ""
res = append(res, v)
case "[~!]": //右边任意
k = strings.Replace(k, "[~!]", "", -1)
k = strings.Replace(k, "[~]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "` "
}
@ -1148,18 +966,16 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
k = "`" + k + "` "
}
where += k + " NOT BETWEEN ? AND ? "
vs := ObjToSlice(v)
res = append(res, vs[0])
res = append(res, vs[1])
res = append(res, v.(Slice)[0])
res = append(res, v.(Slice)[1])
case "[<>]":
k = strings.Replace(k, "[<>]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "` "
}
where += k + " BETWEEN ? AND ? "
vs := ObjToSlice(v)
res = append(res, vs[0])
res = append(res, vs[1])
res = append(res, v.(Slice)[0])
res = append(res, v.(Slice)[1])
default:
if !strings.Contains(k, ".") {
k = "`" + k + "` "
@ -1170,98 +986,6 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
return where, res
}
if len(vs) == 1 {
where += k + "=? "
res = append(res, vs[0])
return where, res
}
min := int64(0)
isMin := true
IsRange := true
num := int64(0)
isNum := true
where1 := ""
res1 := Slice{}
where2 := k + " IN ("
res2 := Slice{}
for kvs := 0; kvs <= len(vs); kvs++ {
vsv := int64(0)
if kvs < len(vs) {
vsv = vs.GetCeilInt64(kvs)
//确保是全部是int类型
if ObjToStr(vsv) != vs.GetString(kvs) {
IsRange = false
break
}
}
if isNum {
isNum = false
num = vsv
} else {
num++
}
if isMin {
isMin = false
min = vsv
}
//不等于则到了分路口
if num != vsv {
//between
if num-min > 1 {
if where1 != "" {
where1 += " OR " + k + " BETWEEN ? AND ? "
} else {
where1 += k + " BETWEEN ? AND ? "
}
res1 = append(res1, min)
res1 = append(res1, num-1)
} else {
//如果就前进一步就用OR
where2 += "?,"
res2 = append(res2, min)
}
min = vsv
num = vsv
}
}
if IsRange {
where3 := ""
if where1 != "" {
where3 += where1
res = append(res, res1...)
}
if len(res2) == 1 {
if where3 == "" {
where3 += k + " = ? "
} else {
where3 += " OR " + k + " = ? "
}
res = append(res, res2...)
} else if len(res2) > 1 {
where2 = where2[:len(where2)-1]
if where3 == "" {
where3 += where2 + ")"
} else {
where3 += " OR " + where2 + ")"
}
res = append(res, res2...)
}
if where3 != "" {
where += "(" + where3 + ")"
}
return where, res
}
where += k + " IN ("
res = append(res, vs...)
@ -1295,100 +1019,6 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
if len(vs) == 0 {
return where, res
}
if len(vs) == 1 {
where += k + "=? "
res = append(res, vs[0])
return where, res
}
//In转betwin和IN提升部分性能
min := int64(0)
isMin := true
IsRange := true
num := int64(0)
isNum := true
where1 := ""
res1 := Slice{}
where2 := k + " IN ("
res2 := Slice{}
for kvs := 0; kvs <= len(vs); kvs++ {
vsv := int64(0)
if kvs < len(vs) {
vsv = vs.GetCeilInt64(kvs)
//确保是全部是int类型
if ObjToStr(vsv) != vs.GetString(kvs) {
IsRange = false
break
}
}
if isNum {
isNum = false
num = vsv
} else {
num++
}
if isMin {
isMin = false
min = vsv
}
//不等于则到了分路口
if num != vsv {
//between
if num-min > 1 {
if where1 != "" {
where1 += " OR " + k + " BETWEEN ? AND ? "
} else {
where1 += k + " BETWEEN ? AND ? "
}
res1 = append(res1, min)
res1 = append(res1, num-1)
} else {
//如果就前进一步就用OR
where2 += "?,"
res2 = append(res2, min)
}
min = vsv
num = vsv
}
}
if IsRange {
where3 := ""
if where1 != "" {
where3 += where1
res = append(res, res1...)
}
if len(res2) == 1 {
if where3 == "" {
where3 += k + " = ? "
} else {
where3 += " OR " + k + " = ? "
}
res = append(res, res2...)
} else if len(res2) > 1 {
where2 = where2[:len(where2)-1]
if where3 == "" {
where3 += where2 + ")"
} else {
where3 += " OR " + where2 + ")"
}
res = append(res, res2...)
}
if where3 != "" {
where += "(" + where3 + ")"
}
return where, res
}
where += k + " IN ("
res = append(res, vs...)
@ -1412,7 +1042,7 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
return where, res
}
// that.Db.Update("user",hotime.Map{"ustate":"1"},hotime.Map{"AND":hotime.Map{"OR":hotime.Map{"uid":4,"uname":"dasda"}},"ustate":1})
// that.Db.Update("user",hotime.Map{"ustate":"1"},hotime.Map{"AND":hotime.Map{"OR":hotime.Map{"uid":4,"uname":"dasda"}},"ustate":1})
func (that *HoTimeDB) notIn(k string, v interface{}, where string, res []interface{}) (string, []interface{}) {
//where:=""
//fmt.Println(reflect.ValueOf(v).Type().String())
@ -1548,7 +1178,7 @@ func (that *HoTimeDB) Update(table string, data Map, where Map) int64 {
func (that *HoTimeDB) Delete(table string, data map[string]interface{}) int64 {
query := "DELETE FROM `" + that.Prefix + table + "` "
query := "DELETE FROM " + that.Prefix + table + " "
temp, resWhere := that.where(data)
query += temp + ";"

View File

@ -1,332 +0,0 @@
-- HoTimeDB 测试表结构
-- 用于测试和示例的MySQL表结构定义
-- 请根据实际需要修改表结构和字段类型
-- 创建数据库(可选)
CREATE DATABASE IF NOT EXISTS `hotimedb_test` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE `hotimedb_test`;
-- 用户表
DROP TABLE IF EXISTS `app_user`;
CREATE TABLE `app_user` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`name` varchar(100) NOT NULL DEFAULT '' COMMENT '用户姓名',
`email` varchar(255) NOT NULL DEFAULT '' COMMENT '邮箱地址',
`password` varchar(255) NOT NULL DEFAULT '' COMMENT '密码hash',
`phone` varchar(20) NOT NULL DEFAULT '' COMMENT '手机号',
`age` int(11) NOT NULL DEFAULT '0' COMMENT '年龄',
`gender` tinyint(4) NOT NULL DEFAULT '0' COMMENT '性别 0-未知 1-男 2-女',
`avatar` varchar(500) NOT NULL DEFAULT '' COMMENT '头像URL',
`level` varchar(20) NOT NULL DEFAULT 'normal' COMMENT '用户等级 normal-普通 vip-会员 svip-超级会员',
`balance` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '账户余额',
`login_count` int(11) NOT NULL DEFAULT '0' COMMENT '登录次数',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态 1-正常 0-禁用 -1-删除',
`last_login` datetime DEFAULT NULL COMMENT '最后登录时间',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted_at` datetime DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_email` (`email`),
KEY `idx_status` (`status`),
KEY `idx_level` (`level`),
KEY `idx_created_time` (`created_time`),
KEY `idx_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表';
-- 用户资料表
DROP TABLE IF EXISTS `app_profile`;
CREATE TABLE `app_profile` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
`real_name` varchar(50) NOT NULL DEFAULT '' COMMENT '真实姓名',
`id_card` varchar(20) NOT NULL DEFAULT '' COMMENT '身份证号',
`address` varchar(500) NOT NULL DEFAULT '' COMMENT '地址',
`bio` text COMMENT '个人简介',
`verified` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否认证 1-是 0-否',
`preferences` json DEFAULT NULL COMMENT '用户偏好设置JSON',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_user_id` (`user_id`),
KEY `idx_verified` (`verified`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户资料表';
-- 部门表
DROP TABLE IF EXISTS `app_department`;
CREATE TABLE `app_department` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '部门ID',
`name` varchar(100) NOT NULL DEFAULT '' COMMENT '部门名称',
`parent_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '上级部门ID',
`manager_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '部门经理ID',
`description` text COMMENT '部门描述',
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态 1-正常 0-禁用',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_parent_id` (`parent_id`),
KEY `idx_manager_id` (`manager_id`),
KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='部门表';
-- 商品表
DROP TABLE IF EXISTS `app_product`;
CREATE TABLE `app_product` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '商品ID',
`title` varchar(200) NOT NULL DEFAULT '' COMMENT '商品标题',
`description` text COMMENT '商品描述',
`price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '商品价格',
`stock` int(11) NOT NULL DEFAULT '0' COMMENT '库存数量',
`category_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '分类ID',
`brand` varchar(100) NOT NULL DEFAULT '' COMMENT '品牌',
`tags` varchar(500) NOT NULL DEFAULT '' COMMENT '标签,逗号分隔',
`images` json DEFAULT NULL COMMENT '商品图片JSON数组',
`attributes` json DEFAULT NULL COMMENT '商品属性JSON',
`sales_count` int(11) NOT NULL DEFAULT '0' COMMENT '销售数量',
`view_count` int(11) NOT NULL DEFAULT '0' COMMENT '浏览数量',
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态 1-上架 0-下架',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_category_id` (`category_id`),
KEY `idx_price` (`price`),
KEY `idx_status` (`status`),
KEY `idx_created_time` (`created_time`),
FULLTEXT KEY `ft_title_description` (`title`,`description`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商品表';
-- 订单表
DROP TABLE IF EXISTS `app_order`;
CREATE TABLE `app_order` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '订单ID',
`order_no` varchar(50) NOT NULL DEFAULT '' COMMENT '订单号',
`user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
`product_id` bigint(20) unsigned NOT NULL COMMENT '商品ID',
`quantity` int(11) NOT NULL DEFAULT '1' COMMENT '数量',
`price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '单价',
`amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '总金额',
`discount_amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '优惠金额',
`final_amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '实付金额',
`status` varchar(20) NOT NULL DEFAULT 'pending' COMMENT '订单状态 pending-待付款 paid-已付款 shipped-已发货 completed-已完成 cancelled-已取消',
`payment_method` varchar(20) NOT NULL DEFAULT '' COMMENT '支付方式',
`shipping_address` json DEFAULT NULL COMMENT '收货地址JSON',
`remark` text COMMENT '订单备注',
`paid_time` datetime DEFAULT NULL COMMENT '支付时间',
`shipped_time` datetime DEFAULT NULL COMMENT '发货时间',
`completed_time` datetime DEFAULT NULL COMMENT '完成时间',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_order_no` (`order_no`),
KEY `idx_user_id` (`user_id`),
KEY `idx_product_id` (`product_id`),
KEY `idx_status` (`status`),
KEY `idx_created_time` (`created_time`),
KEY `idx_paid_time` (`paid_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单表';
-- 订单详情表
DROP TABLE IF EXISTS `app_order_detail`;
CREATE TABLE `app_order_detail` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`order_id` bigint(20) unsigned NOT NULL COMMENT '订单ID',
`product_id` bigint(20) unsigned NOT NULL COMMENT '商品ID',
`product_title` varchar(200) NOT NULL DEFAULT '' COMMENT '商品标题',
`product_image` varchar(500) NOT NULL DEFAULT '' COMMENT '商品图片',
`price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '单价',
`quantity` int(11) NOT NULL DEFAULT '1' COMMENT '数量',
`amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '小计',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_order_id` (`order_id`),
KEY `idx_product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单详情表';
-- 支付日志表
DROP TABLE IF EXISTS `app_payment_log`;
CREATE TABLE `app_payment_log` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
`order_id` bigint(20) unsigned DEFAULT NULL COMMENT '订单ID',
`transaction_id` varchar(100) NOT NULL DEFAULT '' COMMENT '交易ID',
`type` varchar(20) NOT NULL DEFAULT '' COMMENT '类型 order_payment-订单支付 recharge-充值 refund-退款',
`amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '金额',
`method` varchar(20) NOT NULL DEFAULT '' COMMENT '支付方式 balance-余额 alipay-支付宝 wechat-微信',
`status` varchar(20) NOT NULL DEFAULT 'pending' COMMENT '状态 pending-处理中 success-成功 failed-失败',
`description` varchar(255) NOT NULL DEFAULT '' COMMENT '描述',
`extra_data` json DEFAULT NULL COMMENT '额外数据JSON',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`),
KEY `idx_order_id` (`order_id`),
KEY `idx_transaction_id` (`transaction_id`),
KEY `idx_type` (`type`),
KEY `idx_status` (`status`),
KEY `idx_created_time` (`created_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='支付日志表';
-- 转账日志表
DROP TABLE IF EXISTS `app_transfer_log`;
CREATE TABLE `app_transfer_log` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`from_user_id` bigint(20) unsigned NOT NULL COMMENT '转出用户ID',
`to_user_id` bigint(20) unsigned NOT NULL COMMENT '转入用户ID',
`amount` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '转账金额',
`type` varchar(20) NOT NULL DEFAULT 'transfer' COMMENT '类型',
`status` varchar(20) NOT NULL DEFAULT 'success' COMMENT '状态',
`description` varchar(255) NOT NULL DEFAULT '' COMMENT '描述',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_from_user_id` (`from_user_id`),
KEY `idx_to_user_id` (`to_user_id`),
KEY `idx_created_time` (`created_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='转账日志表';
-- 操作日志表
DROP TABLE IF EXISTS `app_operation_log`;
CREATE TABLE `app_operation_log` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`user_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
`module` varchar(50) NOT NULL DEFAULT '' COMMENT '模块',
`action` varchar(50) NOT NULL DEFAULT '' COMMENT '操作',
`description` varchar(255) NOT NULL DEFAULT '' COMMENT '描述',
`ip` varchar(45) NOT NULL DEFAULT '' COMMENT 'IP地址',
`user_agent` varchar(500) NOT NULL DEFAULT '' COMMENT '用户代理',
`request_data` json DEFAULT NULL COMMENT '请求数据JSON',
`response_data` json DEFAULT NULL COMMENT '响应数据JSON',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态 1-成功 0-失败',
`execution_time` int(11) NOT NULL DEFAULT '0' COMMENT '执行时间(毫秒)',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`),
KEY `idx_module` (`module`),
KEY `idx_action` (`action`),
KEY `idx_created_time` (`created_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='操作日志表';
-- 缓存表HoTimeDB内置缓存使用
DROP TABLE IF EXISTS `app_cached`;
CREATE TABLE `app_cached` (
`key` varchar(255) NOT NULL COMMENT '缓存键',
`value` longtext COMMENT '缓存值',
`expire_time` datetime DEFAULT NULL COMMENT '过期时间',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`key`),
KEY `idx_expire_time` (`expire_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='缓存表';
-- 批量用户表(用于批量操作示例)
DROP TABLE IF EXISTS `app_user_batch`;
CREATE TABLE `app_user_batch` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(100) NOT NULL DEFAULT '' COMMENT '用户姓名',
`email` varchar(255) NOT NULL DEFAULT '' COMMENT '邮箱地址',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态',
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_created_time` (`created_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='批量用户表';
-- 插入测试数据
INSERT INTO `app_user` (`name`, `email`, `password`, `age`, `level`, `balance`, `status`, `created_time`) VALUES
('张三', 'zhangsan@example.com', 'hashed_password_1', 25, 'normal', 1000.00, 1, '2023-01-15 10:30:00'),
('李四', 'lisi@example.com', 'hashed_password_2', 30, 'vip', 5000.00, 1, '2023-02-20 14:20:00'),
('王五', 'wangwu@example.com', 'hashed_password_3', 28, 'svip', 10000.00, 1, '2023-03-10 16:45:00'),
('赵六', 'zhaoliu@example.com', 'hashed_password_4', 35, 'normal', 500.00, 1, '2023-04-05 09:15:00'),
('钱七', 'qianqi@example.com', 'hashed_password_5', 22, 'vip', 2500.00, 0, '2023-05-12 11:30:00');
INSERT INTO `app_profile` (`user_id`, `real_name`, `verified`) VALUES
(1, '张三', 1),
(2, '李四', 1),
(3, '王五', 1),
(4, '赵六', 0),
(5, '钱七', 0);
INSERT INTO `app_department` (`name`, `parent_id`, `description`) VALUES
('技术部', 0, '负责技术开发和维护'),
('产品部', 0, '负责产品设计和规划'),
('市场部', 0, '负责市场推广和销售'),
('前端组', 1, '负责前端开发'),
('后端组', 1, '负责后端开发');
INSERT INTO `app_product` (`title`, `description`, `price`, `stock`, `category_id`, `brand`, `sales_count`) VALUES
('苹果手机', '最新款苹果手机,性能强劲', 6999.00, 100, 1, '苹果', 50),
('华为手机', '国产精品手机,拍照出色', 4999.00, 200, 1, '华为', 80),
('小米手机', '性价比之王,配置丰富', 2999.00, 300, 1, '小米', 120),
('联想笔记本', '商务办公首选,稳定可靠', 5999.00, 50, 2, '联想', 30),
('戴尔笔记本', '游戏性能出色,散热良好', 8999.00, 30, 2, '戴尔', 15);
INSERT INTO `app_order` (`order_no`, `user_id`, `product_id`, `quantity`, `price`, `amount`, `final_amount`, `status`, `created_time`) VALUES
('ORD202301150001', 1, 1, 1, 6999.00, 6999.00, 6999.00, 'paid', '2023-01-15 15:30:00'),
('ORD202301160001', 2, 2, 2, 4999.00, 9998.00, 9998.00, 'paid', '2023-01-16 10:20:00'),
('ORD202301170001', 3, 3, 1, 2999.00, 2999.00, 2999.00, 'completed', '2023-01-17 14:15:00'),
('ORD202301180001', 1, 4, 1, 5999.00, 5999.00, 5999.00, 'pending', '2023-01-18 16:45:00'),
('ORD202301190001', 4, 5, 1, 8999.00, 8999.00, 8999.00, 'cancelled', '2023-01-19 11:30:00');
INSERT INTO `app_order_detail` (`order_id`, `product_id`, `product_title`, `price`, `quantity`, `amount`) VALUES
(1, 1, '苹果手机', 6999.00, 1, 6999.00),
(2, 2, '华为手机', 4999.00, 2, 9998.00),
(3, 3, '小米手机', 2999.00, 1, 2999.00),
(4, 4, '联想笔记本', 5999.00, 1, 5999.00),
(5, 5, '戴尔笔记本', 8999.00, 1, 8999.00);
INSERT INTO `app_payment_log` (`user_id`, `order_id`, `type`, `amount`, `method`, `status`, `description`) VALUES
(1, 1, 'order_payment', 6999.00, 'balance', 'success', '订单支付'),
(2, 2, 'order_payment', 9998.00, 'alipay', 'success', '订单支付'),
(3, 3, 'order_payment', 2999.00, 'wechat', 'success', '订单支付'),
(2, NULL, 'recharge', 10000.00, 'alipay', 'success', '账户充值'),
(3, NULL, 'recharge', 5000.00, 'wechat', 'success', '账户充值');
-- 创建索引优化查询性能
CREATE INDEX idx_user_email_status ON app_user(email, status);
CREATE INDEX idx_order_user_status ON app_order(user_id, status);
CREATE INDEX idx_order_created_status ON app_order(created_time, status);
CREATE INDEX idx_product_category_status ON app_product(category_id, status);
-- 创建视图(可选)
CREATE OR REPLACE VIEW v_user_order_stats AS
SELECT
u.id as user_id,
u.name as user_name,
u.email,
u.level,
COUNT(o.id) as order_count,
COALESCE(SUM(o.final_amount), 0) as total_amount,
COALESCE(AVG(o.final_amount), 0) as avg_amount,
MAX(o.created_time) as last_order_time
FROM app_user u
LEFT JOIN app_order o ON u.id = o.user_id AND o.status IN ('paid', 'completed')
WHERE u.status = 1
GROUP BY u.id;
-- 存储过程示例(可选)
DELIMITER //
CREATE PROCEDURE GetUserOrderSummary(IN p_user_id BIGINT)
BEGIN
SELECT
u.name,
u.email,
u.level,
u.balance,
COUNT(o.id) as order_count,
COALESCE(SUM(CASE WHEN o.status = 'paid' THEN o.final_amount END), 0) as paid_amount,
COALESCE(SUM(CASE WHEN o.status = 'completed' THEN o.final_amount END), 0) as completed_amount
FROM app_user u
LEFT JOIN app_order o ON u.id = o.user_id
WHERE u.id = p_user_id AND u.status = 1
GROUP BY u.id;
END //
DELIMITER ;
-- 显示表结构信息
SELECT
TABLE_NAME as '表名',
TABLE_COMMENT as '表注释',
TABLE_ROWS as '预估行数',
ROUND(DATA_LENGTH/1024/1024, 2) as '数据大小(MB)'
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'app_%'
ORDER BY TABLE_NAME;

View File

@ -1,7 +1,6 @@
package baidu
import (
. "code.hoteas.com/golang/hotime/common"
"fmt"
"io/ioutil"
"net/http"
@ -22,93 +21,6 @@ func (that *baiduMap) Init(Ak string) {
//query
}
// from 源坐标类型:
// 1GPS标准坐标
// 2搜狗地图坐标
// 3火星坐标gcj02即高德地图、腾讯地图和MapABC等地图使用的坐标
// 43中列举的地图坐标对应的墨卡托平面坐标;
// 5百度地图采用的经纬度坐标bd09ll
// 6百度地图采用的墨卡托平面坐标bd09mc;
// 7图吧地图坐标
// 851地图坐标
// int 1 1 否
// to
// 目标坐标类型:
// 3火星坐标gcj02即高德地图、腾讯地图及MapABC等地图使用的坐标
// 5百度地图采用的经纬度坐标bd09ll
// 6百度地图采用的墨卡托平面坐标bd09mc
func (that *baiduMap) Geoconv(latlngs []Map, from, to int) (Slice, error) {
client := &http.Client{}
latlngsStr := ""
for _, v := range latlngs {
if latlngsStr != "" {
latlngsStr = latlngsStr + ";" + v.GetString("lng") + "," + v.GetString("lat")
} else {
latlngsStr = v.GetString("lng") + "," + v.GetString("lat")
}
}
url := "https://api.map.baidu.com/geoconv/v1/?from=" + ObjToStr(from) + "&to=" + ObjToStr(to) + "&ak=" + that.Ak + "&coords=" + latlngsStr
reqest, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Println("Fatal error ", err.Error())
return nil, err
}
response, err := client.Do(reqest)
defer response.Body.Close()
if err != nil {
fmt.Println("Fatal error ", err.Error())
return nil, err
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
//fmt.Println(string(body))
data := ObjToMap(string(body))
if data.GetCeilInt64("status") != 0 {
return nil, err
}
return data.GetSlice("result"), err
}
func (that *baiduMap) GetAddress(lat string, lng string) (string, error) {
client := &http.Client{}
url := "https://api.map.baidu.com/reverse_geocoding/v3/?ak=" + that.Ak + "&output=json&location=" + lat + "," + lng
reqest, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Println("Fatal error ", err.Error())
return "", err
}
response, err := client.Do(reqest)
defer response.Body.Close()
if err != nil {
fmt.Println("Fatal error ", err.Error())
return "", err
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", err
}
//fmt.Println(string(body))
return string(body), err
}
// GetPosition 获取定位列表
func (that *baiduMap) GetPosition(name string, region string) (string, error) {

View File

@ -18,13 +18,13 @@ func Down(url, path, name string, e ...*Error) bool {
}
out, err := os.Create(path + name)
if err != nil && len(e) != 0 {
if err != nil && e[0] != nil {
e[0].SetError(err)
return false
}
defer out.Close()
resp, err := http.Get(url)
if err != nil && len(e) != 0 {
if err != nil && e[0] != nil {
e[0].SetError(err)
return false
}
@ -32,7 +32,7 @@ func Down(url, path, name string, e ...*Error) bool {
pix, err := ioutil.ReadAll(resp.Body)
_, err = io.Copy(out, bytes.NewReader(pix))
if err != nil && len(e) != 0 {
if err != nil && e[0] != nil {
e[0].SetError(err)
return false
}

View File

@ -1,149 +0,0 @@
package mongodb
import (
. "code.hoteas.com/golang/hotime/common"
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MongoDb struct {
Client *mongo.Client
Ctx context.Context
DataBase *mongo.Database
Connect *mongo.Collection
LastErr error
}
func GetMongoDb(database, url string) (*MongoDb, error) {
db := MongoDb{}
clientOptions := options.Client().ApplyURI(url)
db.Ctx = context.TODO()
// Connect to MongoDb
var err error
db.Client, err = mongo.Connect(db.Ctx, clientOptions)
if err != nil {
return nil, err
}
// Check the connection
err = db.Client.Ping(db.Ctx, nil)
if err != nil {
return nil, err
}
fmt.Println("Connected to MongoDb!")
//databases, err := db.Client.ListDatabaseNames(db.Ctx, bson.M{})
//if err != nil {
// return nil, err
//}
//fmt.Println(databases)
db.DataBase = db.Client.Database(database)
return &db, nil
}
func (that *MongoDb) Insert(table string, data interface{}) string {
collection := that.DataBase.Collection(table)
re, err := collection.InsertOne(that.Ctx, data)
if err != nil {
that.LastErr = err
return ""
}
return ObjToStr(re.InsertedID)
}
func (that *MongoDb) InsertMany(table string, data ...interface{}) Slice {
collection := that.DataBase.Collection(table)
re, err := collection.InsertMany(that.Ctx, data)
if err != nil {
that.LastErr = err
return Slice{}
}
return ObjToSlice(re.InsertedIDs)
}
func (that *MongoDb) Update(table string, data Map, where Map) int64 {
collection := that.DataBase.Collection(table)
re, err := collection.UpdateMany(that.Ctx, where, data)
if err != nil {
that.LastErr = err
return 0
}
return re.ModifiedCount
}
func (that *MongoDb) Delete(table string, where Map) int64 {
collection := that.DataBase.Collection(table)
re, err := collection.DeleteMany(that.Ctx, where)
if err != nil {
that.LastErr = err
return 0
}
return re.DeletedCount
}
func (that *MongoDb) Get(table string, where Map) Map {
results := []Map{}
var cursor *mongo.Cursor
var err error
collection := that.DataBase.Collection(table)
if cursor, err = collection.Find(that.Ctx, where, options.Find().SetSkip(0), options.Find().SetLimit(2)); err != nil {
that.LastErr = err
return nil
}
//延迟关闭游标
defer func() {
if err := cursor.Close(that.Ctx); err != nil {
that.LastErr = err
}
}()
//这里的结果遍历可以使用另外一种更方便的方式:
if err = cursor.All(that.Ctx, &results); err != nil {
that.LastErr = err
return nil
}
if len(results) > 0 {
return results[0]
}
return nil
}
func (that MongoDb) Select(table string, where Map, page, pageRow int64) []Map {
page = (page - 1) * pageRow
if page < 0 {
page = 0
}
results := []Map{}
var cursor *mongo.Cursor
var err error
collection := that.DataBase.Collection(table)
if cursor, err = collection.Find(that.Ctx, where, options.Find().SetSkip(page), options.Find().SetLimit(pageRow)); err != nil {
that.LastErr = err
return results
}
//延迟关闭游标
defer func() {
if err := cursor.Close(that.Ctx); err != nil {
that.LastErr = err
}
}()
//这里的结果遍历可以使用另外一种更方便的方式:
if err = cursor.All(that.Ctx, &results); err != nil {
that.LastErr = err
return results
}
return results
}

104
example/app/article.go Normal file
View File

@ -0,0 +1,104 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"time"
)
var ArticleCtr = Ctr{
"info": func(that *Context) {
sn := that.Req.FormValue("sn")
article := that.Db.Get("article", Map{"[><]ctg_article": "article.id=ctg_article.article_id"}, "article.*,ctg_article.ctg_id AS sctg_id", Map{"ctg_article.sn": sn})
if article == nil {
that.Display(4, "找不到对应数据")
return
}
ctgId := article.GetCeilInt64("sctg_id")
ctg := that.Db.Get("ctg", "*", Map{"id": ctgId})
parents := []Map{}
parentId := ctg.GetCeilInt64("parent_id")
article["tongji"] = that.Db.Select("ctg", "sn,name,img,parent_id", Map{"parent_id": parentId})
for true {
if parentId == 0 {
break
}
parent := that.Db.Get("ctg", "sn,name,img,parent_id", Map{"id": parentId})
if parent == nil {
break
}
parents = append(parents, parent)
parentId = parent.GetCeilInt64("parent_id")
}
ctg["parents"] = parents
article["ctg"] = ctg
that.Display(0, article)
},
"list": func(that *Context) {
sn := that.Req.FormValue("ctg_sn") //ctgsn
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page == 0 {
page = 1
}
if pageSize == 0 {
pageSize = 10
}
keywords := that.Req.FormValue("keywords")
lunbo := ObjToInt(that.Req.FormValue("lunbo"))
sort := that.Req.FormValue("sort")
where := Map{"article.push_time[<]": time.Now().Format("2006-01-02 15:04"), "article.state": 0}
if sn != "" {
ctg := that.Db.Get("ctg", "id", Map{"sn": sn})
if ctg != nil {
where["ctg_article.ctg_id"] = ctg.GetCeilInt("id")
}
}
startTime := that.Req.FormValue("start_time") //ctgsn
finishTime := that.Req.FormValue("finish_time") //ctgsn
if lunbo != 0 {
where["article.lunbo"] = lunbo
}
if len(startTime) > 5 {
where["article.push_time[>=]"] = startTime
}
if len(finishTime) > 5 {
where["article.push_time[<=]"] = finishTime
}
if keywords != "" {
where["OR"] = Map{"article.title[~]": keywords, "article.description[~]": keywords, "article.author[~]": keywords, "article.sn[~]": keywords, "article.origin[~]": keywords, "article.url[~]": keywords}
}
if len(where) > 1 {
where = Map{"AND": where}
}
if sort == "" {
where["ORDER"] = Slice{"article.sort DESC", "article.push_time DESC"}
}
if sort == "time" {
where["ORDER"] = "article.push_time DESC"
}
count := that.Db.Count("article", Map{"[><]ctg_article": "article.id=ctg_article.article_id"}, where)
article := that.Db.Page(page, pageSize).PageSelect("article", Map{"[><]ctg_article": "article.id=ctg_article.article_id"}, "ctg_article.sn,article.img,article.title,article.description,article.push_time,article.lunbo,article.author,article.origin,article.url", where)
that.Display(0, Map{"count": count, "data": article})
},
}

77
example/app/ctg.go Normal file
View File

@ -0,0 +1,77 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var CtgCtr = Ctr{
"info": func(that *Context) {
sn := that.Req.FormValue("sn")
ctg := that.Db.Get("ctg", "*", Map{"sn": sn})
parents := []Map{}
parentId := ctg.GetCeilInt64("parent_id")
ctg["tongji"] = that.Db.Select("ctg", "sn,name,img,parent_id", Map{"parent_id": parentId})
for true {
if parentId == 0 {
break
}
parent := that.Db.Get("ctg", "sn,name,img,parent_id", Map{"id": parentId})
if parent == nil {
break
}
parents = append(parents, parent)
parentId = parent.GetCeilInt64("parent_id")
}
if ctg.GetCeilInt64("article_id") != 0 {
ctg["article"] = that.Db.Get("article", "*", Map{"id": ctg.GetCeilInt64("article_id")})
}
ctg["parents"] = parents
that.Display(0, ctg)
},
"list": func(that *Context) {
sn := that.Req.FormValue("sn") //ctgsn
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page == 0 {
page = 1
}
if pageSize == 0 {
pageSize = 50
}
keywords := that.Req.FormValue("keywords")
//sort:=that.Req.FormValue("sort")
where := Map{"state": 0}
if sn != "" {
ctg := that.Db.Get("ctg", "id", Map{"sn": sn})
if ctg != nil {
where["parent_id"] = ctg.GetCeilInt("id")
}
}
if keywords != "" {
where["OR"] = Map{"name[~]": keywords, "url[~]": keywords, "sn[~]": keywords}
}
if len(where) > 1 {
where = Map{"AND": where}
}
where["ORDER"] = Slice{"sort DESC", "id DESC"}
article := that.Db.Page(page, pageSize).PageSelect("ctg", "name,sn,sort,url,img", where)
that.Display(0, article)
},
}

127
example/app/init.go Normal file
View File

@ -0,0 +1,127 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"time"
)
var AppProj = Proj{
"article": ArticleCtr,
"org": OrgCtr,
"ctg": CtgCtr,
"mail": MailCtr,
"test": {
"test": func(that *Context) {
//data:=that.Db.Table("admin").Order("id DESC").Select("*")
//data1:=that.Db.Table("admin").Where(Map{"name[~]":"m"}).Order("id DESC").Select("*")
//
//data3:=that.Db.Select("admin","*",Map{"name[~]":"m"})
data2 := that.Db.Table("article").Where(Map{"title[~]": "m"}).Order("id DESC").Page(1, 10).Select("*")
c := that.Db.Table("article").Where(Map{"title[~]": "m"}).Order("id DESC").Group("title").Select("*")
//that.Display(0,Slice{data1,data,data3,data2})
that.Display(0, Slice{data2, c})
},
"res": func(that *Context) {
ebw_res := that.Db.Select("ebw_res", "*")
for _, v := range ebw_res {
data := Map{"id": v.GetCeilInt("id"), "name": v.GetString("name"),
"parent_id": v.GetCeilInt64("pid"),
"sn": v.GetString("url"), "create_time": time.Now().Format("2006-01-02 15:04"),
"modify_time": time.Now().Format("2006-01-02 15:04"), "admin_id": 1}
if data.GetCeilInt("parent_id") == 0 {
data["parent_id"] = nil
}
that.Db.Insert("ctg", data)
}
that.Db.Exec("UPDATE ctg SET parent_id =NULL WHERE parent_id=id")
ss(0, that)
that.Display(0, len(ebw_res))
},
"news": func(that *Context) {
ebw_news := that.Db.Select("ebw_news", "*")
for _, v := range ebw_news {
ctg := that.Db.Get("ctg", "*", Map{"sn": v.GetString("type")})
data := Map{"sn": v.GetString("id"), "title": v.GetString("title"),
"content": v.GetString("content"), "push_time": v.GetString("timedate"),
"author": v.GetString("owner"), "origin": v.GetString("source"), "click_num": v.GetString("readtime"),
"sort": v.GetCeilInt("zhiding"), "create_time": time.Now().Format("2006-01-02 15:04"),
"modify_time": time.Now().Format("2006-01-02 15:04"), "admin_id": 1}
if ctg != nil {
data["ctg_id"] = ctg.GetCeilInt("id")
}
that.Db.Insert("article", data)
}
that.Display(0, len(ebw_news))
},
"res2news": func(that *Context) {
ebw_news_addition_res := that.Db.Select("ebw_news_addition_res", "*")
for _, v := range ebw_news_addition_res {
ctg := that.Db.Get("ctg", "*", Map{"sn": v.GetString("fk_res")})
article := that.Db.Get("article", "*", Map{"sn": v.GetString("fk_newsid")})
data := Map{"sn": Md5(ObjToStr(time.Now().UnixNano()) + ObjToStr(RandX(10000, 100000))),
"create_time": time.Now().Format("2006-01-02 15:04"),
"modify_time": time.Now().Format("2006-01-02 15:04"), "admin_id": 1}
if ctg != nil {
data["ctg_id"] = ctg.GetCeilInt("id")
}
if article != nil {
data["article_id"] = article.GetCeilInt("id")
}
that.Db.Insert("ctg_article", data)
}
that.Display(0, len(ebw_news_addition_res))
},
//将文章没有关联的ctg_article进行关联
"article": func(that *Context) {
articles := that.Db.Select("article", "id,ctg_id")
for _, v := range articles {
ctg_article := that.Db.Get("ctg_article", "id", Map{"article_id": v.GetCeilInt("id")})
if ctg_article == nil {
data := Map{"sn": Md5(ObjToStr(time.Now().UnixNano()) + ObjToStr(RandX(10000, 100000))),
"create_time": time.Now().Format("2006-01-02 15:04"),
"modify_time": time.Now().Format("2006-01-02 15:04"), "admin_id": 1}
if v.GetCeilInt("ctg_id") == 0 || v.GetCeilInt("id") == 0 {
continue
}
data["ctg_id"] = v.GetCeilInt("ctg_id")
data["article_id"] = v.GetCeilInt("id")
that.Db.Insert("ctg_article", data)
}
}
that.Display(0, len(articles))
},
},
}
func ss(parent_id int, that *Context) {
var ctgs []Map
ctg := that.Db.Get("ctg", "*", Map{"id": parent_id})
if parent_id == 0 {
ctgs = that.Db.Select("ctg", "*", Map{"parent_id": nil})
} else {
ctgs = that.Db.Select("ctg", "*", Map{"parent_id": parent_id})
}
for _, v := range ctgs {
if ctg == nil {
ctg = Map{"parent_ids": ","}
}
ids := ctg.GetString("parent_ids") + ObjToStr(v.GetCeilInt("id")) + ","
that.Db.Update("ctg", Map{"parent_ids": ids}, Map{"id": v.GetCeilInt("id")})
ss(v.GetCeilInt("id"), that)
}
}

96
example/app/mail.go Normal file
View File

@ -0,0 +1,96 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"time"
)
var MailCtr = Ctr{
"add": func(that *Context) {
title := that.Req.FormValue("title")
name := that.Req.FormValue("name")
phone := that.Req.FormValue("phone")
content := that.Req.FormValue("content")
tp := ObjToInt(that.Req.FormValue("type"))
show := ObjToInt(that.Req.FormValue("show"))
if len(title) < 5 {
that.Display(3, "标题过短")
return
}
if len(name) < 2 {
that.Display(3, "姓名错误")
return
}
if len(phone) < 8 {
that.Display(3, "联系方式错误")
return
}
if len(content) < 10 {
that.Display(3, "内容过短")
return
}
data := Map{
"sn": Md5(ObjToStr(time.Now().UnixNano()) + ObjToStr(RandX(10000, 100000))),
"name": name, "title": title, "phone": phone, "content": content, "type": tp, "show": show,
"modify_time[#]": "NOW()", "create_time[#]": "NOW()",
}
id := that.Db.Insert("mail", data)
if id == 0 {
that.Display(4, "创建失败")
return
}
that.Display(0, "成功")
return
},
"info": func(that *Context) {
sn := that.Req.FormValue("sn")
mail := that.Db.Get("mail", "*", Map{"sn": sn})
that.Display(0, mail)
},
"list": func(that *Context) {
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page == 0 {
page = 1
}
if pageSize == 0 {
pageSize = 10
}
//keywords:=that.Req.FormValue("keywords")
//sort:=that.Req.FormValue("sort")
where := Map{"state": 0, "show": 1}
//if keywords!=""{
// where["OR"]=Map{"title[~]":keywords,"description[~]":keywords,"author[~]":keywords,"sn[~]":keywords,"origin[~]":keywords,"url[~]":keywords}
//}
if len(where) > 1 {
where = Map{"AND": where}
}
//if sort==""{
// where["ORDER"]=Slice{"sort DESC","push_time DESC"}
//}
//
//if sort=="time"{
where["ORDER"] = "create_time DESC"
//}
count := that.Db.Count("mail", where)
mail := that.Db.Page(page, pageSize).PageSelect("mail", "*", where)
that.Display(0, Map{"count": count, "data": mail})
},
}

60
example/app/org.go Normal file
View File

@ -0,0 +1,60 @@
package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"time"
)
var OrgCtr = Ctr{
"info": func(that *Context) {
sn := that.Req.FormValue("sn")
article := that.Db.Get("article", "*", Map{"sn": sn})
that.Display(0, article)
},
"list": func(that *Context) {
sn := that.Req.FormValue("sn") //orgsn
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
if page == 0 {
page = 1
}
if pageSize == 0 {
pageSize = 50
}
keywords := that.Req.FormValue("keywords")
sort := that.Req.FormValue("sort")
where := Map{"push_time[<=]": time.Now().Format("2006-01-02 15:04"), "state": 0}
if sn != "" {
org := that.Db.Get("org", "id", Map{"sn": sn})
if org != nil {
where["org_id"] = org.GetCeilInt("id")
}
}
if keywords != "" {
where["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "author[~]": keywords, "sn[~]": keywords, "origin[~]": keywords, "url[~]": keywords}
}
if len(where) > 1 {
where = Map{"AND": where}
}
if sort == "" {
where["ORDER"] = Slice{"sort DESC", "id DESC"}
}
if sort == "time" {
where["ORDER"] = "push_time DESC"
}
article := that.Db.Page(page, pageSize).PageSelect("article", "sn,title,description,push_time,lunbo,author,origin,url", where)
that.Display(0, article)
},
}

View File

@ -1,472 +0,0 @@
{
"flow": {
"admin": {
"sql": {
"role_id": "role_id"
},
"stop": false,
"table": "admin"
},
"article": {
"sql": {
"admin_id": "id"
},
"stop": false,
"table": "article"
},
"ctg": {
"sql": {
"admin_id": "id"
},
"stop": false,
"table": "ctg"
},
"ctg_article": {
"sql": {
"admin_id": "id"
},
"stop": false,
"table": "ctg_article"
},
"ctg_copy": {
"sql": {
"admin_id": "id"
},
"stop": false,
"table": "ctg_copy"
},
"logs": {
"sql": {
},
"stop": false,
"table": "logs"
},
"org": {
"sql": {
"admin_id": "id"
},
"stop": false,
"table": "org"
},
"role": {
"sql": {
"admin_id": "id",
"id": "role_id"
},
"stop": true,
"table": "role"
}
},
"id": "74a8a59407fa7d6c7fcdc85742dbae57",
"label": "HoTime管理平台",
"labelConfig": {
"add": "添加",
"delete": "删除",
"download": "下载清单",
"edit": "编辑",
"info": "查看详情",
"show": "开启"
},
"menus": [
{
"auth": [
"show"
],
"icon": "Setting",
"label": "ebw_news",
"menus": [
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "ebw_news",
"table": "ebw_news"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "ebw_news_addition_res",
"table": "ebw_news_addition_res"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "ebw_annex",
"table": "ebw_annex"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "ebw_customer",
"table": "ebw_customer"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "ebw_items",
"table": "ebw_items"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "ebw_res",
"table": "ebw_res"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "ebw_vote",
"table": "ebw_vote"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "ebw_vote_option",
"table": "ebw_vote_option"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "ebw_user",
"table": "ebw_user"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "ebw_attachment",
"table": "ebw_attachment"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "ebw_jobs",
"table": "ebw_jobs"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "ebw_vote_user",
"table": "ebw_vote_user"
}
],
"name": "sys:ebw"
},
{
"auth": [
"show"
],
"icon": "Setting",
"label": "系统管理",
"menus": [
{
"auth": [
"show",
"download"
],
"label": "日志管理",
"table": "logs"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "角色管理",
"table": "role"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "组织管理",
"table": "org"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "人员管理",
"table": "admin"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "文章管理",
"table": "article"
}
],
"name": "sys"
},
{
"auth": [
"show"
],
"icon": "Setting",
"label": "外部系统",
"menus": [
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "外部系统",
"table": "swiper_sys"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "顶部",
"table": "swiper_top"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "飘窗",
"table": "swiper_fly"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "底部",
"table": "swiper_bottom"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "中间",
"table": "swiper_center"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "关联专题",
"table": "swiper_point"
}
],
"name": "sys:swiper"
},
{
"auth": [
"show"
],
"icon": "Setting",
"label": "栏目管理",
"menus": [
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "栏目管理",
"table": "ctg"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "关联栏目",
"table": "ctg_article"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "栏目管理",
"table": "ctg_copy"
}
],
"name": "sys:ctg"
},
{
"auth": [
"show"
],
"icon": "Setting",
"label": "纪委信箱",
"menus": [
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "纪委信箱",
"table": "mail_discipline"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "总经理信箱",
"table": "mail"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "党委书记信箱",
"table": "mail_part"
}
],
"name": "sys:mail"
}
],
"name": "admin",
"stop": [
"role",
"org"
]
}

File diff suppressed because it is too large Load Diff

View File

@ -1,422 +0,0 @@
[
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "idcard",
"strict": false,
"type": ""
},
{
"add": false,
"edit": false,
"info": true,
"list": true,
"must": false,
"name": "id",
"strict": true,
"type": ""
},
{
"add": false,
"edit": false,
"info": true,
"list": true,
"must": false,
"name": "sn",
"strict": false,
"type": ""
},
{
"add": false,
"edit": false,
"info": false,
"list": false,
"must": false,
"name": "parent_ids",
"strict": true,
"type": "index"
},
{
"add": false,
"edit": false,
"info": false,
"list": false,
"must": false,
"name": "index",
"strict": true,
"type": "index"
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "parent_id",
"true": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "amount",
"strict": true,
"type": "money"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "info",
"strict": false,
"type": "textArea"
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "status",
"strict": false,
"type": "select"
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "state",
"strict": false,
"type": "select"
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "sex",
"strict": false,
"type": "select"
},
{
"add": false,
"edit": false,
"info": false,
"list": false,
"must": false,
"name": "delete",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "lat",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "lng",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "latitude",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "longitude",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": false,
"list": false,
"must": false,
"name": "password",
"strict": false,
"type": "password"
},
{
"add": true,
"edit": true,
"info": false,
"list": false,
"must": false,
"name": "pwd",
"strict": false,
"type": "password"
},
{
"add": false,
"edit": false,
"info": false,
"list": false,
"must": false,
"name": "version",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "seq",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "sort",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "note",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "description",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "abstract",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "content",
"strict": false,
"type": "textArea"
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "address",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "full_name",
"strict": false,
"type": ""
},
{
"add": false,
"edit": false,
"info": true,
"list": false,
"must": false,
"name": "create_time",
"strict": true,
"type": "time"
},
{
"add": false,
"edit": false,
"info": true,
"list": true,
"must": false,
"name": "modify_time",
"strict": true,
"type": "time"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "image",
"strict": false,
"type": "image"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "img",
"strict": false,
"type": "image"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "avatar",
"strict": false,
"type": "image"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "icon",
"strict": false,
"type": "image"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "file",
"strict": false,
"type": "file"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "age",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "email",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "time",
"strict": false,
"type": "time"
},
{
"add": false,
"edit": false,
"info": true,
"list": false,
"must": false,
"name": "level",
"strict": false,
"type": ""
},
{
"add": true,
"edit": true,
"info": true,
"list": true,
"must": false,
"name": "rule",
"strict": false,
"type": "form"
},
{
"add": true,
"edit": true,
"info": true,
"list": false,
"must": false,
"name": "auth",
"strict": true,
"type": "auth"
},
{
"add": false,
"edit": false,
"info": true,
"list": true,
"must": false,
"name": "table",
"strict": false,
"type": "table"
},
{
"add": false,
"edit": false,
"info": true,
"list": true,
"must": false,
"name": "table_id",
"strict": false,
"type": "table_id"
}
]

View File

@ -2,6 +2,7 @@ package main
import (
. "code.hoteas.com/golang/hotime"
"code.hoteas.com/golang/hotime/example/app"
)
func main() {
@ -12,6 +13,6 @@ func main() {
return isFinished
})
appIns.Run(Router{})
appIns.Run(Router{"app": app.AppProj})
}

File diff suppressed because one or more lines are too long

View File

@ -1 +0,0 @@
.el-upload{height:100px;width:100px;background:#eee;overflow:hidden}.el-upload img[data-v-3b5105e6]{height:100%;width:100%;-o-object-fit:cover;object-fit:cover;display:block}.el-upload i[data-v-3b5105e6]{font-size:40px;margin:30% 31%;display:block}.custom-tree-node[data-v-3b5105e6]{font-size:14px;padding-right:8px}.info-descriptions[data-v-4d4566fc] .el-descriptions__body .el-descriptions__label{min-width:90px;text-align:right;background:transparent;color:#606266;font-weight:400}.el-descriptions .is-bordered th[data-v-4d4566fc],.info-descriptions[data-v-4d4566fc] .el-descriptions .is-bordered td{border:transparent;max-width:25vw}.tree-line .el-tree-node{position:relative;padding-left:16px}.tree-line .el-tree-node__content{line-height:18px;font-size:14px}.tree-line .el-tree-node__children{padding-left:16px}.tree-line .el-tree-node:before{content:"";height:100%;width:1px;position:absolute;left:-3px;top:-26px;border-width:1px;border-left:1px dashed #52627c}.tree-line .el-tree-node:last-child:before{height:38px}.tree-line .el-tree-node:after{content:"";width:24px;height:20px;position:absolute;left:-3px;top:12px;border-width:1px;border-top:1px dashed #52627c}.tree-line>.el-tree-node:after{border-top:none}.tree-line>.el-tree-node:before{border-left:none}.tree-line .el-tree-node__expand-icon{font-size:18px;color:#000}.tree-line .el-tree-node__expand-icon.is-leaf{color:transparent}.dialog-box .el-descriptions__header{margin:20px 0 5px}.dialog-box .el-descriptions__body{background:#fff}.textarea-box *{word-break:break-all;white-space:pre-wrap}.textarea-box table{width:100%!important}.textarea-box img{max-width:80%!important}.textarea-box::-webkit-scrollbar-thumb{height:5px;background-color:rgba(0,0,0,.2)!important}

View File

@ -1 +0,0 @@
body[data-v-c08f3364],dd[data-v-c08f3364],dl[data-v-c08f3364],form[data-v-c08f3364],h1[data-v-c08f3364],h2[data-v-c08f3364],h3[data-v-c08f3364],h4[data-v-c08f3364],h5[data-v-c08f3364],h6[data-v-c08f3364],html[data-v-c08f3364],ol[data-v-c08f3364],p[data-v-c08f3364],pre[data-v-c08f3364],tbody[data-v-c08f3364],textarea[data-v-c08f3364],tfoot[data-v-c08f3364],thead[data-v-c08f3364],ul[data-v-c08f3364]{margin:0;font-size:14px;font-family:Microsoft YaHei}dl[data-v-c08f3364],ol[data-v-c08f3364],ul[data-v-c08f3364]{padding:0}li[data-v-c08f3364]{list-style:none}input[data-v-c08f3364]{border:none;outline:none;font-family:Microsoft YaHei;background-color:#fff}a[data-v-c08f3364]{font-family:Microsoft YaHei;text-decoration:none}[data-v-c08f3364]{margin:0;padding:0}.login[data-v-c08f3364]{position:relative;width:100%;height:100%;background-color:#353d56;background-repeat:no-repeat;background-attachment:fixed;background-size:cover}.login-item[data-v-c08f3364]{position:absolute;top:calc(50% - 30vh);left:60%;min-width:388px;width:18vw;max-width:588px;padding:8vh 30px;box-sizing:border-box;background-size:468px 468px;background:hsla(0,0%,100%,.85);border-radius:10px}.login-item .right-content[data-v-c08f3364]{box-sizing:border-box;width:100%}.login-item .right-content .login-title[data-v-c08f3364]{font-size:26px;font-weight:700;color:#4f619b;text-align:center}.errorMsg[data-v-c08f3364]{width:100%;height:34px;line-height:34px;color:red;font-size:14px;overflow:hidden}.login-item .right-content .inputWrap[data-v-c08f3364]{width:90%;height:32px;line-height:32px;color:#646464;font-size:16px;border:1px solid #b4b4b4;margin:0 auto 5%;padding:2% 10px;border-radius:10px}.login-item .right-content .inputWrap.inputFocus[data-v-c08f3364]{border:1px solid #4f619b;box-shadow:0 0 0 3px rgba(91,113,185,.4)}.login-item .right-content .inputWrap input[data-v-c08f3364]{background-color:transparent;color:#646464;display:inline-block;height:100%;width:80%}.login-btn[data-v-c08f3364]{width:97%;height:52px;text-align:center;line-height:52px;font-size:17px;color:#fff;background-color:#4f619b;border-radius:10px;margin:0 auto;margin-top:50px;cursor:pointer;font-weight:800}

View File

@ -1 +0,0 @@
.el-upload{height:100px;width:100px;background:#eee;overflow:hidden}.el-upload img[data-v-51dbed3c]{height:100%;width:100%;-o-object-fit:cover;object-fit:cover;display:block}.el-upload i[data-v-51dbed3c]{font-size:40px;margin:30% 31%;display:block}.custom-tree-node[data-v-51dbed3c]{font-size:14px;padding-right:8px}.info-descriptions[data-v-4d4566fc] .el-descriptions__body .el-descriptions__label{min-width:90px;text-align:right;background:transparent;color:#606266;font-weight:400}.el-descriptions .is-bordered th[data-v-4d4566fc],.info-descriptions[data-v-4d4566fc] .el-descriptions .is-bordered td{border:transparent;max-width:25vw}.tree-line .el-tree-node{position:relative;padding-left:16px}.tree-line .el-tree-node__content{line-height:18px;font-size:14px}.tree-line .el-tree-node__children{padding-left:16px}.tree-line .el-tree-node:before{content:"";height:100%;width:1px;position:absolute;left:-3px;top:-26px;border-width:1px;border-left:1px dashed #52627c}.tree-line .el-tree-node:last-child:before{height:38px}.tree-line .el-tree-node:after{content:"";width:24px;height:20px;position:absolute;left:-3px;top:12px;border-width:1px;border-top:1px dashed #52627c}.tree-line>.el-tree-node:after{border-top:none}.tree-line>.el-tree-node:before{border-left:none}.tree-line .el-tree-node__expand-icon{font-size:18px;color:#000}.tree-line .el-tree-node__expand-icon.is-leaf{color:transparent}.dialog-box .el-descriptions__header{margin:20px 0 5px}.dialog-box .el-descriptions__body{background:#fff}.textarea-box *{word-break:break-all;white-space:pre-wrap}.textarea-box table{width:100%!important}.textarea-box img{max-width:80%!important}.textarea-box::-webkit-scrollbar-thumb{height:5px;background-color:rgba(0,0,0,.2)!important}

View File

@ -1 +0,0 @@
.full-screen-container[data-v-12e6b782]{z-index:10000}.file-upload .el-upload{background:transparent;width:100%;height:auto;text-align:left;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.file-upload .el-upload .el-button{margin-right:10px}.el-upload img[data-v-69e31561]{height:100%;width:100%;-o-object-fit:cover;object-fit:cover;display:block}.el-upload i[data-v-69e31561]{font-size:40px;margin:30% 31%;display:block}.el-upload{height:100px;width:100px;background:#eee;overflow:hidden}.tree-line .el-tree-node{position:relative;padding-left:16px}.tree-line .el-tree-node__content{line-height:18px;font-size:14px}.tree-line .el-tree-node__children{padding-left:16px}.tree-line .el-tree-node:before{content:"";height:100%;width:1px;position:absolute;left:-3px;top:-26px;border-width:1px;border-left:1px dashed #52627c}.tree-line .el-tree-node:last-child:before{height:38px}.tree-line .el-tree-node:after{content:"";width:24px;height:20px;position:absolute;left:-3px;top:12px;border-width:1px;border-top:1px dashed #52627c}.tree-line>.el-tree-node:after{border-top:none}.tree-line>.el-tree-node:before{border-left:none}.tree-line .el-tree-node__expand-icon{font-size:18px;color:#000}.tree-line .el-tree-node__expand-icon.is-leaf{color:transparent}

View File

@ -1 +0,0 @@
.left-nav-home-bar{background:#2c3759!important;overflow:hidden;text-overflow:ellipsis}.left-nav-home-bar,.left-nav-home-bar i{color:#fff!important}.el-submenu .el-menu-item{height:40px;line-height:40px;width:auto;min-width:60px;padding:0 10px 0 25px!important;text-overflow:ellipsis;overflow:hidden}.el-menu .el-submenu__title{height:46px;line-height:46px;padding-left:10px!important;text-overflow:ellipsis;overflow:hidden}.left-nav-home-bar i{margin-bottom:6px!important}.el-menu-item-group__title{padding:0 0 0 10px}.el-menu--collapse .el-menu-item-group__title,.el-menu--collapse .el-submenu__title{padding-left:20px!important}.el-menu-item i,.el-submenu__title i{margin-top:-4px;vertical-align:middle;margin:-3px 5px 0 0;right:1px}.head-left[data-v-b2941c10],.head-right[data-v-b2941c10]{display:flex;justify-content:center;flex-direction:column}.head-right[data-v-b2941c10]{align-items:flex-end}.el-upload{height:100px;width:100px;background:#eee;overflow:hidden}.el-upload img[data-v-51dbed3c]{height:100%;width:100%;-o-object-fit:cover;object-fit:cover;display:block}.el-upload i[data-v-51dbed3c]{font-size:40px;margin:30% 31%;display:block}.custom-tree-node[data-v-51dbed3c]{font-size:14px;padding-right:8px}.info-descriptions[data-v-4d4566fc] .el-descriptions__body .el-descriptions__label{min-width:90px;text-align:right;background:transparent;color:#606266;font-weight:400}.el-descriptions .is-bordered th[data-v-4d4566fc],.info-descriptions[data-v-4d4566fc] .el-descriptions .is-bordered td{border:transparent;max-width:25vw}.tree-line .el-tree-node{position:relative;padding-left:16px}.tree-line .el-tree-node__content{line-height:18px;font-size:14px}.tree-line .el-tree-node__children{padding-left:16px}.tree-line .el-tree-node:before{content:"";height:100%;width:1px;position:absolute;left:-3px;top:-26px;border-width:1px;border-left:1px dashed #52627c}.tree-line .el-tree-node:last-child:before{height:38px}.tree-line .el-tree-node:after{content:"";width:24px;height:20px;position:absolute;left:-3px;top:12px;border-width:1px;border-top:1px dashed #52627c}.tree-line>.el-tree-node:after{border-top:none}.tree-line>.el-tree-node:before{border-left:none}.tree-line .el-tree-node__expand-icon{font-size:18px;color:#000}.tree-line .el-tree-node__expand-icon.is-leaf{color:transparent}.dialog-box .el-descriptions__header{margin:20px 0 5px}.dialog-box .el-descriptions__body{background:#fff}.textarea-box *{word-break:break-all;white-space:pre-wrap}.textarea-box table{width:100%!important}.textarea-box img{max-width:80%!important}.textarea-box::-webkit-scrollbar-thumb{height:5px;background-color:rgba(0,0,0,.2)!important}.el-dialog{margin:auto!important;top:50%;transform:translateY(-50%)}.el-dialog-div{height:75vh;overflow:auto}.el-dialog__body{padding-top:15px;padding-bottom:45px}.el-dialog-div .el-tabs__header{position:absolute;left:1px;top:69px;width:calc(90vw - 42px);margin:0 20px;z-index:1}.el-dialog-div .el-tabs__content{padding-top:50px}.el-dialog-div .el-affix--fixed{bottom:20vh}.el-dialog-div .el-affix--fixed .el-form-item{padding:0!important;background:transparent!important}

View File

@ -1 +0,0 @@
.full-screen-container[data-v-12e6b782]{z-index:10000}.file-upload .el-upload{background:transparent;width:100%;height:auto;text-align:left;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.file-upload .el-upload .el-button{margin-right:10px}.el-upload img[data-v-96cdfb38]{height:100%;width:100%;-o-object-fit:cover;object-fit:cover;display:block}.el-upload i[data-v-96cdfb38]{font-size:40px;margin:30% 31%;display:block}.el-upload{height:100px;width:100px;background:#eee;overflow:hidden}.tree-line .el-tree-node{position:relative;padding-left:16px}.tree-line .el-tree-node__content{line-height:18px;font-size:14px}.tree-line .el-tree-node__children{padding-left:16px}.tree-line .el-tree-node:before{content:"";height:100%;width:1px;position:absolute;left:-3px;top:-26px;border-width:1px;border-left:1px dashed #52627c}.tree-line .el-tree-node:last-child:before{height:38px}.tree-line .el-tree-node:after{content:"";width:24px;height:20px;position:absolute;left:-3px;top:12px;border-width:1px;border-top:1px dashed #52627c}.tree-line>.el-tree-node:after{border-top:none}.tree-line>.el-tree-node:before{border-left:none}.tree-line .el-tree-node__expand-icon{font-size:18px;color:#000}.tree-line .el-tree-node__expand-icon.is-leaf{color:transparent}

View File

@ -1 +0,0 @@
.not-show-tab-label .el-tabs__header{display:none}.el-descriptions__body{background:#f0f0f0}.not-show-tab-search{display:none}.el-table__body-wrapper{margin-bottom:4px;padding-bottom:2px}.el-table__body-wrapper::-webkit-scrollbar{width:8px;height:8px}.el-table__body-wrapper::-webkit-scrollbar-track{border-radius:10px;-webkit-box-shadow:inset 0 0 6px hsla(0,0%,93.3%,.3);background-color:#eee}.el-table__body-wrapper::-webkit-scrollbar-thumb{border-radius:10px;-webkit-box-shadow:inset 0 0 6px rgba(145,143,143,.3);background-color:#918f8f}.input-with-select .el-input-group__prepend{background-color:#fff}.daterange-box .select .el-input__inner{border-top-right-radius:0;border-bottom-right-radius:0}.daterange-box .daterange.el-input__inner{border-top-left-radius:0;border-bottom-left-radius:0;vertical-align:bottom}[data-v-e9f58da4] .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{background-color:#409eff!important;color:#fff}

View File

@ -1 +0,0 @@
.left-nav-home-bar{background:#2c3759!important;overflow:hidden;text-overflow:ellipsis}.left-nav-home-bar,.left-nav-home-bar i{color:#fff!important}.el-submenu .el-menu-item{height:40px;line-height:40px;width:auto;min-width:60px;padding:0 10px 0 25px!important;text-overflow:ellipsis;overflow:hidden}.el-menu .el-submenu__title{height:46px;line-height:46px;padding-left:10px!important;text-overflow:ellipsis;overflow:hidden}.left-nav-home-bar i{margin-bottom:6px!important}.el-menu-item-group__title{padding:0 0 0 10px}.el-menu--collapse .el-menu-item-group__title,.el-menu--collapse .el-submenu__title{padding-left:20px!important}.el-menu-item i,.el-submenu__title i{margin-top:-4px;vertical-align:middle;margin:-3px 5px 0 0;right:1px}.head-left[data-v-b2941c10],.head-right[data-v-b2941c10]{display:flex;justify-content:center;flex-direction:column}.head-right[data-v-b2941c10]{align-items:flex-end}.el-upload{height:100px;width:100px;background:#eee;overflow:hidden}.el-upload img[data-v-3b5105e6]{height:100%;width:100%;-o-object-fit:cover;object-fit:cover;display:block}.el-upload i[data-v-3b5105e6]{font-size:40px;margin:30% 31%;display:block}.custom-tree-node[data-v-3b5105e6]{font-size:14px;padding-right:8px}.info-descriptions[data-v-4d4566fc] .el-descriptions__body .el-descriptions__label{min-width:90px;text-align:right;background:transparent;color:#606266;font-weight:400}.el-descriptions .is-bordered th[data-v-4d4566fc],.info-descriptions[data-v-4d4566fc] .el-descriptions .is-bordered td{border:transparent;max-width:25vw}.tree-line .el-tree-node{position:relative;padding-left:16px}.tree-line .el-tree-node__content{line-height:18px;font-size:14px}.tree-line .el-tree-node__children{padding-left:16px}.tree-line .el-tree-node:before{content:"";height:100%;width:1px;position:absolute;left:-3px;top:-26px;border-width:1px;border-left:1px dashed #52627c}.tree-line .el-tree-node:last-child:before{height:38px}.tree-line .el-tree-node:after{content:"";width:24px;height:20px;position:absolute;left:-3px;top:12px;border-width:1px;border-top:1px dashed #52627c}.tree-line>.el-tree-node:after{border-top:none}.tree-line>.el-tree-node:before{border-left:none}.tree-line .el-tree-node__expand-icon{font-size:18px;color:#000}.tree-line .el-tree-node__expand-icon.is-leaf{color:transparent}.dialog-box .el-descriptions__header{margin:20px 0 5px}.dialog-box .el-descriptions__body{background:#fff}.textarea-box *{word-break:break-all;white-space:pre-wrap}.textarea-box table{width:100%!important}.textarea-box img{max-width:80%!important}.textarea-box::-webkit-scrollbar-thumb{height:5px;background-color:rgba(0,0,0,.2)!important}.el-dialog{margin:auto!important;top:50%;transform:translateY(-50%)}.el-dialog-div{height:75vh;overflow:auto}.el-dialog__body{padding-top:15px;padding-bottom:45px}.el-dialog-div .el-tabs__header{position:absolute;left:1px;top:69px;width:calc(90vw - 42px);margin:0 20px;z-index:1}.el-dialog-div .el-tabs__content{padding-top:50px}.el-dialog-div .el-affix--fixed{bottom:20vh}.el-dialog-div .el-affix--fixed .el-form-item{padding:0!important;background:transparent!important}

File diff suppressed because one or more lines are too long

View File

@ -1 +0,0 @@
.full-screen-container[data-v-12e6b782]{z-index:10000}.not-show-tab-label .el-tabs__header{display:none}.el-descriptions__body{background:#f0f0f0}.not-show-tab-search{display:none}.el-table__body-wrapper{margin-bottom:4px;padding-bottom:2px}.el-table__body-wrapper::-webkit-scrollbar{width:8px;height:8px}.el-table__body-wrapper::-webkit-scrollbar-track{border-radius:10px;-webkit-box-shadow:inset 0 0 6px hsla(0,0%,93.3%,.3);background-color:#eee}.el-table__body-wrapper::-webkit-scrollbar-thumb{border-radius:10px;-webkit-box-shadow:inset 0 0 6px rgba(145,143,143,.3);background-color:#918f8f}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

View File

@ -1,3 +0,0 @@
<!DOCTYPE html><html lang=""><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="favicon.ico"><script src="js/manage.js"></script><script src="https://api.map.baidu.com/api?v=2.0&ak=bF4Y6tQg94hV2vesn2ZIaUIXO4aRxxRk"></script><title></title><style>body{
margin: 0px;
}</style><link href="css/chunk-0de923e9.c4e8272a.css" rel="prefetch"><link href="css/chunk-1a458102.466135f0.css" rel="prefetch"><link href="css/chunk-291edee4.508cb3c8.css" rel="prefetch"><link href="css/chunk-4aefa5ec.fcc75990.css" rel="prefetch"><link href="css/chunk-4f81d902.91f1ef17.css" rel="prefetch"><link href="css/chunk-856f3c38.9b9508b8.css" rel="prefetch"><link href="css/chunk-e3f8e5a6.7876554f.css" rel="prefetch"><link href="js/chunk-0de923e9.1f0fca7e.js" rel="prefetch"><link href="js/chunk-1a458102.9a54e9ae.js" rel="prefetch"><link href="js/chunk-25ddb50b.55ec750b.js" rel="prefetch"><link href="js/chunk-291edee4.e8dbe8c8.js" rel="prefetch"><link href="js/chunk-4aefa5ec.c237610d.js" rel="prefetch"><link href="js/chunk-4f81d902.c5fdb7dd.js" rel="prefetch"><link href="js/chunk-7ea17297.38d572ef.js" rel="prefetch"><link href="js/chunk-856f3c38.29c2fcc0.js" rel="prefetch"><link href="js/chunk-e3f8e5a6.ff58e6f8.js" rel="prefetch"><link href="js/chunk-e624c1ca.62513cbc.js" rel="prefetch"><link href="css/app.abfb5de2.css" rel="preload" as="style"><link href="js/app.25e49e88.js" rel="preload" as="script"><link href="css/app.abfb5de2.css" rel="stylesheet"></head><body><noscript><strong>We're sorry but hotime doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id="app"></div><script src="js/app.25e49e88.js"></script></body></html>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +0,0 @@
(window.webpackJsonp=window.webpackJsonp||[]).push([["chunk-0de923e9"],{"578a":function(o,n,t){"use strict";t.r(n);t("b0c0");var i=t("f2bf"),s={class:"login-item"},r={class:"right-content"},u={class:"login-title"},l={style:{height:"60px"}},d=Object(i.r)(" 账号:"),b=Object(i.r)(" 密码:");var e=t("2934"),c={name:"Login",data:function(){return{showLog:!1,showLogInfo:"",label:"HoTime DashBoard",form:{name:"",password:""},backgroundImage:window.Hotime.data.name+"/hotime/wallpaper?random=1&type=1",focusName:!1,focusPassword:!1}},methods:{login:function(){var n=this;if(""==this.name||""==this.password)return this.showLogInfo="参数不足!",void(this.showLog=!0);Object(e.a)(window.Hotime.data.name+"/hotime/login",n.form).then(function(o){if(0!=o.status)return n.showLogInfo=o.error.msg,void(n.showLog=!0);location.hash="#/",location.reload()})},getBgImg:function(){var n=this;Object(e.e)(window.Hotime.data.name+"/hotime/wallpaper?random=1").then(function(o){0==o.status&&(n.backgroundImage=o.result.url)})},focusPrice:function(o){this["focus"+o]=!0},blurPrice:function(o){this["focus"+o]=!1}},mounted:function(){var n=this;this.label=window.Hotime.data.label,document.onkeydown=function(o){o=window.event||o;13==(o.keyCode||o.which||o.charCode)&&n.login()}}},a=(t("fad9"),t("6b0d")),t=t.n(a);n.default=t()(c,[["render",function(o,n,t,e,c,a){return Object(i.L)(),Object(i.n)("div",{class:"login",style:Object(i.C)({width:"100%",height:"100vh","background-image":"url("+c.backgroundImage+")"})},[Object(i.o)("div",s,[Object(i.o)("div",r,[Object(i.o)("p",u,Object(i.Y)(c.label),1),Object(i.o)("div",l,[Object(i.lb)(Object(i.o)("p",{class:"errorMsg"},Object(i.Y)(c.showLogInfo),513),[[i.hb,c.showLog]])]),Object(i.o)("p",{class:Object(i.B)(["inputWrap",{inputFocus:c.focusName}])},[d,Object(i.lb)(Object(i.o)("input",{type:"text","onUpdate:modelValue":n[0]||(n[0]=function(o){return c.form.name=o}),class:"accountVal",onKeyup:n[1]||(n[1]=Object(i.mb)(function(){return a.login&&a.login.apply(a,arguments)},["enter"])),onFocus:n[2]||(n[2]=function(o){return a.focusPrice("Name")}),onBlur:n[3]||(n[3]=function(o){return a.blurPrice("Name")})},null,544),[[i.gb,c.form.name]])],2),Object(i.o)("p",{class:Object(i.B)(["inputWrap",{inputFocus:c.focusPassword}])},[b,Object(i.lb)(Object(i.o)("input",{type:"password","onUpdate:modelValue":n[4]||(n[4]=function(o){return c.form.password=o}),class:"passwordVal",onKeyup:n[5]||(n[5]=Object(i.mb)(function(){return a.login&&a.login.apply(a,arguments)},["enter"])),onFocus:n[6]||(n[6]=function(o){return a.focusPrice("Password")}),onBlur:n[7]||(n[7]=function(o){return a.blurPrice("Password")})},null,544),[[i.gb,c.form.password]])],2),Object(i.o)("p",{class:"login-btn",onClick:n[8]||(n[8]=function(){return a.login&&a.login.apply(a,arguments)})},"登录")])])],4)}],["__scopeId","data-v-c08f3364"]])},dbeb:function(o,n,t){},fad9:function(o,n,t){"use strict";t("dbeb")}}]);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +0,0 @@
(window.webpackJsonp=window.webpackJsonp||[]).push([["chunk-25ddb50b"],{"107c":function(t,e,n){var r=n("d039"),c=n("da84").RegExp;t.exports=r(function(){var t=c("(?<a>b)","g");return"b"!==t.exec("b").groups.a||"bc"!=="b".replace(t,"$<a>c")})},"129f":function(t,e){t.exports=Object.is||function(t,e){return t===e?0!==t||1/t==1/e:t!=t&&e!=e}},"14c3":function(t,e,n){var r=n("c6b6"),c=n("9263");t.exports=function(t,e){var n=t.exec;if("function"==typeof n){n=n.call(t,e);if("object"!=typeof n)throw TypeError("RegExp exec method returned something other than an Object or null");return n}if("RegExp"!==r(t))throw TypeError("RegExp#exec called on incompatible receiver");return c.call(t,e)}},"159b":function(t,e,n){var r,c=n("da84"),i=n("fdbc"),o=n("17c2"),a=n("9112");for(r in i){var l=c[r],l=l&&l.prototype;if(l&&l.forEach!==o)try{a(l,"forEach",o)}catch(t){l.forEach=o}}},"17c2":function(t,e,n){"use strict";var r=n("b727").forEach,n=n("a640")("forEach");t.exports=n?[].forEach:function(t){return r(this,t,1<arguments.length?arguments[1]:void 0)}},"83c5":function(t,e,n){"use strict";n("159b");e.a={list:{},constructor:function(){this.list={}},$on:function(t,e){this.list[t]=this.list[t]||[],this.list[t].push(e)},$emit:function(t,e){this.list[t]&&this.list[t].forEach(function(t){t(e)})},$off:function(t){this.list[t]&&delete this.list[t]}}},"841c":function(t,e,n){"use strict";var r=n("d784"),o=n("825a"),a=n("1d80"),l=n("129f"),s=n("577e"),u=n("14c3");r("search",function(r,c,i){return[function(t){var e=a(this),n=null==t?void 0:t[r];return void 0!==n?n.call(t,e):new RegExp(t)[r](s(e))},function(t){var e=o(this),t=s(t),n=i(c,e,t);if(n.done)return n.value;n=e.lastIndex,l(n,0)||(e.lastIndex=0),t=u(e,t);return l(e.lastIndex,n)||(e.lastIndex=n),null===t?-1:t.index}]})},9263:function(t,e,n){"use strict";var r,p=n("577e"),h=n("ad6d"),c=n("9f7f"),i=n("5692"),g=n("7c73"),v=n("69f3").get,o=n("fce3"),n=n("107c"),E=RegExp.prototype.exec,b=i("native-string-replace",String.prototype.replace),I=E,R=(i=/a/,r=/b*/g,E.call(i,"a"),E.call(r,"a"),0!==i.lastIndex||0!==r.lastIndex),y=c.UNSUPPORTED_Y||c.BROKEN_CARET,w=void 0!==/()??/.exec("")[1];(R||w||y||o||n)&&(I=function(t){var e,n,r,c,i,o,a=this,l=v(a),t=p(t),s=l.raw;if(s)return s.lastIndex=a.lastIndex,f=I.call(s,t),a.lastIndex=s.lastIndex,f;var u=l.groups,s=y&&a.sticky,f=h.call(a),l=a.source,d=0,x=t;if(s&&(-1===(f=f.replace("y","")).indexOf("g")&&(f+="g"),x=t.slice(a.lastIndex),0<a.lastIndex&&(!a.multiline||a.multiline&&"\n"!==t.charAt(a.lastIndex-1))&&(l="(?: "+l+")",x=" "+x,d++),e=new RegExp("^(?:"+l+")",f)),w&&(e=new RegExp("^"+l+"$(?!\\s)",f)),R&&(n=a.lastIndex),r=E.call(s?e:a,x),s?r?(r.input=r.input.slice(d),r[0]=r[0].slice(d),r.index=a.lastIndex,a.lastIndex+=r[0].length):a.lastIndex=0:R&&r&&(a.lastIndex=a.global?r.index+r[0].length:n),w&&r&&1<r.length&&b.call(r[0],e,function(){for(c=1;c<arguments.length-2;c++)void 0===arguments[c]&&(r[c]=void 0)}),r&&u)for(r.groups=i=g(null),c=0;c<u.length;c++)i[(o=u[c])[0]]=r[o[1]];return r}),t.exports=I},"9f7f":function(t,e,n){var r=n("d039"),c=n("da84").RegExp;e.UNSUPPORTED_Y=r(function(){var t=c("a","y");return t.lastIndex=2,null!=t.exec("abcd")}),e.BROKEN_CARET=r(function(){var t=c("^r","gy");return t.lastIndex=2,null!=t.exec("str")})},ac1f:function(t,e,n){"use strict";var r=n("23e7"),n=n("9263");r({target:"RegExp",proto:!0,forced:/./.exec!==n},{exec:n})},ad6d:function(t,e,n){"use strict";var r=n("825a");t.exports=function(){var t=r(this),e="";return t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.sticky&&(e+="y"),e}},d784:function(t,e,n){"use strict";n("ac1f");var l=n("6eeb"),s=n("9263"),u=n("d039"),f=n("b622"),d=n("9112"),x=f("species"),p=RegExp.prototype;t.exports=function(n,t,e,r){var o,c=f(n),a=!u(function(){var t={};return t[c]=function(){return 7},7!=""[n](t)}),i=a&&!u(function(){var t=!1,e=/a/;return"split"===n&&((e={constructor:{}}).constructor[x]=function(){return e},e.flags="",e[c]=/./[c]),e.exec=function(){return t=!0,null},e[c](""),!t});a&&i&&!e||(o=/./[c],i=t(c,""[n],function(t,e,n,r,c){var i=e.exec;return i===s||i===p.exec?a&&!c?{done:!0,value:o.call(e,n,r)}:{done:!0,value:t.call(n,e,r)}:{done:!1}}),l(String.prototype,n,i[0]),l(p,c,i[1])),r&&d(p[c],"sham",!0)}},fce3:function(t,e,n){var r=n("d039"),c=n("da84").RegExp;t.exports=r(function(){var t=c(".","s");return!(t.dotAll&&t.exec("\n")&&"s"===t.flags)})}}]);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +0,0 @@
(window.webpackJsonp=window.webpackJsonp||[]).push([["chunk-e624c1ca"],{"4de4":function(t,n,r){"use strict";var e=r("23e7"),o=r("b727").filter;e({target:"Array",proto:!0,forced:!r("1dde")("filter")},{filter:function(t){return o(this,t,1<arguments.length?arguments[1]:void 0)}})},a640:function(t,n,r){"use strict";var e=r("d039");t.exports=function(t,n){var r=[][t];return!!r&&e(function(){r.call(null,n||function(){throw 1},1)})}}}]);

View File

@ -1,13 +0,0 @@
/*
* Copyright (c) 2022/7/23 下午7:22
* AuthorHoTeas
*/
// eslint-disable-next-line no-unused-vars
var Hotime = {
vueComponent: {},
mapData: {},
pageRow:20,
tableMapData: {},
tableName:"admin"
}

View File

@ -1,784 +0,0 @@
package main
import (
"database/sql"
"fmt"
"log"
// 实际使用时请替换为正确的导入路径
// "code.hoteas.com/golang/hotime/cache"
// "code.hoteas.com/golang/hotime/common"
// "code.hoteas.com/golang/hotime/db"
"code.hoteas.com/golang/hotime/cache"
"code.hoteas.com/golang/hotime/common"
"code.hoteas.com/golang/hotime/db"
_ "github.com/go-sql-driver/mysql"
"github.com/sirupsen/logrus"
)
// HoTimeDB使用示例代码集合 - 修正版
// 本文件包含了各种常见场景的完整示例代码,所有条件查询语法已修正
// 示例1: 基本初始化和配置
func Example1_BasicSetup() {
// 创建数据库实例
database := &db.HoTimeDB{
Prefix: "app_", // 设置表前缀
Mode: 2, // 开发模式输出SQL日志
Type: "mysql", // 数据库类型
}
// 设置日志
logger := logrus.New()
database.Log = logger
// 设置连接函数
database.SetConnect(func(err ...*common.Error) (master, slave *sql.DB) {
// 主数据库连接
master, dbErr := sql.Open("mysql", "root:password@tcp(localhost:3306)/testdb?charset=utf8&parseTime=true")
if dbErr != nil {
log.Fatal("数据库连接失败:", dbErr)
}
// 从数据库连接(可选,用于读写分离)
slave = master // 这里使用同一个连接,实际项目中可以连接到从库
return master, slave
})
fmt.Println("数据库初始化完成")
}
// 示例2: 基本CRUD操作修正版
func Example2_BasicCRUD_Fixed(db *db.HoTimeDB) {
// 创建用户
fmt.Println("=== 创建用户 ===")
userId := db.Insert("user", common.Map{
"name": "张三",
"email": "zhangsan@example.com",
"age": 25,
"status": 1,
"balance": 1000.50,
"created_time[#]": "NOW()",
})
fmt.Printf("新用户ID: %d\n", userId)
// 查询用户单条件可以不用AND
fmt.Println("\n=== 查询用户 ===")
user := db.Get("user", "*", common.Map{
"id": userId,
})
if user != nil {
fmt.Printf("用户信息: %+v\n", user)
}
// 更新用户多条件必须用AND包装
fmt.Println("\n=== 更新用户 ===")
affected := db.Update("user", common.Map{
"name": "李四",
"age": 26,
"updated_time[#]": "NOW()",
}, common.Map{
"AND": common.Map{
"id": userId,
"status": 1, // 确保只更新正常状态的用户
},
})
fmt.Printf("更新记录数: %d\n", affected)
// 软删除用户
fmt.Println("\n=== 软删除用户 ===")
affected = db.Update("user", common.Map{
"deleted_at[#]": "NOW()",
"status": 0,
}, common.Map{
"id": userId, // 单条件不需要AND
})
fmt.Printf("软删除记录数: %d\n", affected)
}
// 示例3: 条件查询语法(修正版)
func Example3_ConditionQuery_Fixed(db *db.HoTimeDB) {
fmt.Println("=== 条件查询语法示例 ===")
// ✅ 正确:单个条件
users1 := db.Select("user", "*", common.Map{
"status": 1,
})
fmt.Printf("活跃用户: %d个\n", len(users1))
// ✅ 正确多个条件用AND包装
users2 := db.Select("user", "*", common.Map{
"AND": common.Map{
"status": 1,
"age[>]": 18,
"age[<=]": 60,
},
})
fmt.Printf("活跃的成年用户: %d个\n", len(users2))
// ✅ 正确OR条件
users3 := db.Select("user", "*", common.Map{
"OR": common.Map{
"level": "vip",
"balance[>]": 5000,
},
})
fmt.Printf("VIP或高余额用户: %d个\n", len(users3))
// ✅ 正确:条件 + 特殊参数
users4 := db.Select("user", "*", common.Map{
"AND": common.Map{
"status": 1,
"age[>=]": 18,
},
"ORDER": "created_time DESC",
"LIMIT": 10,
})
fmt.Printf("最近的活跃成年用户: %d个\n", len(users4))
// ✅ 正确:复杂嵌套条件
users5 := db.Select("user", "*", common.Map{
"AND": common.Map{
"status": 1,
"OR": common.Map{
"age[<]": 30,
"level": "vip",
},
},
"ORDER": []string{"level DESC", "created_time DESC"},
"LIMIT": []int{0, 20},
})
fmt.Printf("年轻或VIP的活跃用户: %d个\n", len(users5))
// ✅ 正确:模糊查询
users6 := db.Select("user", "*", common.Map{
"AND": common.Map{
"name[~]": "张", // 姓名包含"张"
"email[~!]": "gmail", // 邮箱以gmail开头
"status": 1,
},
})
fmt.Printf("姓张的gmail活跃用户: %d个\n", len(users6))
// ✅ 正确:范围查询
users7 := db.Select("user", "*", common.Map{
"AND": common.Map{
"age[<>]": []int{18, 35}, // 年龄在18-35之间
"balance[><]": []float64{0, 100}, // 余额不在0-100之间
"status": 1,
},
})
fmt.Printf("18-35岁且余额>100的活跃用户: %d个\n", len(users7))
// ✅ 正确IN查询
users8 := db.Select("user", "*", common.Map{
"AND": common.Map{
"id": []int{1, 2, 3, 4, 5}, // ID在指定范围内
"status[!]": []int{0, -1}, // 状态不为0或-1
},
})
fmt.Printf("指定ID的活跃用户: %d个\n", len(users8))
}
// 示例4: 链式查询操作(正确版)
func Example4_ChainQuery_Fixed(db *db.HoTimeDB) {
fmt.Println("=== 链式查询示例 ===")
// 链式查询链式语法允许单独的Where然后用And添加更多条件
users := db.Table("user").
Where("status", 1). // 链式中可以单独Where
And("age[>=]", 18). // 然后用And添加条件
And("age[<=]", 60). // 再添加条件
Or(common.Map{ // 或者用Or添加OR条件组
"level": "vip",
"balance[>]": 5000,
}).
Order("created_time DESC", "id ASC"). // 排序
Limit(0, 10). // 限制结果
Select("id,name,email,age,balance,level")
fmt.Printf("链式查询到 %d 个用户\n", len(users))
for i, user := range users {
fmt.Printf("用户%d: %s (年龄:%v, 余额:%v)\n",
i+1,
user.GetString("name"),
user.Get("age"),
user.Get("balance"))
}
// 链式统计查询
count := db.Table("user").
Where("status", 1).
And("age[>=]", 18).
Count()
fmt.Printf("符合条件的用户总数: %d\n", count)
}
// 示例5: JOIN查询操作修正版
func Example5_JoinQuery_Fixed(db *db.HoTimeDB) {
fmt.Println("=== JOIN查询示例 ===")
// 链式JOIN查询
orders := db.Table("order").
LeftJoin("user", "order.user_id = user.id").
LeftJoin("product", "order.product_id = product.id").
Where("order.status", "paid"). // 链式中单个条件可以直接Where
And("order.created_time[>]", "2023-01-01"). // 用And添加更多条件
Order("order.created_time DESC").
Select(`
order.id as order_id,
order.amount,
order.status,
order.created_time,
user.name as user_name,
user.email as user_email,
product.title as product_title,
product.price as product_price
`)
fmt.Printf("链式JOIN查询到 %d 个订单\n", len(orders))
for _, order := range orders {
fmt.Printf("订单ID:%v, 用户:%s, 商品:%s, 金额:%v\n",
order.Get("order_id"),
order.GetString("user_name"),
order.GetString("product_title"),
order.Get("amount"))
}
// 传统JOIN语法多个条件必须用AND包装
orders2 := db.Select("order",
common.Slice{
common.Map{"[>]user": "order.user_id = user.id"},
common.Map{"[>]product": "order.product_id = product.id"},
},
"order.*, user.name as user_name, product.title as product_title",
common.Map{
"AND": common.Map{
"order.status": "paid",
"order.created_time[>]": "2023-01-01",
},
})
fmt.Printf("传统JOIN语法查询到 %d 个订单\n", len(orders2))
}
// 示例6: 分页查询(修正版)
func Example6_PaginationQuery_Fixed(db *db.HoTimeDB) {
fmt.Println("=== 分页查询示例 ===")
page := 2
pageSize := 10
// 获取总数(单条件)
total := db.Count("user", common.Map{
"AND": common.Map{
"status": 1,
"deleted_at": nil,
},
})
// 分页数据(链式方式)
users := db.Table("user").
Where("status", 1).
And("deleted_at", nil).
Order("created_time DESC").
Page(page, pageSize).
Select("id,name,email,created_time")
// 使用传统方式的分页查询
users2 := db.Page(page, pageSize).PageSelect("user", "*", common.Map{
"AND": common.Map{
"status": 1,
"deleted_at": nil,
},
"ORDER": "created_time DESC",
})
// 计算分页信息
totalPages := (total + pageSize - 1) / pageSize
offset := (page - 1) * pageSize
fmt.Printf("总记录数: %d\n", total)
fmt.Printf("总页数: %d\n", totalPages)
fmt.Printf("当前页: %d\n", page)
fmt.Printf("每页大小: %d\n", pageSize)
fmt.Printf("偏移量: %d\n", offset)
fmt.Printf("链式查询当前页记录数: %d\n", len(users))
fmt.Printf("传统查询当前页记录数: %d\n", len(users2))
for i, user := range users {
fmt.Printf(" %d. %s (%s) - %v\n",
offset+i+1,
user.GetString("name"),
user.GetString("email"),
user.Get("created_time"))
}
}
// 示例7: 聚合函数查询(修正版)
func Example7_AggregateQuery_Fixed(db *db.HoTimeDB) {
fmt.Println("=== 聚合函数查询示例 ===")
// 基本统计
userCount := db.Count("user")
activeUserCount := db.Count("user", common.Map{"status": 1})
totalBalance := db.Sum("user", "balance", common.Map{"status": 1})
fmt.Printf("总用户数: %d\n", userCount)
fmt.Printf("活跃用户数: %d\n", activeUserCount)
fmt.Printf("活跃用户总余额: %.2f\n", totalBalance)
// 分组统计(正确语法)
stats := db.Select("user",
"level, COUNT(*) as user_count, AVG(age) as avg_age, SUM(balance) as total_balance",
common.Map{
"status": 1, // 单条件不需要AND
"GROUP": "level",
"ORDER": "user_count DESC",
})
fmt.Println("\n按等级分组统计:")
for _, stat := range stats {
fmt.Printf("等级:%v, 用户数:%v, 平均年龄:%v, 总余额:%v\n",
stat.Get("level"),
stat.Get("user_count"),
stat.Get("avg_age"),
stat.Get("total_balance"))
}
// 关联统计(修正版)
orderStats := db.Select("order",
common.Slice{
common.Map{"[>]user": "order.user_id = user.id"},
},
"user.level, COUNT(order.id) as order_count, SUM(order.amount) as total_amount",
common.Map{
"AND": common.Map{
"order.status": "paid",
"order.created_time[>]": "2023-01-01",
},
"GROUP": "user.level",
"ORDER": "total_amount DESC",
})
fmt.Println("\n用户等级订单统计:")
for _, stat := range orderStats {
fmt.Printf("等级:%v, 订单数:%v, 总金额:%v\n",
stat.Get("level"),
stat.Get("order_count"),
stat.Get("total_amount"))
}
}
// 示例8: 事务处理(修正版)
func Example8_Transaction_Fixed(db *db.HoTimeDB) {
fmt.Println("=== 事务处理示例 ===")
// 模拟转账操作
fromUserId := int64(1)
toUserId := int64(2)
amount := 100.0
success := db.Action(func(tx db.HoTimeDB) bool {
// 检查转出账户余额(单条件)
fromUser := tx.Get("user", "balance", common.Map{"id": fromUserId})
if fromUser == nil {
fmt.Println("转出用户不存在")
return false
}
fromBalance := fromUser.GetFloat64("balance")
if fromBalance < amount {
fmt.Println("余额不足")
return false
}
// 扣减转出账户余额多条件必须用AND
affected1 := tx.Update("user", common.Map{
"balance[#]": fmt.Sprintf("balance - %.2f", amount),
"updated_time[#]": "NOW()",
}, common.Map{
"AND": common.Map{
"id": fromUserId,
"balance[>=]": amount, // 再次确保余额足够
},
})
if affected1 == 0 {
fmt.Println("扣减余额失败")
return false
}
// 增加转入账户余额(单条件)
affected2 := tx.Update("user", common.Map{
"balance[#]": fmt.Sprintf("balance + %.2f", amount),
"updated_time[#]": "NOW()",
}, common.Map{
"id": toUserId,
})
if affected2 == 0 {
fmt.Println("增加余额失败")
return false
}
// 记录转账日志
logId := tx.Insert("transfer_log", common.Map{
"from_user_id": fromUserId,
"to_user_id": toUserId,
"amount": amount,
"status": "success",
"created_time[#]": "NOW()",
})
if logId == 0 {
fmt.Println("记录日志失败")
return false
}
fmt.Printf("转账成功: 用户%d -> 用户%d, 金额:%.2f\n", fromUserId, toUserId, amount)
return true
})
if success {
fmt.Println("事务执行成功")
} else {
fmt.Println("事务回滚")
if db.LastErr.GetError() != nil {
fmt.Println("错误原因:", db.LastErr.GetError())
}
}
}
// 示例9: 缓存机制(修正版)
func Example9_CacheSystem_Fixed(db *db.HoTimeDB) {
fmt.Println("=== 缓存机制示例 ===")
// 设置缓存(实际项目中需要配置缓存参数)
db.HoTimeCache = &cache.HoTimeCache{}
// 第一次查询(会缓存结果)
fmt.Println("第一次查询(会缓存)...")
users1 := db.Select("user", "*", common.Map{
"status": 1, // 单条件
"LIMIT": 10,
})
fmt.Printf("查询到 %d 个用户\n", len(users1))
// 第二次相同查询(从缓存获取)
fmt.Println("第二次相同查询(从缓存获取)...")
users2 := db.Select("user", "*", common.Map{
"status": 1, // 单条件
"LIMIT": 10,
})
fmt.Printf("查询到 %d 个用户\n", len(users2))
// 更新操作会清除缓存
fmt.Println("执行更新操作(会清除缓存)...")
affected := db.Update("user", common.Map{
"updated_time[#]": "NOW()",
}, common.Map{
"id": 1, // 单条件
})
fmt.Printf("更新 %d 条记录\n", affected)
// 再次查询(重新从数据库获取并缓存)
fmt.Println("更新后再次查询(重新缓存)...")
users3 := db.Select("user", "*", common.Map{
"status": 1, // 单条件
"LIMIT": 10,
})
fmt.Printf("查询到 %d 个用户\n", len(users3))
}
// 示例10: 性能优化技巧(修正版)
func Example10_PerformanceOptimization_Fixed(db *db.HoTimeDB) {
fmt.Println("=== 性能优化技巧示例 ===")
// IN查询优化连续数字自动转为BETWEEN
fmt.Println("IN查询优化示例...")
users := db.Select("user", "*", common.Map{
"id": []int{1, 2, 3, 4, 5, 10, 11, 12, 13, 20}, // 单个IN条件会被优化
})
fmt.Printf("查询到 %d 个用户\n", len(users))
fmt.Println("执行的SQL:", db.LastQuery)
// 批量插入(使用事务)
fmt.Println("\n批量插入示例...")
success := db.Action(func(tx db.HoTimeDB) bool {
for i := 1; i <= 100; i++ {
id := tx.Insert("user_batch", common.Map{
"name": fmt.Sprintf("批量用户%d", i),
"email": fmt.Sprintf("batch%d@example.com", i),
"status": 1,
"created_time[#]": "NOW()",
})
if id == 0 {
return false
}
// 每10个用户输出一次进度
if i%10 == 0 {
fmt.Printf("已插入 %d 个用户\n", i)
}
}
return true
})
if success {
fmt.Println("批量插入完成")
} else {
fmt.Println("批量插入失败")
}
// 索引友好的查询(修正版)
fmt.Println("\n索引友好的查询...")
recentUsers := db.Select("user", "*", common.Map{
"AND": common.Map{
"created_time[>]": "2023-01-01", // 假设created_time有索引
"status": 1, // 假设status有索引
},
"ORDER": "created_time DESC", // 利用索引排序
"LIMIT": 20,
})
fmt.Printf("查询到 %d 个近期用户\n", len(recentUsers))
}
// 完整的应用示例(修正版)
func CompleteExample_Fixed() {
fmt.Println("=== HoTimeDB完整应用示例修正版 ===")
// 初始化数据库
database := &db.HoTimeDB{
Prefix: "app_",
Mode: 1, // 测试模式
Type: "mysql",
}
// 设置连接
database.SetConnect(func(err ...*common.Error) (master, slave *sql.DB) {
// 这里使用实际的数据库连接字符串
dsn := "root:password@tcp(localhost:3306)/testdb?charset=utf8mb4&parseTime=True&loc=Local"
master, dbErr := sql.Open("mysql", dsn)
if dbErr != nil {
log.Fatal("数据库连接失败:", dbErr)
}
return master, master
})
// 用户管理系统示例
fmt.Println("\n=== 用户管理系统 ===")
// 1. 创建用户
userId := database.Insert("user", common.Map{
"name": "示例用户",
"email": "example@test.com",
"password": "hashed_password",
"age": 28,
"status": 1,
"level": "normal",
"balance": 500.00,
"created_time[#]": "NOW()",
})
fmt.Printf("创建用户成功ID: %d\n", userId)
// 2. 用户登录更新多条件用AND
database.Update("user", common.Map{
"last_login[#]": "NOW()",
"login_count[#]": "login_count + 1",
}, common.Map{
"AND": common.Map{
"id": userId,
"status": 1,
},
})
// 3. 创建订单
orderId := database.Insert("order", common.Map{
"user_id": userId,
"amount": 299.99,
"status": "pending",
"created_time[#]": "NOW()",
})
fmt.Printf("创建订单成功ID: %d\n", orderId)
// 4. 订单支付(使用事务,修正版)
paymentSuccess := database.Action(func(tx db.HoTimeDB) bool {
// 更新订单状态(单条件)
affected1 := tx.Update("order", common.Map{
"status": "paid",
"paid_time[#]": "NOW()",
}, common.Map{
"id": orderId,
})
if affected1 == 0 {
return false
}
// 扣减用户余额多条件用AND
affected2 := tx.Update("user", common.Map{
"balance[#]": "balance - 299.99",
}, common.Map{
"AND": common.Map{
"id": userId,
"balance[>=]": 299.99, // 确保余额足够
},
})
if affected2 == 0 {
fmt.Println("余额不足或用户不存在")
return false
}
// 记录支付日志
logId := tx.Insert("payment_log", common.Map{
"user_id": userId,
"order_id": orderId,
"amount": 299.99,
"type": "order_payment",
"status": "success",
"created_time[#]": "NOW()",
})
return logId > 0
})
if paymentSuccess {
fmt.Println("订单支付成功")
} else {
fmt.Println("订单支付失败")
}
// 5. 查询用户订单列表(链式查询)
userOrders := database.Table("order").
LeftJoin("user", "order.user_id = user.id").
Where("order.user_id", userId). // 链式中单个条件可以直接Where
Order("order.created_time DESC").
Select(`
order.id,
order.amount,
order.status,
order.created_time,
order.paid_time,
user.name as user_name
`)
fmt.Printf("\n用户订单列表 (%d个订单):\n", len(userOrders))
for _, order := range userOrders {
fmt.Printf(" 订单ID:%v, 金额:%v, 状态:%s, 创建时间:%v\n",
order.Get("id"),
order.Get("amount"),
order.GetString("status"),
order.Get("created_time"))
}
// 6. 生成统计报表(修正版)
stats := database.Select("order",
common.Slice{
common.Map{"[>]user": "order.user_id = user.id"},
},
`
DATE(order.created_time) as date,
COUNT(order.id) as order_count,
SUM(order.amount) as total_amount,
AVG(order.amount) as avg_amount
`,
common.Map{
"AND": common.Map{
"order.status": "paid",
"order.created_time[>]": "2023-01-01",
},
"GROUP": "DATE(order.created_time)",
"ORDER": "date DESC",
"LIMIT": 30,
})
fmt.Printf("\n最近30天订单统计:\n")
for _, stat := range stats {
fmt.Printf("日期:%v, 订单数:%v, 总金额:%v, 平均金额:%v\n",
stat.Get("date"),
stat.Get("order_count"),
stat.Get("total_amount"),
stat.Get("avg_amount"))
}
fmt.Println("\n示例执行完成")
}
// 语法对比示例
func SyntaxComparison() {
fmt.Println("=== HoTimeDB语法对比 ===")
// 模拟数据库对象
var db *db.HoTimeDB
fmt.Println("❌ 错误语法示例(不支持):")
fmt.Println(`
// 这样写是错误的多个条件不能直接放在根Map中
wrongUsers := db.Select("user", "*", common.Map{
"status": 1, // ❌ 错误
"age[>]": 18, // ❌ 错误
"ORDER": "id DESC",
})
`)
fmt.Println("✅ 正确语法示例:")
fmt.Println(`
// 单个条件可以直接写
correctUsers1 := db.Select("user", "*", common.Map{
"status": 1, // ✅ 正确,单个条件
})
// 多个条件必须用AND包装
correctUsers2 := db.Select("user", "*", common.Map{
"AND": common.Map{ // ✅ 正确多个条件用AND包装
"status": 1,
"age[>]": 18,
},
"ORDER": "id DESC", // ✅ 正确,特殊参数与条件同级
})
// OR条件
correctUsers3 := db.Select("user", "*", common.Map{
"OR": common.Map{ // ✅ 正确OR条件
"level": "vip",
"balance[>]": 1000,
},
})
// 嵌套条件
correctUsers4 := db.Select("user", "*", common.Map{
"AND": common.Map{ // ✅ 正确,嵌套条件
"status": 1,
"OR": common.Map{
"age[<]": 30,
"level": "vip",
},
},
"ORDER": "created_time DESC",
"LIMIT": 20,
})
`)
// 实际不执行查询,只是展示语法
_ = db
}
// 运行所有修正后的示例
func RunAllFixedExamples() {
fmt.Println("开始运行HoTimeDB所有修正后的示例...")
fmt.Println("注意:实际运行时需要确保数据库连接正确,并且相关表存在")
// 展示语法对比
SyntaxComparison()
fmt.Println("请根据实际环境配置数据库连接后运行相应示例")
fmt.Println("所有示例代码已修正完毕,语法正确!")
}
func main() {
// 运行语法对比示例
RunAllFixedExamples()
}

1
go.mod
View File

@ -12,6 +12,5 @@ require (
github.com/sirupsen/logrus v1.8.1
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.364
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ocr v1.0.364
go.mongodb.org/mongo-driver v1.10.1
golang.org/x/net v0.0.0-20220225172249-27dd8689420f
)

30
go.sum
View File

@ -14,16 +14,10 @@ github.com/go-pay/gopay v1.5.78 h1:wIHp8g/jK0ik5bZo2MWt3jAQsktT3nkdXZxlRZvljko=
github.com/go-pay/gopay v1.5.78/go.mod h1:M6Nlk2VdZHCbWphOw3rtbnz4SiOk6Xvxg6mxwDfg+Ps=
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/gomodule/redigo v1.8.5 h1:nRAxCa+SVsyjSBrtZmG/cqb6VbTmuRzpg/PoTFlpumc=
github.com/gomodule/redigo v1.8.5/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw=
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI=
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
@ -31,12 +25,8 @@ github.com/mattn/go-sqlite3 v1.14.12 h1:TJ1bhYJPV44phC+IMu1u2K/i5RriLTPe+yc68XDJ
github.com/mattn/go-sqlite3 v1.14.12/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0=
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/silenceper/wechat/v2 v2.1.2 h1:+QfIMiYfwST2ZloTwmYp0O0p5Y1LYRZxfLWfMuSE30k=
@ -49,36 +39,20 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.2.3-0.20181224173747-660f15d67dbb/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.364 h1:X1Jws4XqrTH+p7FBQ7BpjW4qFXObKHWm0/XhW/GvqRs=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.364/go.mod h1:7sCQWVkxcsR38nffDW057DRGk8mUjK1Ing/EFOK8s8Y=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ocr v1.0.364 h1:kbor60vo37v7Hu+i17gooox9Rw281fVHNna8zwtDG1w=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ocr v1.0.364/go.mod h1:LeIUBOLhc+Y5YCEpZrULPD9lgoXXV4/EmIcoEvmHz9c=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
github.com/xdg-go/scram v1.1.1 h1:VOMT+81stJgXW3CpHyqHN3AXDYIMsx56mEFrB37Mb/E=
github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g=
github.com/xdg-go/stringprep v1.0.3 h1:kdwGpVNwPFtjs98xCGkHjQtGKh86rDcRZN17QEMCOIs=
github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
go.mongodb.org/mongo-driver v1.10.1 h1:NujsPveKwHaWuKUer/ceo9DzEe7HIj1SlJ6uvXZG0S4=
go.mongodb.org/mongo-driver v1.10.1/go.mod h1:z4XpeoU6w+9Vht+jAFyLgVrD+jGSQQe0+CBWFHNiHt8=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29 h1:tkVvjkPTB7pnW3jnid7kNyAMPVWllTNOf/qKDze4p9o=
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d h1:sK3txAijHtOK88l68nt020reeT1ZdKLIYetKl95FzVY=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f h1:oA4XRj0qtSt8Yo1Zms0CUlsT3KG69V2UGQWPBxujDmc=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@ -92,16 +66,12 @@ golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9sn
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/h2non/gock.v1 v1.0.15 h1:SzLqcIlb/fDfg7UvukMpNcWsu7sI5tWwL+KCATZqks0=
gopkg.in/h2non/gock.v1 v1.0.15/go.mod h1:sX4zAkdYX1TRGJ2JY156cFspQn4yRWn6p9EMdODlynE=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -94,9 +94,6 @@ func findCaller(skip int) string {
if file == "code/makecode.go" {
file, line = getCaller(skip + i + j)
}
if strings.Index(file, "common/") == 0 {
file, line = getCaller(skip + i + j)
}
if strings.Contains(file, "application.go") {
file, line = getCaller(skip + i + j)
}

View File

@ -1 +0,0 @@
test/Test*.xlsx

View File

@ -1,26 +0,0 @@
language: go
install:
- go get -d -t -v ./... && go build -v ./...
go:
- 1.8.x
- 1.9.x
- 1.10.x
- 1.11.x
os:
- linux
- osx
env:
matrix:
- GOARCH=amd64
- GOARCH=386
script:
- go vet ./...
- go test ./... -v -coverprofile=coverage.txt -covermode=atomic
after_success:
- bash <(curl -s https://codecov.io/bash)

View File

@ -1,46 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [xuri.me](https://xuri.me). The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@ -1,464 +0,0 @@
<!-- use this template to generate the contributor docs with the following command: `$ lingo run docs --template CONTRIBUTING_TEMPLATE.md --output CONTRIBUTING.md` -->
# Contributing to excelize
Want to hack on excelize? Awesome! This page contains information about reporting issues as well as some tips and
guidelines useful to experienced open source contributors. Finally, make sure
you read our [community guidelines](#community-guidelines) before you
start participating.
## Topics
* [Reporting Security Issues](#reporting-security-issues)
* [Design and Cleanup Proposals](#design-and-cleanup-proposals)
* [Reporting Issues](#reporting-other-issues)
* [Quick Contribution Tips and Guidelines](#quick-contribution-tips-and-guidelines)
* [Community Guidelines](#community-guidelines)
## Reporting security issues
The excelize maintainers take security seriously. If you discover a security
issue, please bring it to their attention right away!
Please **DO NOT** file a public issue, instead send your report privately to
[xuri.me](https://xuri.me).
Security reports are greatly appreciated and we will publicly thank you for it.
We currently do not offer a paid security bounty program, but are not
ruling it out in the future.
## Reporting other issues
A great way to contribute to the project is to send a detailed report when you
encounter an issue. We always appreciate a well-written, thorough bug report,
and will thank you for it!
Check that [our issue database](https://github.com/360EntSecGroup-Skylar/excelize/issues)
doesn't already include that problem or suggestion before submitting an issue.
If you find a match, you can use the "subscribe" button to get notified on
updates. Do *not* leave random "+1" or "I have this too" comments, as they
only clutter the discussion, and don't help resolving it. However, if you
have ways to reproduce the issue or have additional information that may help
resolving the issue, please leave a comment.
When reporting issues, always include the output of `go env`.
Also include the steps required to reproduce the problem if possible and
applicable. This information will help us review and fix your issue faster.
When sending lengthy log-files, consider posting them as a gist [https://gist.github.com](https://gist.github.com).
Don't forget to remove sensitive data from your logfiles before posting (you can
replace those parts with "REDACTED").
## Quick contribution tips and guidelines
This section gives the experienced contributor some tips and guidelines.
### Pull requests are always welcome
Not sure if that typo is worth a pull request? Found a bug and know how to fix
it? Do it! We will appreciate it. Any significant improvement should be
documented as [a GitHub issue](https://github.com/360EntSecGroup-Skylar/excelize/issues) before
anybody starts working on it.
We are always thrilled to receive pull requests. We do our best to process them
quickly. If your pull request is not accepted on the first try,
don't get discouraged!
### Design and cleanup proposals
You can propose new designs for existing excelize features. You can also design
entirely new features. We really appreciate contributors who want to refactor or
otherwise cleanup our project.
We try hard to keep excelize lean and focused. Excelize can't do everything for
everybody. This means that we might decide against incorporating a new feature.
However, there might be a way to implement that feature *on top of* excelize.
### Conventions
Fork the repository and make changes on your fork in a feature branch:
* If it's a bug fix branch, name it XXXX-something where XXXX is the number of
the issue.
* If it's a feature branch, create an enhancement issue to announce
your intentions, and name it XXXX-something where XXXX is the number of the
issue.
Submit unit tests for your changes. Go has a great test framework built in; use
it! Take a look at existing tests for inspiration. Run the full test on your branch before
submitting a pull request.
Update the documentation when creating or modifying features. Test your
documentation changes for clarity, concision, and correctness, as well as a
clean documentation build.
Write clean code. Universally formatted code promotes ease of writing, reading,
and maintenance. Always run `gofmt -s -w file.go` on each changed file before
committing your changes. Most editors have plug-ins that do this automatically.
Pull request descriptions should be as clear as possible and include a reference
to all the issues that they address.
### Successful Changes
Before contributing large or high impact changes, make the effort to coordinate
with the maintainers of the project before submitting a pull request. This
prevents you from doing extra work that may or may not be merged.
Large PRs that are just submitted without any prior communication are unlikely
to be successful.
While pull requests are the methodology for submitting changes to code, changes
are much more likely to be accepted if they are accompanied by additional
engineering work. While we don't define this explicitly, most of these goals
are accomplished through communication of the design goals and subsequent
solutions. Often times, it helps to first state the problem before presenting
solutions.
Typically, the best methods of accomplishing this are to submit an issue,
stating the problem. This issue can include a problem statement and a
checklist with requirements. If solutions are proposed, alternatives should be
listed and eliminated. Even if the criteria for elimination of a solution is
frivolous, say so.
Larger changes typically work best with design documents. These are focused on
providing context to the design at the time the feature was conceived and can
inform future documentation contributions.
### Commit Messages
Commit messages must start with a capitalized and short summary
written in the imperative, followed by an optional, more detailed explanatory
text which is separated from the summary by an empty line.
Commit messages should follow best practices, including explaining the context
of the problem and how it was solved, including in caveats or follow up changes
required. They should tell the story of the change and provide readers
understanding of what led to it.
In practice, the best approach to maintaining a nice commit message is to
leverage a `git add -p` and `git commit --amend` to formulate a solid
changeset. This allows one to piece together a change, as information becomes
available.
If you squash a series of commits, don't just submit that. Re-write the commit
message, as if the series of commits was a single stroke of brilliance.
That said, there is no requirement to have a single commit for a PR, as long as
each commit tells the story. For example, if there is a feature that requires a
package, it might make sense to have the package in a separate commit then have
a subsequent commit that uses it.
Remember, you're telling part of the story with the commit message. Don't make
your chapter weird.
### Review
Code review comments may be added to your pull request. Discuss, then make the
suggested modifications and push additional commits to your feature branch. Post
a comment after pushing. New commits show up in the pull request automatically,
but the reviewers are notified only when you comment.
Pull requests must be cleanly rebased on top of master without multiple branches
mixed into the PR.
**Git tip**: If your PR no longer merges cleanly, use `rebase master` in your
feature branch to update your pull request rather than `merge master`.
Before you make a pull request, squash your commits into logical units of work
using `git rebase -i` and `git push -f`. A logical unit of work is a consistent
set of patches that should be reviewed together: for example, upgrading the
version of a vendored dependency and taking advantage of its now available new
feature constitute two separate units of work. Implementing a new function and
calling it in another file constitute a single logical unit of work. The very
high majority of submissions should have a single commit, so if in doubt: squash
down to one.
After every commit, make sure the test passes. Include documentation
changes in the same pull request so that a revert would remove all traces of
the feature or fix.
Include an issue reference like `Closes #XXXX` or `Fixes #XXXX` in commits that
close an issue. Including references automatically closes the issue on a merge.
Please see the [Coding Style](#coding-style) for further guidelines.
### Merge approval
The excelize maintainers use LGTM (Looks Good To Me) in comments on the code review to
indicate acceptance.
### Sign your work
The sign-off is a simple line at the end of the explanation for the patch. Your
signature certifies that you wrote the patch or otherwise have the right to pass
it on as an open-source patch. The rules are pretty simple: if you can certify
the below (from [developercertificate.org](http://developercertificate.org/)):
```text
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
1 Letterman Drive
Suite D4700
San Francisco, CA, 94129
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
Then you just add a line to every git commit message:
Signed-off-by: Ri Xu https://xuri.me
Use your real name (sorry, no pseudonyms or anonymous contributions.)
If you set your `user.name` and `user.email` git configs, you can sign your
commit automatically with `git commit -s`.
### How can I become a maintainer
First, all maintainers have 3 things
* They share responsibility in the project's success.
* They have made a long-term, recurring time investment to improve the project.
* They spend that time doing whatever needs to be done, not necessarily what
is the most interesting or fun.
Maintainers are often under-appreciated, because their work is harder to appreciate.
It's easy to appreciate a really cool and technically advanced feature. It's harder
to appreciate the absence of bugs, the slow but steady improvement in stability,
or the reliability of a release process. But those things distinguish a good
project from a great one.
Don't forget: being a maintainer is a time investment. Make sure you
will have time to make yourself available. You don't have to be a
maintainer to make a difference on the project!
If you want to become a meintainer, contact [xuri.me](https://xuri.me) and given a introduction of you.
## Community guidelines
We want to keep the community awesome, growing and collaborative. We need
your help to keep it that way. To help with this we've come up with some general
guidelines for the community as a whole:
* Be nice: Be courteous, respectful and polite to fellow community members:
no regional, racial, gender, or other abuse will be tolerated. We like
nice people way better than mean ones!
* Encourage diversity and participation: Make everyone in our community feel
welcome, regardless of their background and the extent of their
contributions, and do everything possible to encourage participation in
our community.
* Keep it legal: Basically, don't get us in trouble. Share only content that
you own, do not share private or sensitive information, and don't break
the law.
* Stay on topic: Make sure that you are posting to the correct channel and
avoid off-topic discussions. Remember when you update an issue or respond
to an email you are potentially sending to a large number of people. Please
consider this before you update. Also remember that nobody likes spam.
* Don't send email to the maintainers: There's no need to send email to the
maintainers to ask them to investigate an issue or to take a look at a
pull request. Instead of sending an email, GitHub mentions should be
used to ping maintainers to review a pull request, a proposal or an
issue.
### Guideline violations — 3 strikes method
The point of this section is not to find opportunities to punish people, but we
do need a fair way to deal with people who are making our community suck.
1. First occurrence: We'll give you a friendly, but public reminder that the
behavior is inappropriate according to our guidelines.
2. Second occurrence: We will send you a private message with a warning that
any additional violations will result in removal from the community.
3. Third occurrence: Depending on the violation, we may need to delete or ban
your account.
**Notes:**
* Obvious spammers are banned on first occurrence. If we don't do this, we'll
have spam all over the place.
* Violations are forgiven after 6 months of good behavior, and we won't hold a
grudge.
* People who commit minor infractions will get some education, rather than
hammering them in the 3 strikes process.
* The rules apply equally to everyone in the community, no matter how much
you've contributed.
* Extreme violations of a threatening, abusive, destructive or illegal nature
will be addressed immediately and are not subject to 3 strikes or forgiveness.
* Contact [xuri.me](https://xuri.me) to report abuse or appeal violations. In the case of
appeals, we know that mistakes happen, and we'll work with you to come up with a
fair solution if there has been a misunderstanding.
## Coding Style
Unless explicitly stated, we follow all coding guidelines from the Go
community. While some of these standards may seem arbitrary, they somehow seem
to result in a solid, consistent codebase.
It is possible that the code base does not currently comply with these
guidelines. We are not looking for a massive PR that fixes this, since that
goes against the spirit of the guidelines. All new contributions should make a
best effort to clean up and make the code base better than they left it.
Obviously, apply your best judgement. Remember, the goal here is to make the
code base easier for humans to navigate and understand. Always keep that in
mind when nudging others to comply.
The rules:
1. All code should be formatted with `gofmt -s`.
2. All code should pass the default levels of
[`golint`](https://github.com/golang/lint).
3. All code should follow the guidelines covered in [Effective
Go](http://golang.org/doc/effective_go.html) and [Go Code Review
Comments](https://github.com/golang/go/wiki/CodeReviewComments).
4. Comment the code. Tell us the why, the history and the context.
5. Document _all_ declarations and methods, even private ones. Declare
expectations, caveats and anything else that may be important. If a type
gets exported, having the comments already there will ensure it's ready.
6. Variable name length should be proportional to its context and no longer.
`noCommaALongVariableNameLikeThisIsNotMoreClearWhenASimpleCommentWouldDo`.
In practice, short methods will have short variable names and globals will
have longer names.
7. No underscores in package names. If you need a compound name, step back,
and re-examine why you need a compound name. If you still think you need a
compound name, lose the underscore.
8. No utils or helpers packages. If a function is not general enough to
warrant its own package, it has not been written generally enough to be a
part of a util package. Just leave it unexported and well-documented.
9. All tests should run with `go test` and outside tooling should not be
required. No, we don't need another unit testing framework. Assertion
packages are acceptable if they provide _real_ incremental value.
10. Even though we call these "rules" above, they are actually just
guidelines. Since you've read all the rules, you now know that.
If you are having trouble getting into the mood of idiomatic Go, we recommend
reading through [Effective Go](https://golang.org/doc/effective_go.html). The
[Go Blog](https://blog.golang.org) is also a great resource. Drinking the
kool-aid is a lot easier than going thirsty.
## Code Review Comments and Effective Go Guidelines
[CodeLingo](https://codelingo.io) automatically checks every pull request against the following guidelines from [Effective Go](https://golang.org/doc/effective_go.html) and [Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments).
### Package Comment
Every package should have a package comment, a block comment preceding the package clause.
For multi-file packages, the package comment only needs to be present in one file, and any one will do.
The package comment should introduce the package and provide information relevant to the package as a
whole. It will appear first on the godoc page and should set up the detailed documentation that follows.
### Single Method Interface Name
By convention, one-method interfaces are named by the method name plus an -er suffix
or similar modification to construct an agent noun: Reader, Writer, Formatter, CloseNotifier etc.
There are a number of such names and it's productive to honor them and the function names they capture.
Read, Write, Close, Flush, String and so on have canonical signatures and meanings. To avoid confusion,
don't give your method one of those names unless it has the same signature and meaning. Conversely,
if your type implements a method with the same meaning as a method on a well-known type, give it the
same name and signature; call your string-converter method String not ToString.
### Avoid Annotations in Comments
Comments do not need extra formatting such as banners of stars. The generated output
may not even be presented in a fixed-width font, so don't depend on spacing for alignment—godoc,
like gofmt, takes care of that. The comments are uninterpreted plain text, so HTML and other
annotations such as _this_ will reproduce verbatim and should not be used. One adjustment godoc
does do is to display indented text in a fixed-width font, suitable for program snippets.
The package comment for the fmt package uses this to good effect.
### Comment First Word as Subject
Doc comments work best as complete sentences, which allow a wide variety of automated presentations.
The first sentence should be a one-sentence summary that starts with the name being declared.
### Good Package Name
It's helpful if everyone using the package can use the same name
to refer to its contents, which implies that the package name should
be good: short, concise, evocative. By convention, packages are
given lower case, single-word names; there should be no need for
underscores or mixedCaps. Err on the side of brevity, since everyone
using your package will be typing that name. And don't worry about
collisions a priori. The package name is only the default name for
imports; it need not be unique across all source code, and in the
rare case of a collision the importing package can choose a different
name to use locally. In any case, confusion is rare because the file
name in the import determines just which package is being used.
### Avoid Renaming Imports
Avoid renaming imports except to avoid a name collision; good package names
should not require renaming. In the event of collision, prefer to rename the
most local or project-specific import.
### Context as First Argument
Values of the context.Context type carry security credentials, tracing information,
deadlines, and cancellation signals across API and process boundaries. Go programs
pass Contexts explicitly along the entire function call chain from incoming RPCs
and HTTP requests to outgoing requests.
Most functions that use a Context should accept it as their first parameter.
### Do Not Discard Errors
Do not discard errors using _ variables. If a function returns an error,
check it to make sure the function succeeded. Handle the error, return it, or,
in truly exceptional situations, panic.
### Go Error Format
Error strings should not be capitalized (unless beginning with proper nouns
or acronyms) or end with punctuation, since they are usually printed following
other context. That is, use fmt.Errorf("something bad") not fmt.Errorf("Something bad"),
so that log.Printf("Reading %s: %v", filename, err) formats without a spurious
capital letter mid-message. This does not apply to logging, which is implicitly
line-oriented and not combined inside other messages.
### Use Crypto Rand
Do not use package math/rand to generate keys, even
throwaway ones. Unseeded, the generator is completely predictable.
Seeded with time.Nanoseconds(), there are just a few bits of entropy.
Instead, use crypto/rand's Reader, and if you need text, print to
hexadecimal or base64

View File

@ -1,384 +0,0 @@
<!-- use this template to generate the contributor docs with the following command: `$ lingo run docs --template CONTRIBUTING_TEMPLATE.md --output CONTRIBUTING.md` -->
# Contributing to excelize
Want to hack on excelize? Awesome! This page contains information about reporting issues as well as some tips and
guidelines useful to experienced open source contributors. Finally, make sure
you read our [community guidelines](#community-guidelines) before you
start participating.
## Topics
* [Reporting Security Issues](#reporting-security-issues)
* [Design and Cleanup Proposals](#design-and-cleanup-proposals)
* [Reporting Issues](#reporting-other-issues)
* [Quick Contribution Tips and Guidelines](#quick-contribution-tips-and-guidelines)
* [Community Guidelines](#community-guidelines)
## Reporting security issues
The excelize maintainers take security seriously. If you discover a security
issue, please bring it to their attention right away!
Please **DO NOT** file a public issue, instead send your report privately to
[xuri.me](https://xuri.me).
Security reports are greatly appreciated and we will publicly thank you for it.
We currently do not offer a paid security bounty program, but are not
ruling it out in the future.
## Reporting other issues
A great way to contribute to the project is to send a detailed report when you
encounter an issue. We always appreciate a well-written, thorough bug report,
and will thank you for it!
Check that [our issue database](https://github.com/360EntSecGroup-Skylar/excelize/issues)
doesn't already include that problem or suggestion before submitting an issue.
If you find a match, you can use the "subscribe" button to get notified on
updates. Do *not* leave random "+1" or "I have this too" comments, as they
only clutter the discussion, and don't help resolving it. However, if you
have ways to reproduce the issue or have additional information that may help
resolving the issue, please leave a comment.
When reporting issues, always include the output of `go env`.
Also include the steps required to reproduce the problem if possible and
applicable. This information will help us review and fix your issue faster.
When sending lengthy log-files, consider posting them as a gist [https://gist.github.com](https://gist.github.com).
Don't forget to remove sensitive data from your logfiles before posting (you can
replace those parts with "REDACTED").
## Quick contribution tips and guidelines
This section gives the experienced contributor some tips and guidelines.
### Pull requests are always welcome
Not sure if that typo is worth a pull request? Found a bug and know how to fix
it? Do it! We will appreciate it. Any significant improvement should be
documented as [a GitHub issue](https://github.com/360EntSecGroup-Skylar/excelize/issues) before
anybody starts working on it.
We are always thrilled to receive pull requests. We do our best to process them
quickly. If your pull request is not accepted on the first try,
don't get discouraged!
### Design and cleanup proposals
You can propose new designs for existing excelize features. You can also design
entirely new features. We really appreciate contributors who want to refactor or
otherwise cleanup our project.
We try hard to keep excelize lean and focused. Excelize can't do everything for
everybody. This means that we might decide against incorporating a new feature.
However, there might be a way to implement that feature *on top of* excelize.
### Conventions
Fork the repository and make changes on your fork in a feature branch:
* If it's a bug fix branch, name it XXXX-something where XXXX is the number of
the issue.
* If it's a feature branch, create an enhancement issue to announce
your intentions, and name it XXXX-something where XXXX is the number of the
issue.
Submit unit tests for your changes. Go has a great test framework built in; use
it! Take a look at existing tests for inspiration. Run the full test on your branch before
submitting a pull request.
Update the documentation when creating or modifying features. Test your
documentation changes for clarity, concision, and correctness, as well as a
clean documentation build.
Write clean code. Universally formatted code promotes ease of writing, reading,
and maintenance. Always run `gofmt -s -w file.go` on each changed file before
committing your changes. Most editors have plug-ins that do this automatically.
Pull request descriptions should be as clear as possible and include a reference
to all the issues that they address.
### Successful Changes
Before contributing large or high impact changes, make the effort to coordinate
with the maintainers of the project before submitting a pull request. This
prevents you from doing extra work that may or may not be merged.
Large PRs that are just submitted without any prior communication are unlikely
to be successful.
While pull requests are the methodology for submitting changes to code, changes
are much more likely to be accepted if they are accompanied by additional
engineering work. While we don't define this explicitly, most of these goals
are accomplished through communication of the design goals and subsequent
solutions. Often times, it helps to first state the problem before presenting
solutions.
Typically, the best methods of accomplishing this are to submit an issue,
stating the problem. This issue can include a problem statement and a
checklist with requirements. If solutions are proposed, alternatives should be
listed and eliminated. Even if the criteria for elimination of a solution is
frivolous, say so.
Larger changes typically work best with design documents. These are focused on
providing context to the design at the time the feature was conceived and can
inform future documentation contributions.
### Commit Messages
Commit messages must start with a capitalized and short summary
written in the imperative, followed by an optional, more detailed explanatory
text which is separated from the summary by an empty line.
Commit messages should follow best practices, including explaining the context
of the problem and how it was solved, including in caveats or follow up changes
required. They should tell the story of the change and provide readers
understanding of what led to it.
In practice, the best approach to maintaining a nice commit message is to
leverage a `git add -p` and `git commit --amend` to formulate a solid
changeset. This allows one to piece together a change, as information becomes
available.
If you squash a series of commits, don't just submit that. Re-write the commit
message, as if the series of commits was a single stroke of brilliance.
That said, there is no requirement to have a single commit for a PR, as long as
each commit tells the story. For example, if there is a feature that requires a
package, it might make sense to have the package in a separate commit then have
a subsequent commit that uses it.
Remember, you're telling part of the story with the commit message. Don't make
your chapter weird.
### Review
Code review comments may be added to your pull request. Discuss, then make the
suggested modifications and push additional commits to your feature branch. Post
a comment after pushing. New commits show up in the pull request automatically,
but the reviewers are notified only when you comment.
Pull requests must be cleanly rebased on top of master without multiple branches
mixed into the PR.
**Git tip**: If your PR no longer merges cleanly, use `rebase master` in your
feature branch to update your pull request rather than `merge master`.
Before you make a pull request, squash your commits into logical units of work
using `git rebase -i` and `git push -f`. A logical unit of work is a consistent
set of patches that should be reviewed together: for example, upgrading the
version of a vendored dependency and taking advantage of its now available new
feature constitute two separate units of work. Implementing a new function and
calling it in another file constitute a single logical unit of work. The very
high majority of submissions should have a single commit, so if in doubt: squash
down to one.
After every commit, make sure the test passes. Include documentation
changes in the same pull request so that a revert would remove all traces of
the feature or fix.
Include an issue reference like `Closes #XXXX` or `Fixes #XXXX` in commits that
close an issue. Including references automatically closes the issue on a merge.
Please see the [Coding Style](#coding-style) for further guidelines.
### Merge approval
The excelize maintainers use LGTM (Looks Good To Me) in comments on the code review to
indicate acceptance.
### Sign your work
The sign-off is a simple line at the end of the explanation for the patch. Your
signature certifies that you wrote the patch or otherwise have the right to pass
it on as an open-source patch. The rules are pretty simple: if you can certify
the below (from [developercertificate.org](http://developercertificate.org/)):
```text
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
1 Letterman Drive
Suite D4700
San Francisco, CA, 94129
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
Then you just add a line to every git commit message:
Signed-off-by: Ri Xu https://xuri.me
Use your real name (sorry, no pseudonyms or anonymous contributions.)
If you set your `user.name` and `user.email` git configs, you can sign your
commit automatically with `git commit -s`.
### How can I become a maintainer
First, all maintainers have 3 things
* They share responsibility in the project's success.
* They have made a long-term, recurring time investment to improve the project.
* They spend that time doing whatever needs to be done, not necessarily what
is the most interesting or fun.
Maintainers are often under-appreciated, because their work is harder to appreciate.
It's easy to appreciate a really cool and technically advanced feature. It's harder
to appreciate the absence of bugs, the slow but steady improvement in stability,
or the reliability of a release process. But those things distinguish a good
project from a great one.
Don't forget: being a maintainer is a time investment. Make sure you
will have time to make yourself available. You don't have to be a
maintainer to make a difference on the project!
If you want to become a meintainer, contact [xuri.me](https://xuri.me) and given a introduction of you.
## Community guidelines
We want to keep the community awesome, growing and collaborative. We need
your help to keep it that way. To help with this we've come up with some general
guidelines for the community as a whole:
* Be nice: Be courteous, respectful and polite to fellow community members:
no regional, racial, gender, or other abuse will be tolerated. We like
nice people way better than mean ones!
* Encourage diversity and participation: Make everyone in our community feel
welcome, regardless of their background and the extent of their
contributions, and do everything possible to encourage participation in
our community.
* Keep it legal: Basically, don't get us in trouble. Share only content that
you own, do not share private or sensitive information, and don't break
the law.
* Stay on topic: Make sure that you are posting to the correct channel and
avoid off-topic discussions. Remember when you update an issue or respond
to an email you are potentially sending to a large number of people. Please
consider this before you update. Also remember that nobody likes spam.
* Don't send email to the maintainers: There's no need to send email to the
maintainers to ask them to investigate an issue or to take a look at a
pull request. Instead of sending an email, GitHub mentions should be
used to ping maintainers to review a pull request, a proposal or an
issue.
### Guideline violations — 3 strikes method
The point of this section is not to find opportunities to punish people, but we
do need a fair way to deal with people who are making our community suck.
1. First occurrence: We'll give you a friendly, but public reminder that the
behavior is inappropriate according to our guidelines.
2. Second occurrence: We will send you a private message with a warning that
any additional violations will result in removal from the community.
3. Third occurrence: Depending on the violation, we may need to delete or ban
your account.
**Notes:**
* Obvious spammers are banned on first occurrence. If we don't do this, we'll
have spam all over the place.
* Violations are forgiven after 6 months of good behavior, and we won't hold a
grudge.
* People who commit minor infractions will get some education, rather than
hammering them in the 3 strikes process.
* The rules apply equally to everyone in the community, no matter how much
you've contributed.
* Extreme violations of a threatening, abusive, destructive or illegal nature
will be addressed immediately and are not subject to 3 strikes or forgiveness.
* Contact [xuri.me](https://xuri.me) to report abuse or appeal violations. In the case of
appeals, we know that mistakes happen, and we'll work with you to come up with a
fair solution if there has been a misunderstanding.
## Coding Style
Unless explicitly stated, we follow all coding guidelines from the Go
community. While some of these standards may seem arbitrary, they somehow seem
to result in a solid, consistent codebase.
It is possible that the code base does not currently comply with these
guidelines. We are not looking for a massive PR that fixes this, since that
goes against the spirit of the guidelines. All new contributions should make a
best effort to clean up and make the code base better than they left it.
Obviously, apply your best judgement. Remember, the goal here is to make the
code base easier for humans to navigate and understand. Always keep that in
mind when nudging others to comply.
The rules:
1. All code should be formatted with `gofmt -s`.
2. All code should pass the default levels of
[`golint`](https://github.com/golang/lint).
3. All code should follow the guidelines covered in [Effective
Go](http://golang.org/doc/effective_go.html) and [Go Code Review
Comments](https://github.com/golang/go/wiki/CodeReviewComments).
4. Comment the code. Tell us the why, the history and the context.
5. Document _all_ declarations and methods, even private ones. Declare
expectations, caveats and anything else that may be important. If a type
gets exported, having the comments already there will ensure it's ready.
6. Variable name length should be proportional to its context and no longer.
`noCommaALongVariableNameLikeThisIsNotMoreClearWhenASimpleCommentWouldDo`.
In practice, short methods will have short variable names and globals will
have longer names.
7. No underscores in package names. If you need a compound name, step back,
and re-examine why you need a compound name. If you still think you need a
compound name, lose the underscore.
8. No utils or helpers packages. If a function is not general enough to
warrant its own package, it has not been written generally enough to be a
part of a util package. Just leave it unexported and well-documented.
9. All tests should run with `go test` and outside tooling should not be
required. No, we don't need another unit testing framework. Assertion
packages are acceptable if they provide _real_ incremental value.
10. Even though we call these "rules" above, they are actually just
guidelines. Since you've read all the rules, you now know that.
If you are having trouble getting into the mood of idiomatic Go, we recommend
reading through [Effective Go](https://golang.org/doc/effective_go.html). The
[Go Blog](https://blog.golang.org) is also a great resource. Drinking the
kool-aid is a lot easier than going thirsty.
## Code Review Comments and Effective Go Guidelines
[CodeLingo](https://codelingo.io) automatically checks every pull request against the following guidelines from [Effective Go](https://golang.org/doc/effective_go.html) and [Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments).
{{range .}}
### {{.title}}
{{.body}}
{{end}}

View File

@ -1,29 +0,0 @@
BSD 3-Clause License
Copyright (c) 2016 - 2019 360 Enterprise Security Group, Endpoint Security,
inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Excelize nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,45 +0,0 @@
# PR Details
<!--- Provide a general summary of your changes in the Title above -->
## Description
<!--- Describe your changes in detail -->
## Related Issue
<!--- This project only accepts pull requests related to open issues -->
<!--- If suggesting a new feature or change, please discuss it in an issue first -->
<!--- If fixing a bug, there should be an issue describing it with steps to reproduce -->
<!--- Please link to the issue here: -->
## Motivation and Context
<!--- Why is this change required? What problem does it solve? -->
## How Has This Been Tested
<!--- Please describe in detail how you tested your changes. -->
<!--- Include details of your testing environment, and the tests you ran to -->
<!--- see how your change affects other areas of the code, etc. -->
## Types of changes
<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->
- [ ] Docs change / refactoring / dependency upgrade
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
## Checklist
<!--- Go over all the following points, and put an `x` in all the boxes that apply. -->
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
- [ ] My code follows the code style of this project.
- [ ] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly.
- [ ] I have read the **CONTRIBUTING** document.
- [ ] I have added tests to cover my changes.
- [ ] All new and existing tests passed.

View File

@ -1,179 +0,0 @@
<p align="center"><img width="650" src="./excelize.png" alt="Excelize logo"></p>
<p align="center">
<a href="https://travis-ci.org/360EntSecGroup-Skylar/excelize"><img src="https://travis-ci.org/360EntSecGroup-Skylar/excelize.svg?branch=master" alt="Build Status"></a>
<a href="https://codecov.io/gh/360EntSecGroup-Skylar/excelize"><img src="https://codecov.io/gh/360EntSecGroup-Skylar/excelize/branch/master/graph/badge.svg" alt="Code Coverage"></a>
<a href="https://goreportcard.com/report/github.com/360EntSecGroup-Skylar/excelize"><img src="https://goreportcard.com/badge/github.com/360EntSecGroup-Skylar/excelize" alt="Go Report Card"></a>
<a href="https://godoc.org/github.com/360EntSecGroup-Skylar/excelize"><img src="https://godoc.org/github.com/360EntSecGroup-Skylar/excelize?status.svg" alt="GoDoc"></a>
<a href="https://opensource.org/licenses/BSD-3-Clause"><img src="https://img.shields.io/badge/license-bsd-orange.svg" alt="Licenses"></a>
<a href="https://www.paypal.me/xuri"><img src="https://img.shields.io/badge/Donate-PayPal-green.svg" alt="Donate"></a>
</p>
# Excelize
## Introduction
Excelize is a library written in pure Go and providing a set of functions that allow you to write to and read from XLSX files. Support reads and writes XLSX file generated by Microsoft Excel&trade; 2007 and later. Support save file without losing original charts of XLSX. This library needs Go version 1.8 or later. The full API docs can be seen using go's built-in documentation tool, or online at [godoc.org](https://godoc.org/github.com/360EntSecGroup-Skylar/excelize) and [docs reference](https://xuri.me/excelize/).
## Basic Usage
### Installation
```go
go get github.com/360EntSecGroup-Skylar/excelize
```
### Create XLSX file
Here is a minimal example usage that will create XLSX file.
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
xlsx := excelize.NewFile()
// Create a new sheet.
index := xlsx.NewSheet("Sheet2")
// Set value of a cell.
xlsx.SetCellValue("Sheet2", "A2", "Hello world.")
xlsx.SetCellValue("Sheet1", "B2", 100)
// Set active sheet of the workbook.
xlsx.SetActiveSheet(index)
// Save xlsx file by the given path.
err := xlsx.SaveAs("./Book1.xlsx")
if err != nil {
fmt.Println(err)
}
}
```
### Reading XLSX file
The following constitutes the bare to read a XLSX document.
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
xlsx, err := excelize.OpenFile("./Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// Get value from cell by given worksheet name and axis.
cell := xlsx.GetCellValue("Sheet1", "B2")
fmt.Println(cell)
// Get all the rows in the Sheet1.
rows := xlsx.GetRows("Sheet1")
for _, row := range rows {
for _, colCell := range row {
fmt.Print(colCell, "\t")
}
fmt.Println()
}
}
```
### Add chart to XLSX file
With Excelize chart generation and management is as easy as a few lines of code. You can build charts based off data in your worksheet or generate charts without any data in your worksheet at all.
<p align="center"><img width="650" src="./test/images/chart.png" alt="Excelize"></p>
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
categories := map[string]string{"A2": "Small", "A3": "Normal", "A4": "Large", "B1": "Apple", "C1": "Orange", "D1": "Pear"}
values := map[string]int{"B2": 2, "C2": 3, "D2": 3, "B3": 5, "C3": 2, "D3": 4, "B4": 6, "C4": 7, "D4": 8}
xlsx := excelize.NewFile()
for k, v := range categories {
xlsx.SetCellValue("Sheet1", k, v)
}
for k, v := range values {
xlsx.SetCellValue("Sheet1", k, v)
}
xlsx.AddChart("Sheet1", "E1", `{"type":"col3DClustered","series":[{"name":"Sheet1!$A$2","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$2:$D$2"},{"name":"Sheet1!$A$3","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$3:$D$3"},{"name":"Sheet1!$A$4","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$4:$D$4"}],"title":{"name":"Fruit 3D Clustered Column Chart"}}`)
// Save xlsx file by the given path.
err := xlsx.SaveAs("./Book1.xlsx")
if err != nil {
fmt.Println(err)
}
}
```
### Add picture to XLSX file
```go
package main
import (
"fmt"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
xlsx, err := excelize.OpenFile("./Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// Insert a picture.
err = xlsx.AddPicture("Sheet1", "A2", "./image1.png", "")
if err != nil {
fmt.Println(err)
}
// Insert a picture to worksheet with scaling.
err = xlsx.AddPicture("Sheet1", "D2", "./image2.jpg", `{"x_scale": 0.5, "y_scale": 0.5}`)
if err != nil {
fmt.Println(err)
}
// Insert a picture offset in the cell with printing support.
err = xlsx.AddPicture("Sheet1", "H2", "./image3.gif", `{"x_offset": 15, "y_offset": 10, "print_obj": true, "lock_aspect_ratio": false, "locked": false}`)
if err != nil {
fmt.Println(err)
}
// Save the xlsx file with the origin path.
err = xlsx.Save()
if err != nil {
fmt.Println(err)
}
}
```
## Contributing
Contributions are welcome! Open a pull request to fix a bug, or open an issue to discuss a new feature or change. XML is compliant with [part 1 of the 5th edition of the ECMA-376 Standard for Office Open XML](http://www.ecma-international.org/publications/standards/Ecma-376.htm).
## Credits
Some struct of XML originally by [tealeg/xlsx](https://github.com/tealeg/xlsx).
## Licenses
This program is under the terms of the BSD 3-Clause License. See [https://opensource.org/licenses/BSD-3-Clause](https://opensource.org/licenses/BSD-3-Clause).
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2F360EntSecGroup-Skylar%2Fexcelize.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2F360EntSecGroup-Skylar%2Fexcelize?ref=badge_large)

View File

@ -1,179 +0,0 @@
<p align="center"><img width="650" src="./excelize.png" alt="Excelize logo"></p>
<p align="center">
<a href="https://travis-ci.org/360EntSecGroup-Skylar/excelize"><img src="https://travis-ci.org/360EntSecGroup-Skylar/excelize.svg?branch=master" alt="Build Status"></a>
<a href="https://codecov.io/gh/360EntSecGroup-Skylar/excelize"><img src="https://codecov.io/gh/360EntSecGroup-Skylar/excelize/branch/master/graph/badge.svg" alt="Code Coverage"></a>
<a href="https://goreportcard.com/report/github.com/360EntSecGroup-Skylar/excelize"><img src="https://goreportcard.com/badge/github.com/360EntSecGroup-Skylar/excelize" alt="Go Report Card"></a>
<a href="https://godoc.org/github.com/360EntSecGroup-Skylar/excelize"><img src="https://godoc.org/github.com/360EntSecGroup-Skylar/excelize?status.svg" alt="GoDoc"></a>
<a href="https://opensource.org/licenses/BSD-3-Clause"><img src="https://img.shields.io/badge/license-bsd-orange.svg" alt="Licenses"></a>
<a href="https://www.paypal.me/xuri"><img src="https://img.shields.io/badge/Donate-PayPal-green.svg" alt="Donate"></a>
</p>
# Excelize
## 简介
Excelize 是 Go 语言编写的用于操作 Office Excel 文档类库,基于 ECMA-376 Office OpenXML 标准。可以使用它来读取、写入由 Microsoft Excel&trade; 2007 及以上版本创建的 XLSX 文档。相比较其他的开源类库Excelize 支持写入原本带有图片(表)、透视表和切片器等复杂样式的文档,还支持向 Excel 文档中插入图片与图表,并且在保存后不会丢失文档原有样式,可以应用于各类报表系统中。使用本类库要求使用的 Go 语言为 1.8 或更高版本,完整的 API 使用文档请访问 [godoc.org](https://godoc.org/github.com/360EntSecGroup-Skylar/excelize) 或查看 [参考文档](https://xuri.me/excelize/)。
## 快速上手
### 安装
```go
go get github.com/360EntSecGroup-Skylar/excelize
```
### 创建 Excel 文档
下面是一个创建 Excel 文档的简单例子:
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
xlsx := excelize.NewFile()
// 创建一个工作表
index := xlsx.NewSheet("Sheet2")
// 设置单元格的值
xlsx.SetCellValue("Sheet2", "A2", "Hello world.")
xlsx.SetCellValue("Sheet1", "B2", 100)
// 设置工作簿的默认工作表
xlsx.SetActiveSheet(index)
// 根据指定路径保存文件
err := xlsx.SaveAs("./Book1.xlsx")
if err != nil {
fmt.Println(err)
}
}
```
### 读取 Excel 文档
下面是读取 Excel 文档的例子:
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
xlsx, err := excelize.OpenFile("./Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// 获取工作表中指定单元格的值
cell := xlsx.GetCellValue("Sheet1", "B2")
fmt.Println(cell)
// 获取 Sheet1 上所有单元格
rows := xlsx.GetRows("Sheet1")
for _, row := range rows {
for _, colCell := range row {
fmt.Print(colCell, "\t")
}
fmt.Println()
}
}
```
### 在 Excel 文档中创建图表
使用 Excelize 生成图表十分简单,仅需几行代码。您可以根据工作表中的已有数据构建图表,或向工作表中添加数据并创建图表。
<p align="center"><img width="650" src="./test/images/chart.png" alt="Excelize"></p>
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
categories := map[string]string{"A2": "Small", "A3": "Normal", "A4": "Large", "B1": "Apple", "C1": "Orange", "D1": "Pear"}
values := map[string]int{"B2": 2, "C2": 3, "D2": 3, "B3": 5, "C3": 2, "D3": 4, "B4": 6, "C4": 7, "D4": 8}
xlsx := excelize.NewFile()
for k, v := range categories {
xlsx.SetCellValue("Sheet1", k, v)
}
for k, v := range values {
xlsx.SetCellValue("Sheet1", k, v)
}
xlsx.AddChart("Sheet1", "E1", `{"type":"col3DClustered","series":[{"name":"Sheet1!$A$2","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$2:$D$2"},{"name":"Sheet1!$A$3","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$3:$D$3"},{"name":"Sheet1!$A$4","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$4:$D$4"}],"title":{"name":"Fruit 3D Clustered Column Chart"}}`)
// 根据指定路径保存文件
err := xlsx.SaveAs("./Book1.xlsx")
if err != nil {
fmt.Println(err)
}
}
```
### 向 Excel 文档中插入图片
```go
package main
import (
"fmt"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
xlsx, err := excelize.OpenFile("./Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// 插入图片
err = xlsx.AddPicture("Sheet1", "A2", "./image1.png", "")
if err != nil {
fmt.Println(err)
}
// 在工作表中插入图片,并设置图片的缩放比例
err = xlsx.AddPicture("Sheet1", "D2", "./image2.jpg", `{"x_scale": 0.5, "y_scale": 0.5}`)
if err != nil {
fmt.Println(err)
}
// 在工作表中插入图片,并设置图片的打印属性
err = xlsx.AddPicture("Sheet1", "H2", "./image3.gif", `{"x_offset": 15, "y_offset": 10, "print_obj": true, "lock_aspect_ratio": false, "locked": false}`)
if err != nil {
fmt.Println(err)
}
// 保存文件
err = xlsx.Save()
if err != nil {
fmt.Println(err)
}
}
```
## 社区合作
欢迎您为此项目贡献代码,提出建议或问题、修复 Bug 以及参与讨论对新功能的想法。 XML 符合标准: [part 1 of the 5th edition of the ECMA-376 Standard for Office Open XML](http://www.ecma-international.org/publications/standards/Ecma-376.htm)。
## 致谢
本类库中部分 XML 结构体的定义参考了开源项目:[tealeg/xlsx](https://github.com/tealeg/xlsx).
## 开源许可
本项目遵循 BSD 3-Clause 开源许可协议,访问 [https://opensource.org/licenses/BSD-3-Clause](https://opensource.org/licenses/BSD-3-Clause) 查看许可协议文件。
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2F360EntSecGroup-Skylar%2Fexcelize.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2F360EntSecGroup-Skylar%2Fexcelize?ref=badge_large)

View File

@ -1,599 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"encoding/xml"
"fmt"
"reflect"
"strconv"
"strings"
"time"
)
const (
// STCellFormulaTypeArray defined the formula is an array formula.
STCellFormulaTypeArray = "array"
// STCellFormulaTypeDataTable defined the formula is a data table formula.
STCellFormulaTypeDataTable = "dataTable"
// STCellFormulaTypeNormal defined the formula is a regular cell formula.
STCellFormulaTypeNormal = "normal"
// STCellFormulaTypeShared defined the formula is part of a shared formula.
STCellFormulaTypeShared = "shared"
)
// mergeCellsParser provides a function to check merged cells in worksheet by
// given axis.
func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) string {
axis = strings.ToUpper(axis)
if xlsx.MergeCells != nil {
for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
if checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref) {
axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
}
}
}
return axis
}
// SetCellValue provides a function to set value of a cell. The following
// shows the supported data types:
//
// int
// int8
// int16
// int32
// int64
// uint
// uint8
// uint16
// uint32
// uint64
// float32
// float64
// string
// []byte
// time.Duration
// time.Time
// bool
// nil
//
// Note that default date format is m/d/yy h:mm of time.Time type value. You can
// set numbers format by SetCellStyle() method.
func (f *File) SetCellValue(sheet, axis string, value interface{}) {
switch t := value.(type) {
case float32:
f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(float32)), 'f', -1, 32))
case float64:
f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(float64)), 'f', -1, 64))
case string:
f.SetCellStr(sheet, axis, t)
case []byte:
f.SetCellStr(sheet, axis, string(t))
case time.Duration:
f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(value.(time.Duration).Seconds()/86400), 'f', -1, 32))
f.setDefaultTimeStyle(sheet, axis, 21)
case time.Time:
f.SetCellDefault(sheet, axis, strconv.FormatFloat(float64(timeToExcelTime(timeToUTCTime(value.(time.Time)))), 'f', -1, 64))
f.setDefaultTimeStyle(sheet, axis, 22)
case nil:
f.SetCellStr(sheet, axis, "")
case bool:
f.SetCellBool(sheet, axis, bool(value.(bool)))
default:
f.setCellIntValue(sheet, axis, value)
}
}
// setCellIntValue provides a function to set int value of a cell.
func (f *File) setCellIntValue(sheet, axis string, value interface{}) {
switch value.(type) {
case int:
f.SetCellInt(sheet, axis, value.(int))
case int8:
f.SetCellInt(sheet, axis, int(value.(int8)))
case int16:
f.SetCellInt(sheet, axis, int(value.(int16)))
case int32:
f.SetCellInt(sheet, axis, int(value.(int32)))
case int64:
f.SetCellInt(sheet, axis, int(value.(int64)))
case uint:
f.SetCellInt(sheet, axis, int(value.(uint)))
case uint8:
f.SetCellInt(sheet, axis, int(value.(uint8)))
case uint16:
f.SetCellInt(sheet, axis, int(value.(uint16)))
case uint32:
f.SetCellInt(sheet, axis, int(value.(uint32)))
case uint64:
f.SetCellInt(sheet, axis, int(value.(uint64)))
default:
f.SetCellStr(sheet, axis, fmt.Sprintf("%v", value))
}
}
// SetCellBool provides a function to set bool type value of a cell by given
// worksheet name, cell coordinates and cell value.
func (f *File) SetCellBool(sheet, axis string, value bool) {
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
col := string(strings.Map(letterOnlyMapF, axis))
row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
if err != nil {
return
}
xAxis := row - 1
yAxis := TitleToNumber(col)
rows := xAxis + 1
cell := yAxis + 1
completeRow(xlsx, rows, cell)
completeCol(xlsx, rows, cell)
xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
xlsx.SheetData.Row[xAxis].C[yAxis].T = "b"
if value {
xlsx.SheetData.Row[xAxis].C[yAxis].V = "1"
} else {
xlsx.SheetData.Row[xAxis].C[yAxis].V = "0"
}
}
// GetCellValue provides a function to get formatted value from cell by given
// worksheet name and axis in XLSX file. If it is possible to apply a format
// to the cell value, it will do so, if not then an error will be returned,
// along with the raw value of the cell.
func (f *File) GetCellValue(sheet, axis string) string {
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
if err != nil {
return ""
}
xAxis := row - 1
rows := len(xlsx.SheetData.Row)
if rows > 1 {
lastRow := xlsx.SheetData.Row[rows-1].R
if lastRow >= rows {
rows = lastRow
}
}
if rows < xAxis {
return ""
}
for k := range xlsx.SheetData.Row {
if xlsx.SheetData.Row[k].R == row {
for i := range xlsx.SheetData.Row[k].C {
if axis == xlsx.SheetData.Row[k].C[i].R {
val, _ := xlsx.SheetData.Row[k].C[i].getValueFrom(f, f.sharedStringsReader())
return val
}
}
}
}
return ""
}
// formattedValue provides a function to returns a value after formatted. If
// it is possible to apply a format to the cell value, it will do so, if not
// then an error will be returned, along with the raw value of the cell.
func (f *File) formattedValue(s int, v string) string {
if s == 0 {
return v
}
styleSheet := f.stylesReader()
ok := builtInNumFmtFunc[styleSheet.CellXfs.Xf[s].NumFmtID]
if ok != nil {
return ok(styleSheet.CellXfs.Xf[s].NumFmtID, v)
}
return v
}
// GetCellStyle provides a function to get cell style index by given worksheet
// name and cell coordinates.
func (f *File) GetCellStyle(sheet, axis string) int {
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
col := string(strings.Map(letterOnlyMapF, axis))
row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
if err != nil {
return 0
}
xAxis := row - 1
yAxis := TitleToNumber(col)
rows := xAxis + 1
cell := yAxis + 1
completeRow(xlsx, rows, cell)
completeCol(xlsx, rows, cell)
return f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
}
// GetCellFormula provides a function to get formula from cell by given
// worksheet name and axis in XLSX file.
func (f *File) GetCellFormula(sheet, axis string) string {
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
if err != nil {
return ""
}
xAxis := row - 1
rows := len(xlsx.SheetData.Row)
if rows > 1 {
lastRow := xlsx.SheetData.Row[rows-1].R
if lastRow >= rows {
rows = lastRow
}
}
if rows < xAxis {
return ""
}
for k := range xlsx.SheetData.Row {
if xlsx.SheetData.Row[k].R == row {
for i := range xlsx.SheetData.Row[k].C {
if axis == xlsx.SheetData.Row[k].C[i].R {
if xlsx.SheetData.Row[k].C[i].F == nil {
continue
}
if xlsx.SheetData.Row[k].C[i].F.T == STCellFormulaTypeShared {
return getSharedForumula(xlsx, xlsx.SheetData.Row[k].C[i].F.Si)
}
return xlsx.SheetData.Row[k].C[i].F.Content
}
}
}
}
return ""
}
// getSharedForumula find a cell contains the same formula as another cell,
// the "shared" value can be used for the t attribute and the si attribute can
// be used to refer to the cell containing the formula. Two formulas are
// considered to be the same when their respective representations in
// R1C1-reference notation, are the same.
//
// Note that this function not validate ref tag to check the cell if or not in
// allow area, and always return origin shared formula.
func getSharedForumula(xlsx *xlsxWorksheet, si string) string {
for k := range xlsx.SheetData.Row {
for i := range xlsx.SheetData.Row[k].C {
if xlsx.SheetData.Row[k].C[i].F == nil {
continue
}
if xlsx.SheetData.Row[k].C[i].F.T != STCellFormulaTypeShared {
continue
}
if xlsx.SheetData.Row[k].C[i].F.Si != si {
continue
}
if xlsx.SheetData.Row[k].C[i].F.Ref != "" {
return xlsx.SheetData.Row[k].C[i].F.Content
}
}
}
return ""
}
// SetCellFormula provides a function to set cell formula by given string and
// worksheet name.
func (f *File) SetCellFormula(sheet, axis, formula string) {
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
col := string(strings.Map(letterOnlyMapF, axis))
row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
if err != nil {
return
}
xAxis := row - 1
yAxis := TitleToNumber(col)
rows := xAxis + 1
cell := yAxis + 1
completeRow(xlsx, rows, cell)
completeCol(xlsx, rows, cell)
if xlsx.SheetData.Row[xAxis].C[yAxis].F != nil {
xlsx.SheetData.Row[xAxis].C[yAxis].F.Content = formula
} else {
f := xlsxF{
Content: formula,
}
xlsx.SheetData.Row[xAxis].C[yAxis].F = &f
}
}
// SetCellHyperLink provides a function to set cell hyperlink by given
// worksheet name and link URL address. LinkType defines two types of
// hyperlink "External" for web site or "Location" for moving to one of cell
// in this workbook. The below is example for external link.
//
// xlsx.SetCellHyperLink("Sheet1", "A3", "https://github.com/360EntSecGroup-Skylar/excelize", "External")
// // Set underline and font color style for the cell.
// style, _ := xlsx.NewStyle(`{"font":{"color":"#1265BE","underline":"single"}}`)
// xlsx.SetCellStyle("Sheet1", "A3", "A3", style)
//
// A this is another example for "Location":
//
// xlsx.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location")
//
func (f *File) SetCellHyperLink(sheet, axis, link, linkType string) {
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
linkTypes := map[string]xlsxHyperlink{
"External": {},
"Location": {Location: link},
}
hyperlink, ok := linkTypes[linkType]
if !ok || axis == "" {
return
}
hyperlink.Ref = axis
if linkType == "External" {
rID := f.addSheetRelationships(sheet, SourceRelationshipHyperLink, link, linkType)
hyperlink.RID = "rId" + strconv.Itoa(rID)
}
if xlsx.Hyperlinks == nil {
xlsx.Hyperlinks = &xlsxHyperlinks{}
}
xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink, hyperlink)
}
// GetCellHyperLink provides a function to get cell hyperlink by given
// worksheet name and axis. Boolean type value link will be ture if the cell
// has a hyperlink and the target is the address of the hyperlink. Otherwise,
// the value of link will be false and the value of the target will be a blank
// string. For example get hyperlink of Sheet1!H6:
//
// link, target := xlsx.GetCellHyperLink("Sheet1", "H6")
//
func (f *File) GetCellHyperLink(sheet, axis string) (bool, string) {
var link bool
var target string
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
if xlsx.Hyperlinks == nil || axis == "" {
return link, target
}
for h := range xlsx.Hyperlinks.Hyperlink {
if xlsx.Hyperlinks.Hyperlink[h].Ref == axis {
link = true
target = xlsx.Hyperlinks.Hyperlink[h].Location
if xlsx.Hyperlinks.Hyperlink[h].RID != "" {
target = f.getSheetRelationshipsTargetByID(sheet, xlsx.Hyperlinks.Hyperlink[h].RID)
}
}
}
return link, target
}
// MergeCell provides a function to merge cells by given coordinate area and
// sheet name. For example create a merged cell of D3:E9 on Sheet1:
//
// xlsx.MergeCell("Sheet1", "D3", "E9")
//
// If you create a merged cell that overlaps with another existing merged cell,
// those merged cells that already exist will be removed.
func (f *File) MergeCell(sheet, hcell, vcell string) {
if hcell == vcell {
return
}
hcell = strings.ToUpper(hcell)
vcell = strings.ToUpper(vcell)
// Coordinate conversion, convert C1:B3 to 2,0,1,2.
hcol := string(strings.Map(letterOnlyMapF, hcell))
hrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, hcell))
hyAxis := hrow - 1
hxAxis := TitleToNumber(hcol)
vcol := string(strings.Map(letterOnlyMapF, vcell))
vrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, vcell))
vyAxis := vrow - 1
vxAxis := TitleToNumber(vcol)
if vxAxis < hxAxis {
hcell, vcell = vcell, hcell
vxAxis, hxAxis = hxAxis, vxAxis
}
if vyAxis < hyAxis {
hcell, vcell = vcell, hcell
vyAxis, hyAxis = hyAxis, vyAxis
}
xlsx := f.workSheetReader(sheet)
if xlsx.MergeCells != nil {
mergeCell := xlsxMergeCell{}
// Correct the coordinate area, such correct C1:B3 to B1:C3.
mergeCell.Ref = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
// Delete the merged cells of the overlapping area.
for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
if checkCellInArea(hcell, xlsx.MergeCells.Cells[i].Ref) || checkCellInArea(strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0], mergeCell.Ref) {
xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...)
} else if checkCellInArea(vcell, xlsx.MergeCells.Cells[i].Ref) || checkCellInArea(strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[1], mergeCell.Ref) {
xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:i], xlsx.MergeCells.Cells[i+1:]...)
}
}
xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells, &mergeCell)
} else {
mergeCell := xlsxMergeCell{}
// Correct the coordinate area, such correct C1:B3 to B1:C3.
mergeCell.Ref = ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
mergeCells := xlsxMergeCells{}
mergeCells.Cells = append(mergeCells.Cells, &mergeCell)
xlsx.MergeCells = &mergeCells
}
}
// SetCellInt provides a function to set int type value of a cell by given
// worksheet name, cell coordinates and cell value.
func (f *File) SetCellInt(sheet, axis string, value int) {
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
col := string(strings.Map(letterOnlyMapF, axis))
row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
if err != nil {
return
}
xAxis := row - 1
yAxis := TitleToNumber(col)
rows := xAxis + 1
cell := yAxis + 1
completeRow(xlsx, rows, cell)
completeCol(xlsx, rows, cell)
xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
}
// prepareCellStyle provides a function to prepare style index of cell in
// worksheet by given column index and style index.
func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
if xlsx.Cols != nil && style == 0 {
for _, v := range xlsx.Cols.Col {
if v.Min <= col && col <= v.Max {
style = v.Style
}
}
}
return style
}
// SetCellStr provides a function to set string type value of a cell. Total
// number of characters that a cell can contain 32767 characters.
func (f *File) SetCellStr(sheet, axis, value string) {
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
if len(value) > 32767 {
value = value[0:32767]
}
col := string(strings.Map(letterOnlyMapF, axis))
row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
if err != nil {
return
}
xAxis := row - 1
yAxis := TitleToNumber(col)
rows := xAxis + 1
cell := yAxis + 1
completeRow(xlsx, rows, cell)
completeCol(xlsx, rows, cell)
// Leading space(s) character detection.
if len(value) > 0 {
if value[0] == 32 {
xlsx.SheetData.Row[xAxis].C[yAxis].XMLSpace = xml.Attr{
Name: xml.Name{Space: NameSpaceXML, Local: "space"},
Value: "preserve",
}
}
}
xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
xlsx.SheetData.Row[xAxis].C[yAxis].T = "str"
xlsx.SheetData.Row[xAxis].C[yAxis].V = value
}
// SetCellDefault provides a function to set string type value of a cell as
// default format without escaping the cell.
func (f *File) SetCellDefault(sheet, axis, value string) {
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
col := string(strings.Map(letterOnlyMapF, axis))
row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
if err != nil {
return
}
xAxis := row - 1
yAxis := TitleToNumber(col)
rows := xAxis + 1
cell := yAxis + 1
completeRow(xlsx, rows, cell)
completeCol(xlsx, rows, cell)
xlsx.SheetData.Row[xAxis].C[yAxis].S = f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
xlsx.SheetData.Row[xAxis].C[yAxis].V = value
}
// SetSheetRow writes an array to row by given worksheet name, starting
// coordinate and a pointer to array type 'slice'. For example, writes an
// array to row 6 start with the cell B6 on Sheet1:
//
// xlsx.SetSheetRow("Sheet1", "B6", &[]interface{}{"1", nil, 2})
//
func (f *File) SetSheetRow(sheet, axis string, slice interface{}) {
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
col := string(strings.Map(letterOnlyMapF, axis))
row, err := strconv.Atoi(strings.Map(intOnlyMapF, axis))
if err != nil {
return
}
// Make sure 'slice' is a Ptr to Slice
v := reflect.ValueOf(slice)
if v.Kind() != reflect.Ptr {
return
}
v = v.Elem()
if v.Kind() != reflect.Slice {
return
}
xAxis := row - 1
yAxis := TitleToNumber(col)
rows := xAxis + 1
cell := yAxis + 1
completeRow(xlsx, rows, cell)
completeCol(xlsx, rows, cell)
idx := 0
for i := cell - 1; i < v.Len()+cell-1; i++ {
c := ToAlphaString(i) + strconv.Itoa(row)
f.SetCellValue(sheet, c, v.Index(idx).Interface())
idx++
}
}
// checkCellInArea provides a function to determine if a given coordinate is
// within an area.
func checkCellInArea(cell, area string) bool {
cell = strings.ToUpper(cell)
area = strings.ToUpper(area)
ref := strings.Split(area, ":")
if len(ref) < 2 {
return false
}
from := ref[0]
to := ref[1]
col, row := getCellColRow(cell)
fromCol, fromRow := getCellColRow(from)
toCol, toRow := getCellColRow(to)
return axisLowerOrEqualThan(fromCol, col) && axisLowerOrEqualThan(col, toCol) && axisLowerOrEqualThan(fromRow, row) && axisLowerOrEqualThan(row, toRow)
}

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +0,0 @@
tenets:
- import: codelingo/effective-go
- import: codelingo/code-review-comments

View File

@ -1,376 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"bytes"
"math"
"strconv"
"strings"
)
// Define the default cell size and EMU unit of measurement.
const (
defaultColWidthPixels float64 = 64
defaultRowHeightPixels float64 = 20
EMU int = 9525
)
// GetColVisible provides a function to get visible of a single column by given
// worksheet name and column name. For example, get visible state of column D
// in Sheet1:
//
// xlsx.GetColVisible("Sheet1", "D")
//
func (f *File) GetColVisible(sheet, column string) bool {
xlsx := f.workSheetReader(sheet)
col := TitleToNumber(strings.ToUpper(column)) + 1
visible := true
if xlsx.Cols == nil {
return visible
}
for c := range xlsx.Cols.Col {
if xlsx.Cols.Col[c].Min <= col && col <= xlsx.Cols.Col[c].Max {
visible = !xlsx.Cols.Col[c].Hidden
}
}
return visible
}
// SetColVisible provides a function to set visible of a single column by given
// worksheet name and column name. For example, hide column D in Sheet1:
//
// xlsx.SetColVisible("Sheet1", "D", false)
//
func (f *File) SetColVisible(sheet, column string, visible bool) {
xlsx := f.workSheetReader(sheet)
c := TitleToNumber(strings.ToUpper(column)) + 1
col := xlsxCol{
Min: c,
Max: c,
Hidden: !visible,
CustomWidth: true,
}
if xlsx.Cols == nil {
cols := xlsxCols{}
cols.Col = append(cols.Col, col)
xlsx.Cols = &cols
return
}
for v := range xlsx.Cols.Col {
if xlsx.Cols.Col[v].Min <= c && c <= xlsx.Cols.Col[v].Max {
col = xlsx.Cols.Col[v]
}
}
col.Min = c
col.Max = c
col.Hidden = !visible
col.CustomWidth = true
xlsx.Cols.Col = append(xlsx.Cols.Col, col)
}
// GetColOutlineLevel provides a function to get outline level of a single
// column by given worksheet name and column name. For example, get outline
// level of column D in Sheet1:
//
// xlsx.GetColOutlineLevel("Sheet1", "D")
//
func (f *File) GetColOutlineLevel(sheet, column string) uint8 {
xlsx := f.workSheetReader(sheet)
col := TitleToNumber(strings.ToUpper(column)) + 1
level := uint8(0)
if xlsx.Cols == nil {
return level
}
for c := range xlsx.Cols.Col {
if xlsx.Cols.Col[c].Min <= col && col <= xlsx.Cols.Col[c].Max {
level = xlsx.Cols.Col[c].OutlineLevel
}
}
return level
}
// SetColOutlineLevel provides a function to set outline level of a single
// column by given worksheet name and column name. For example, set outline
// level of column D in Sheet1 to 2:
//
// xlsx.SetColOutlineLevel("Sheet1", "D", 2)
//
func (f *File) SetColOutlineLevel(sheet, column string, level uint8) {
xlsx := f.workSheetReader(sheet)
c := TitleToNumber(strings.ToUpper(column)) + 1
col := xlsxCol{
Min: c,
Max: c,
OutlineLevel: level,
CustomWidth: true,
}
if xlsx.Cols == nil {
cols := xlsxCols{}
cols.Col = append(cols.Col, col)
xlsx.Cols = &cols
return
}
for v := range xlsx.Cols.Col {
if xlsx.Cols.Col[v].Min <= c && c <= xlsx.Cols.Col[v].Max {
col = xlsx.Cols.Col[v]
}
}
col.Min = c
col.Max = c
col.OutlineLevel = level
col.CustomWidth = true
xlsx.Cols.Col = append(xlsx.Cols.Col, col)
}
// SetColWidth provides a function to set the width of a single column or
// multiple columns. For example:
//
// xlsx := excelize.NewFile()
// xlsx.SetColWidth("Sheet1", "A", "H", 20)
// err := xlsx.Save()
// if err != nil {
// fmt.Println(err)
// }
//
func (f *File) SetColWidth(sheet, startcol, endcol string, width float64) {
min := TitleToNumber(strings.ToUpper(startcol)) + 1
max := TitleToNumber(strings.ToUpper(endcol)) + 1
if min > max {
min, max = max, min
}
xlsx := f.workSheetReader(sheet)
col := xlsxCol{
Min: min,
Max: max,
Width: width,
CustomWidth: true,
}
if xlsx.Cols != nil {
xlsx.Cols.Col = append(xlsx.Cols.Col, col)
} else {
cols := xlsxCols{}
cols.Col = append(cols.Col, col)
xlsx.Cols = &cols
}
}
// positionObjectPixels calculate the vertices that define the position of a
// graphical object within the worksheet in pixels.
//
// +------------+------------+
// | A | B |
// +-----+------------+------------+
// | |(x1,y1) | |
// | 1 |(A1)._______|______ |
// | | | | |
// | | | | |
// +-----+----| OBJECT |-----+
// | | | | |
// | 2 | |______________. |
// | | | (B2)|
// | | | (x2,y2)|
// +-----+------------+------------+
//
// Example of an object that covers some of the area from cell A1 to B2.
//
// Based on the width and height of the object we need to calculate 8 vars:
//
// colStart, rowStart, colEnd, rowEnd, x1, y1, x2, y2.
//
// We also calculate the absolute x and y position of the top left vertex of
// the object. This is required for images.
//
// The width and height of the cells that the object occupies can be
// variable and have to be taken into account.
//
// The values of col_start and row_start are passed in from the calling
// function. The values of col_end and row_end are calculated by
// subtracting the width and height of the object from the width and
// height of the underlying cells.
//
// colStart # Col containing upper left corner of object.
// x1 # Distance to left side of object.
//
// rowStart # Row containing top left corner of object.
// y1 # Distance to top of object.
//
// colEnd # Col containing lower right corner of object.
// x2 # Distance to right side of object.
//
// rowEnd # Row containing bottom right corner of object.
// y2 # Distance to bottom of object.
//
// width # Width of object frame.
// height # Height of object frame.
//
// xAbs # Absolute distance to left side of object.
// yAbs # Absolute distance to top side of object.
//
func (f *File) positionObjectPixels(sheet string, colStart, rowStart, x1, y1, width, height int) (int, int, int, int, int, int, int, int) {
xAbs := 0
yAbs := 0
// Calculate the absolute x offset of the top-left vertex.
for colID := 1; colID <= colStart; colID++ {
xAbs += f.getColWidth(sheet, colID)
}
xAbs += x1
// Calculate the absolute y offset of the top-left vertex.
// Store the column change to allow optimisations.
for rowID := 1; rowID <= rowStart; rowID++ {
yAbs += f.getRowHeight(sheet, rowID)
}
yAbs += y1
// Adjust start column for offsets that are greater than the col width.
for x1 >= f.getColWidth(sheet, colStart) {
x1 -= f.getColWidth(sheet, colStart)
colStart++
}
// Adjust start row for offsets that are greater than the row height.
for y1 >= f.getRowHeight(sheet, rowStart) {
y1 -= f.getRowHeight(sheet, rowStart)
rowStart++
}
// Initialise end cell to the same as the start cell.
colEnd := colStart
rowEnd := rowStart
width += x1
height += y1
// Subtract the underlying cell widths to find end cell of the object.
for width >= f.getColWidth(sheet, colEnd) {
colEnd++
width -= f.getColWidth(sheet, colEnd)
}
// Subtract the underlying cell heights to find end cell of the object.
for height >= f.getRowHeight(sheet, rowEnd) {
rowEnd++
height -= f.getRowHeight(sheet, rowEnd)
}
// The end vertices are whatever is left from the width and height.
x2 := width
y2 := height
return colStart, rowStart, xAbs, yAbs, colEnd, rowEnd, x2, y2
}
// getColWidth provides a function to get column width in pixels by given
// sheet name and column index.
func (f *File) getColWidth(sheet string, col int) int {
xlsx := f.workSheetReader(sheet)
if xlsx.Cols != nil {
var width float64
for _, v := range xlsx.Cols.Col {
if v.Min <= col && col <= v.Max {
width = v.Width
}
}
if width != 0 {
return int(convertColWidthToPixels(width))
}
}
// Optimisation for when the column widths haven't changed.
return int(defaultColWidthPixels)
}
// GetColWidth provides a function to get column width by given worksheet name
// and column index.
func (f *File) GetColWidth(sheet, column string) float64 {
col := TitleToNumber(strings.ToUpper(column)) + 1
xlsx := f.workSheetReader(sheet)
if xlsx.Cols != nil {
var width float64
for _, v := range xlsx.Cols.Col {
if v.Min <= col && col <= v.Max {
width = v.Width
}
}
if width != 0 {
return width
}
}
// Optimisation for when the column widths haven't changed.
return defaultColWidthPixels
}
// InsertCol provides a function to insert a new column before given column
// index. For example, create a new column before column C in Sheet1:
//
// xlsx.InsertCol("Sheet1", "C")
//
func (f *File) InsertCol(sheet, column string) {
col := TitleToNumber(strings.ToUpper(column))
f.adjustHelper(sheet, col, -1, 1)
}
// RemoveCol provides a function to remove single column by given worksheet
// name and column index. For example, remove column C in Sheet1:
//
// xlsx.RemoveCol("Sheet1", "C")
//
func (f *File) RemoveCol(sheet, column string) {
xlsx := f.workSheetReader(sheet)
for r := range xlsx.SheetData.Row {
for k, v := range xlsx.SheetData.Row[r].C {
axis := v.R
col := string(strings.Map(letterOnlyMapF, axis))
if col == column {
xlsx.SheetData.Row[r].C = append(xlsx.SheetData.Row[r].C[:k], xlsx.SheetData.Row[r].C[k+1:]...)
}
}
}
col := TitleToNumber(strings.ToUpper(column))
f.adjustHelper(sheet, col, -1, -1)
}
// completeCol provieds function to completion column element tags of XML in a
// sheet.
func completeCol(xlsx *xlsxWorksheet, row, cell int) {
buffer := bytes.Buffer{}
for r := range xlsx.SheetData.Row {
if len(xlsx.SheetData.Row[r].C) < cell {
start := len(xlsx.SheetData.Row[r].C)
for iii := start; iii < cell; iii++ {
buffer.WriteString(ToAlphaString(iii))
buffer.WriteString(strconv.Itoa(r + 1))
xlsx.SheetData.Row[r].C = append(xlsx.SheetData.Row[r].C, xlsxC{
R: buffer.String(),
})
buffer.Reset()
}
}
}
}
// convertColWidthToPixels provieds function to convert the width of a cell
// from user's units to pixels. Excel rounds the column width to the nearest
// pixel. If the width hasn't been set by the user we use the default value.
// If the column is hidden it has a value of zero.
func convertColWidthToPixels(width float64) float64 {
var padding float64 = 5
var pixels float64
var maxDigitWidth float64 = 7
if width == 0 {
return pixels
}
if width < 1 {
pixels = (width * 12) + 0.5
return math.Ceil(pixels)
}
pixels = (width*maxDigitWidth + 0.5) + padding
return math.Ceil(pixels)
}

View File

@ -1,273 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"encoding/json"
"encoding/xml"
"fmt"
"strconv"
"strings"
)
// parseFormatCommentsSet provides a function to parse the format settings of
// the comment with default value.
func parseFormatCommentsSet(formatSet string) (*formatComment, error) {
format := formatComment{
Author: "Author:",
Text: " ",
}
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}
// GetComments retrieves all comments and returns a map of worksheet name to
// the worksheet comments.
func (f *File) GetComments() (comments map[string][]Comment) {
comments = map[string][]Comment{}
for n := range f.sheetMap {
commentID := f.GetSheetIndex(n)
commentsXML := "xl/comments" + strconv.Itoa(commentID) + ".xml"
c, ok := f.XLSX[commentsXML]
if ok {
d := xlsxComments{}
xml.Unmarshal([]byte(c), &d)
sheetComments := []Comment{}
for _, comment := range d.CommentList.Comment {
sheetComment := Comment{}
if comment.AuthorID < len(d.Authors) {
sheetComment.Author = d.Authors[comment.AuthorID].Author
}
sheetComment.Ref = comment.Ref
sheetComment.AuthorID = comment.AuthorID
for _, text := range comment.Text.R {
sheetComment.Text += text.T
}
sheetComments = append(sheetComments, sheetComment)
}
comments[n] = sheetComments
}
}
return
}
// AddComment provides the method to add comment in a sheet by given worksheet
// index, cell and format set (such as author and text). Note that the max
// author length is 255 and the max text length is 32512. For example, add a
// comment in Sheet1!$A$30:
//
// xlsx.AddComment("Sheet1", "A30", `{"author":"Excelize: ","text":"This is a comment."}`)
//
func (f *File) AddComment(sheet, cell, format string) error {
formatSet, err := parseFormatCommentsSet(format)
if err != nil {
return err
}
// Read sheet data.
xlsx := f.workSheetReader(sheet)
commentID := f.countComments() + 1
drawingVML := "xl/drawings/vmlDrawing" + strconv.Itoa(commentID) + ".vml"
sheetRelationshipsComments := "../comments" + strconv.Itoa(commentID) + ".xml"
sheetRelationshipsDrawingVML := "../drawings/vmlDrawing" + strconv.Itoa(commentID) + ".vml"
if xlsx.LegacyDrawing != nil {
// The worksheet already has a comments relationships, use the relationships drawing ../drawings/vmlDrawing%d.vml.
sheetRelationshipsDrawingVML = f.getSheetRelationshipsTargetByID(sheet, xlsx.LegacyDrawing.RID)
commentID, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(sheetRelationshipsDrawingVML, "../drawings/vmlDrawing"), ".vml"))
drawingVML = strings.Replace(sheetRelationshipsDrawingVML, "..", "xl", -1)
} else {
// Add first comment for given sheet.
rID := f.addSheetRelationships(sheet, SourceRelationshipDrawingVML, sheetRelationshipsDrawingVML, "")
f.addSheetRelationships(sheet, SourceRelationshipComments, sheetRelationshipsComments, "")
f.addSheetLegacyDrawing(sheet, rID)
}
commentsXML := "xl/comments" + strconv.Itoa(commentID) + ".xml"
f.addComment(commentsXML, cell, formatSet)
var colCount int
for i, l := range strings.Split(formatSet.Text, "\n") {
if ll := len(l); ll > colCount {
if i == 0 {
ll += len(formatSet.Author)
}
colCount = ll
}
}
f.addDrawingVML(commentID, drawingVML, cell, strings.Count(formatSet.Text, "\n")+1, colCount)
f.addContentTypePart(commentID, "comments")
return err
}
// addDrawingVML provides a function to create comment as
// xl/drawings/vmlDrawing%d.vml by given commit ID and cell.
func (f *File) addDrawingVML(commentID int, drawingVML, cell string, lineCount, colCount int) {
col := string(strings.Map(letterOnlyMapF, cell))
row, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
xAxis := row - 1
yAxis := TitleToNumber(col)
vml := vmlDrawing{
XMLNSv: "urn:schemas-microsoft-com:vml",
XMLNSo: "urn:schemas-microsoft-com:office:office",
XMLNSx: "urn:schemas-microsoft-com:office:excel",
XMLNSmv: "http://macVmlSchemaUri",
Shapelayout: &xlsxShapelayout{
Ext: "edit",
IDmap: &xlsxIDmap{
Ext: "edit",
Data: commentID,
},
},
Shapetype: &xlsxShapetype{
ID: "_x0000_t202",
Coordsize: "21600,21600",
Spt: 202,
Path: "m0,0l0,21600,21600,21600,21600,0xe",
Stroke: &xlsxStroke{
Joinstyle: "miter",
},
VPath: &vPath{
Gradientshapeok: "t",
Connecttype: "miter",
},
},
}
sp := encodeShape{
Fill: &vFill{
Color2: "#fbfe82",
Angle: -180,
Type: "gradient",
Fill: &oFill{
Ext: "view",
Type: "gradientUnscaled",
},
},
Shadow: &vShadow{
On: "t",
Color: "black",
Obscured: "t",
},
Path: &vPath{
Connecttype: "none",
},
Textbox: &vTextbox{
Style: "mso-direction-alt:auto",
Div: &xlsxDiv{
Style: "text-align:left",
},
},
ClientData: &xClientData{
ObjectType: "Note",
Anchor: fmt.Sprintf(
"%d, 23, %d, 0, %d, %d, %d, 5",
1+yAxis, 1+xAxis, 2+yAxis+lineCount, colCount+yAxis, 2+xAxis+lineCount),
AutoFill: "True",
Row: xAxis,
Column: yAxis,
},
}
s, _ := xml.Marshal(sp)
shape := xlsxShape{
ID: "_x0000_s1025",
Type: "#_x0000_t202",
Style: "position:absolute;73.5pt;width:108pt;height:59.25pt;z-index:1;visibility:hidden",
Fillcolor: "#fbf6d6",
Strokecolor: "#edeaa1",
Val: string(s[13 : len(s)-14]),
}
c, ok := f.XLSX[drawingVML]
if ok {
d := decodeVmlDrawing{}
_ = xml.Unmarshal(namespaceStrictToTransitional(c), &d)
for _, v := range d.Shape {
s := xlsxShape{
ID: "_x0000_s1025",
Type: "#_x0000_t202",
Style: "position:absolute;73.5pt;width:108pt;height:59.25pt;z-index:1;visibility:hidden",
Fillcolor: "#fbf6d6",
Strokecolor: "#edeaa1",
Val: v.Val,
}
vml.Shape = append(vml.Shape, s)
}
}
vml.Shape = append(vml.Shape, shape)
v, _ := xml.Marshal(vml)
f.XLSX[drawingVML] = v
}
// addComment provides a function to create chart as xl/comments%d.xml by
// given cell and format sets.
func (f *File) addComment(commentsXML, cell string, formatSet *formatComment) {
a := formatSet.Author
t := formatSet.Text
if len(a) > 255 {
a = a[0:255]
}
if len(t) > 32512 {
t = t[0:32512]
}
comments := xlsxComments{
Authors: []xlsxAuthor{
{
Author: formatSet.Author,
},
},
}
cmt := xlsxComment{
Ref: cell,
AuthorID: 0,
Text: xlsxText{
R: []xlsxR{
{
RPr: &xlsxRPr{
B: " ",
Sz: &attrValFloat{Val: 9},
Color: &xlsxColor{
Indexed: 81,
},
RFont: &attrValString{Val: "Calibri"},
Family: &attrValInt{Val: 2},
},
T: a,
},
{
RPr: &xlsxRPr{
Sz: &attrValFloat{Val: 9},
Color: &xlsxColor{
Indexed: 81,
},
RFont: &attrValString{Val: "Calibri"},
Family: &attrValInt{Val: 2},
},
T: t,
},
},
},
}
c, ok := f.XLSX[commentsXML]
if ok {
d := xlsxComments{}
_ = xml.Unmarshal(namespaceStrictToTransitional(c), &d)
comments.CommentList.Comment = append(comments.CommentList.Comment, d.CommentList.Comment...)
}
comments.CommentList.Comment = append(comments.CommentList.Comment, cmt)
v, _ := xml.Marshal(comments)
f.saveFileList(commentsXML, v)
}
// countComments provides a function to get comments files count storage in
// the folder xl.
func (f *File) countComments() int {
count := 0
for k := range f.XLSX {
if strings.Contains(k, "xl/comments") {
count++
}
}
return count
}

View File

@ -1,233 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"fmt"
"strings"
)
// DataValidationType defined the type of data validation.
type DataValidationType int
// Data validation types.
const (
_DataValidationType = iota
typeNone // inline use
DataValidationTypeCustom
DataValidationTypeDate
DataValidationTypeDecimal
typeList // inline use
DataValidationTypeTextLeng
DataValidationTypeTime
// DataValidationTypeWhole Integer
DataValidationTypeWhole
)
const (
// dataValidationFormulaStrLen 255 characters+ 2 quotes
dataValidationFormulaStrLen = 257
// dataValidationFormulaStrLenErr
dataValidationFormulaStrLenErr = "data validation must be 0-255 characters"
)
// DataValidationErrorStyle defined the style of data validation error alert.
type DataValidationErrorStyle int
// Data validation error styles.
const (
_ DataValidationErrorStyle = iota
DataValidationErrorStyleStop
DataValidationErrorStyleWarning
DataValidationErrorStyleInformation
)
// Data validation error styles.
const (
styleStop = "stop"
styleWarning = "warning"
styleInformation = "information"
)
// DataValidationOperator operator enum.
type DataValidationOperator int
// Data validation operators.
const (
_DataValidationOperator = iota
DataValidationOperatorBetween
DataValidationOperatorEqual
DataValidationOperatorGreaterThan
DataValidationOperatorGreaterThanOrEqual
DataValidationOperatorLessThan
DataValidationOperatorLessThanOrEqual
DataValidationOperatorNotBetween
DataValidationOperatorNotEqual
)
// NewDataValidation return data validation struct.
func NewDataValidation(allowBlank bool) *DataValidation {
return &DataValidation{
AllowBlank: allowBlank,
ShowErrorMessage: false,
ShowInputMessage: false,
}
}
// SetError set error notice.
func (dd *DataValidation) SetError(style DataValidationErrorStyle, title, msg string) {
dd.Error = &msg
dd.ErrorTitle = &title
strStyle := styleStop
switch style {
case DataValidationErrorStyleStop:
strStyle = styleStop
case DataValidationErrorStyleWarning:
strStyle = styleWarning
case DataValidationErrorStyleInformation:
strStyle = styleInformation
}
dd.ShowErrorMessage = true
dd.ErrorStyle = &strStyle
}
// SetInput set prompt notice.
func (dd *DataValidation) SetInput(title, msg string) {
dd.ShowInputMessage = true
dd.PromptTitle = &title
dd.Prompt = &msg
}
// SetDropList data validation list.
func (dd *DataValidation) SetDropList(keys []string) error {
dd.Formula1 = "\"" + strings.Join(keys, ",") + "\""
dd.Type = convDataValidationType(typeList)
return nil
}
// SetRange provides function to set data validation range in drop list.
func (dd *DataValidation) SetRange(f1, f2 int, t DataValidationType, o DataValidationOperator) error {
formula1 := fmt.Sprintf("%d", f1)
formula2 := fmt.Sprintf("%d", f2)
if dataValidationFormulaStrLen < len(dd.Formula1) || dataValidationFormulaStrLen < len(dd.Formula2) {
return fmt.Errorf(dataValidationFormulaStrLenErr)
}
dd.Formula1 = formula1
dd.Formula2 = formula2
dd.Type = convDataValidationType(t)
dd.Operator = convDataValidationOperatior(o)
return nil
}
// SetSqrefDropList provides set data validation on a range with source
// reference range of the worksheet by given data validation object and
// worksheet name. The data validation object can be created by
// NewDataValidation function. For example, set data validation on
// Sheet1!A7:B8 with validation criteria source Sheet1!E1:E3 settings, create
// in-cell dropdown by allowing list source:
//
// dvRange := excelize.NewDataValidation(true)
// dvRange.Sqref = "A7:B8"
// dvRange.SetSqrefDropList("E1:E3", true)
// xlsx.AddDataValidation("Sheet1", dvRange)
//
func (dd *DataValidation) SetSqrefDropList(sqref string, isCurrentSheet bool) error {
if isCurrentSheet {
dd.Formula1 = sqref
dd.Type = convDataValidationType(typeList)
return nil
}
return fmt.Errorf("cross-sheet sqref cell are not supported")
}
// SetSqref provides function to set data validation range in drop list.
func (dd *DataValidation) SetSqref(sqref string) {
if dd.Sqref == "" {
dd.Sqref = sqref
} else {
dd.Sqref = fmt.Sprintf("%s %s", dd.Sqref, sqref)
}
}
// convDataValidationType get excel data validation type.
func convDataValidationType(t DataValidationType) string {
typeMap := map[DataValidationType]string{
typeNone: "none",
DataValidationTypeCustom: "custom",
DataValidationTypeDate: "date",
DataValidationTypeDecimal: "decimal",
typeList: "list",
DataValidationTypeTextLeng: "textLength",
DataValidationTypeTime: "time",
DataValidationTypeWhole: "whole",
}
return typeMap[t]
}
// convDataValidationOperatior get excel data validation operator.
func convDataValidationOperatior(o DataValidationOperator) string {
typeMap := map[DataValidationOperator]string{
DataValidationOperatorBetween: "between",
DataValidationOperatorEqual: "equal",
DataValidationOperatorGreaterThan: "greaterThan",
DataValidationOperatorGreaterThanOrEqual: "greaterThanOrEqual",
DataValidationOperatorLessThan: "lessThan",
DataValidationOperatorLessThanOrEqual: "lessThanOrEqual",
DataValidationOperatorNotBetween: "notBetween",
DataValidationOperatorNotEqual: "notEqual",
}
return typeMap[o]
}
// AddDataValidation provides set data validation on a range of the worksheet
// by given data validation object and worksheet name. The data validation
// object can be created by NewDataValidation function.
//
// Example 1, set data validation on Sheet1!A1:B2 with validation criteria
// settings, show error alert after invalid data is entered with "Stop" style
// and custom title "error body":
//
// dvRange := excelize.NewDataValidation(true)
// dvRange.Sqref = "A1:B2"
// dvRange.SetRange(10, 20, excelize.DataValidationTypeWhole, excelize.DataValidationOperatorBetween)
// dvRange.SetError(excelize.DataValidationErrorStyleStop, "error title", "error body")
// xlsx.AddDataValidation("Sheet1", dvRange)
//
// Example 2, set data validation on Sheet1!A3:B4 with validation criteria
// settings, and show input message when cell is selected:
//
// dvRange = excelize.NewDataValidation(true)
// dvRange.Sqref = "A3:B4"
// dvRange.SetRange(10, 20, excelize.DataValidationTypeWhole, excelize.DataValidationOperatorGreaterThan)
// dvRange.SetInput("input title", "input body")
// xlsx.AddDataValidation("Sheet1", dvRange)
//
// Example 3, set data validation on Sheet1!A5:B6 with validation criteria
// settings, create in-cell dropdown by allowing list source:
//
// dvRange = excelize.NewDataValidation(true)
// dvRange.Sqref = "A5:B6"
// dvRange.SetDropList([]string{"1", "2", "3"})
// xlsx.AddDataValidation("Sheet1", dvRange)
//
func (f *File) AddDataValidation(sheet string, dv *DataValidation) {
xlsx := f.workSheetReader(sheet)
if nil == xlsx.DataValidations {
xlsx.DataValidations = new(xlsxDataValidations)
}
xlsx.DataValidations.DataValidation = append(xlsx.DataValidations.DataValidation, dv)
xlsx.DataValidations.Count = len(xlsx.DataValidations.DataValidation)
}

View File

@ -1,151 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"math"
"time"
)
// timeLocationUTC defined the UTC time location.
var timeLocationUTC, _ = time.LoadLocation("UTC")
// timeToUTCTime provides a function to convert time to UTC time.
func timeToUTCTime(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), timeLocationUTC)
}
// timeToExcelTime provides a function to convert time to Excel time.
func timeToExcelTime(t time.Time) float64 {
// TODO in future this should probably also handle date1904 and like TimeFromExcelTime
var excelTime float64
var deltaDays int64
excelTime = 0
deltaDays = 290 * 364
// check if UnixNano would be out of int64 range
for t.Unix() > deltaDays*24*60*60 {
// reduce by aprox. 290 years, which is max for int64 nanoseconds
delta := time.Duration(deltaDays) * 24 * time.Hour
excelTime = excelTime + float64(deltaDays)
t = t.Add(-delta)
}
// finally add remainder of UnixNano to keep nano precision
// and 25569 which is days between 1900 and 1970
return excelTime + float64(t.UnixNano())/8.64e13 + 25569.0
}
// shiftJulianToNoon provides a function to process julian date to noon.
func shiftJulianToNoon(julianDays, julianFraction float64) (float64, float64) {
switch {
case -0.5 < julianFraction && julianFraction < 0.5:
julianFraction += 0.5
case julianFraction >= 0.5:
julianDays++
julianFraction -= 0.5
case julianFraction <= -0.5:
julianDays--
julianFraction += 1.5
}
return julianDays, julianFraction
}
// fractionOfADay provides a function to return the integer values for hour,
// minutes, seconds and nanoseconds that comprised a given fraction of a day.
// values would round to 1 us.
func fractionOfADay(fraction float64) (hours, minutes, seconds, nanoseconds int) {
const (
c1us = 1e3
c1s = 1e9
c1day = 24 * 60 * 60 * c1s
)
frac := int64(c1day*fraction + c1us/2)
nanoseconds = int((frac%c1s)/c1us) * c1us
frac /= c1s
seconds = int(frac % 60)
frac /= 60
minutes = int(frac % 60)
hours = int(frac / 60)
return
}
// julianDateToGregorianTime provides a function to convert julian date to
// gregorian time.
func julianDateToGregorianTime(part1, part2 float64) time.Time {
part1I, part1F := math.Modf(part1)
part2I, part2F := math.Modf(part2)
julianDays := part1I + part2I
julianFraction := part1F + part2F
julianDays, julianFraction = shiftJulianToNoon(julianDays, julianFraction)
day, month, year := doTheFliegelAndVanFlandernAlgorithm(int(julianDays))
hours, minutes, seconds, nanoseconds := fractionOfADay(julianFraction)
return time.Date(year, time.Month(month), day, hours, minutes, seconds, nanoseconds, time.UTC)
}
// doTheFliegelAndVanFlandernAlgorithm; By this point generations of
// programmers have repeated the algorithm sent to the editor of
// "Communications of the ACM" in 1968 (published in CACM, volume 11, number
// 10, October 1968, p.657). None of those programmers seems to have found it
// necessary to explain the constants or variable names set out by Henry F.
// Fliegel and Thomas C. Van Flandern. Maybe one day I'll buy that jounal and
// expand an explanation here - that day is not today.
func doTheFliegelAndVanFlandernAlgorithm(jd int) (day, month, year int) {
l := jd + 68569
n := (4 * l) / 146097
l = l - (146097*n+3)/4
i := (4000 * (l + 1)) / 1461001
l = l - (1461*i)/4 + 31
j := (80 * l) / 2447
d := l - (2447*j)/80
l = j / 11
m := j + 2 - (12 * l)
y := 100*(n-49) + i + l
return d, m, y
}
// timeFromExcelTime provides a function to convert an excelTime
// representation (stored as a floating point number) to a time.Time.
func timeFromExcelTime(excelTime float64, date1904 bool) time.Time {
const MDD int64 = 106750 // Max time.Duration Days, aprox. 290 years
var date time.Time
var intPart = int64(excelTime)
// Excel uses Julian dates prior to March 1st 1900, and Gregorian
// thereafter.
if intPart <= 61 {
const OFFSET1900 = 15018.0
const OFFSET1904 = 16480.0
const MJD0 float64 = 2400000.5
var date time.Time
if date1904 {
date = julianDateToGregorianTime(MJD0, excelTime+OFFSET1904)
} else {
date = julianDateToGregorianTime(MJD0, excelTime+OFFSET1900)
}
return date
}
var floatPart = excelTime - float64(intPart)
var dayNanoSeconds float64 = 24 * 60 * 60 * 1000 * 1000 * 1000
if date1904 {
date = time.Date(1904, 1, 1, 0, 0, 0, 0, time.UTC)
} else {
date = time.Date(1899, 12, 30, 0, 0, 0, 0, time.UTC)
}
// Duration is limited to aprox. 290 years
for intPart > MDD {
durationDays := time.Duration(MDD) * time.Hour * 24
date = date.Add(durationDays)
intPart = intPart - MDD
}
durationDays := time.Duration(intPart) * time.Hour * 24
durationPart := time.Duration(dayNanoSeconds * floatPart)
return date.Add(durationDays).Add(durationPart)
}

View File

@ -1,456 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
//
// See https://xuri.me/excelize for more information about this package.
package excelize
import (
"archive/zip"
"bytes"
"encoding/xml"
"io"
"io/ioutil"
"os"
"strconv"
"strings"
)
// File define a populated XLSX file struct.
type File struct {
checked map[string]bool
sheetMap map[string]string
ContentTypes *xlsxTypes
Path string
SharedStrings *xlsxSST
Sheet map[string]*xlsxWorksheet
SheetCount int
Styles *xlsxStyleSheet
Theme *xlsxTheme
WorkBook *xlsxWorkbook
WorkBookRels *xlsxWorkbookRels
XLSX map[string][]byte
}
// OpenFile take the name of an XLSX file and returns a populated XLSX file
// struct for it.
func OpenFile(filename string) (*File, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
f, err := OpenReader(file)
if err != nil {
return nil, err
}
f.Path = filename
return f, nil
}
// OpenReader take an io.Reader and return a populated XLSX file.
func OpenReader(r io.Reader) (*File, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
return nil, err
}
file, sheetCount, err := ReadZipReader(zr)
if err != nil {
return nil, err
}
f := &File{
checked: make(map[string]bool),
Sheet: make(map[string]*xlsxWorksheet),
SheetCount: sheetCount,
XLSX: file,
}
f.sheetMap = f.getSheetMap()
f.Styles = f.stylesReader()
f.Theme = f.themeReader()
return f, nil
}
// setDefaultTimeStyle provides a function to set default numbers format for
// time.Time type cell value by given worksheet name, cell coordinates and
// number format code.
func (f *File) setDefaultTimeStyle(sheet, axis string, format int) {
if f.GetCellStyle(sheet, axis) == 0 {
style, _ := f.NewStyle(`{"number_format": ` + strconv.Itoa(format) + `}`)
f.SetCellStyle(sheet, axis, axis, style)
}
}
// workSheetReader provides a function to get the pointer to the structure
// after deserialization by given worksheet name.
func (f *File) workSheetReader(sheet string) *xlsxWorksheet {
name, ok := f.sheetMap[trimSheetName(sheet)]
if !ok {
name = "xl/worksheets/" + strings.ToLower(sheet) + ".xml"
}
if f.Sheet[name] == nil {
var xlsx xlsxWorksheet
_ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(name)), &xlsx)
if f.checked == nil {
f.checked = make(map[string]bool)
}
ok := f.checked[name]
if !ok {
checkSheet(&xlsx)
checkRow(&xlsx)
f.checked[name] = true
}
f.Sheet[name] = &xlsx
}
return f.Sheet[name]
}
// checkSheet provides a function to fill each row element and make that is
// continuous in a worksheet of XML.
func checkSheet(xlsx *xlsxWorksheet) {
row := len(xlsx.SheetData.Row)
if row >= 1 {
lastRow := xlsx.SheetData.Row[row-1].R
if lastRow >= row {
row = lastRow
}
}
sheetData := xlsxSheetData{}
existsRows := map[int]int{}
for k := range xlsx.SheetData.Row {
existsRows[xlsx.SheetData.Row[k].R] = k
}
for i := 0; i < row; i++ {
_, ok := existsRows[i+1]
if ok {
sheetData.Row = append(sheetData.Row, xlsx.SheetData.Row[existsRows[i+1]])
} else {
sheetData.Row = append(sheetData.Row, xlsxRow{
R: i + 1,
})
}
}
xlsx.SheetData = sheetData
}
// replaceWorkSheetsRelationshipsNameSpaceBytes provides a function to replace
// xl/worksheets/sheet%d.xml XML tags to self-closing for compatible Microsoft
// Office Excel 2007.
func replaceWorkSheetsRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
var oldXmlns = []byte(`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
var newXmlns = []byte(`<worksheet xr:uid="{00000000-0001-0000-0000-000000000000}" xmlns:xr3="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3" xmlns:xr2="http://schemas.microsoft.com/office/spreadsheetml/2015/revision2" xmlns:xr="http://schemas.microsoft.com/office/spreadsheetml/2014/revision" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" mc:Ignorable="x14ac xr xr2 xr3" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mx="http://schemas.microsoft.com/office/mac/excel/2008/main" xmlns:mv="urn:schemas-microsoft-com:mac:vml" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
workbookMarshal = bytes.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
return workbookMarshal
}
// UpdateLinkedValue fix linked values within a spreadsheet are not updating in
// Office Excel 2007 and 2010. This function will be remove value tag when met a
// cell have a linked value. Reference
// https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating?forum=excel
//
// Notice: after open XLSX file Excel will be update linked value and generate
// new value and will prompt save file or not.
//
// For example:
//
// <row r="19" spans="2:2">
// <c r="B19">
// <f>SUM(Sheet2!D2,Sheet2!D11)</f>
// <v>100</v>
// </c>
// </row>
//
// to
//
// <row r="19" spans="2:2">
// <c r="B19">
// <f>SUM(Sheet2!D2,Sheet2!D11)</f>
// </c>
// </row>
//
func (f *File) UpdateLinkedValue() {
for _, name := range f.GetSheetMap() {
xlsx := f.workSheetReader(name)
for indexR := range xlsx.SheetData.Row {
for indexC, col := range xlsx.SheetData.Row[indexR].C {
if col.F != nil && col.V != "" {
xlsx.SheetData.Row[indexR].C[indexC].V = ""
xlsx.SheetData.Row[indexR].C[indexC].T = ""
}
}
}
}
}
// adjustHelper provides a function to adjust rows and columns dimensions,
// hyperlinks, merged cells and auto filter when inserting or deleting rows or
// columns.
//
// sheet: Worksheet name that we're editing
// column: Index number of the column we're inserting/deleting before
// row: Index number of the row we're inserting/deleting before
// offset: Number of rows/column to insert/delete negative values indicate deletion
//
// TODO: adjustPageBreaks, adjustComments, adjustDataValidations, adjustProtectedCells
//
func (f *File) adjustHelper(sheet string, column, row, offset int) {
xlsx := f.workSheetReader(sheet)
f.adjustRowDimensions(xlsx, row, offset)
f.adjustColDimensions(xlsx, column, offset)
f.adjustHyperlinks(sheet, column, row, offset)
f.adjustMergeCells(xlsx, column, row, offset)
f.adjustAutoFilter(xlsx, column, row, offset)
checkSheet(xlsx)
checkRow(xlsx)
}
// adjustColDimensions provides a function to update column dimensions when
// inserting or deleting rows or columns.
func (f *File) adjustColDimensions(xlsx *xlsxWorksheet, column, offset int) {
for i, r := range xlsx.SheetData.Row {
for k, v := range r.C {
axis := v.R
col := string(strings.Map(letterOnlyMapF, axis))
row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
yAxis := TitleToNumber(col)
if yAxis >= column && column != -1 {
xlsx.SheetData.Row[i].C[k].R = ToAlphaString(yAxis+offset) + strconv.Itoa(row)
}
}
}
}
// adjustRowDimensions provides a function to update row dimensions when
// inserting or deleting rows or columns.
func (f *File) adjustRowDimensions(xlsx *xlsxWorksheet, rowIndex, offset int) {
if rowIndex == -1 {
return
}
for i, r := range xlsx.SheetData.Row {
if r.R >= rowIndex {
f.ajustSingleRowDimensions(&xlsx.SheetData.Row[i], offset)
}
}
}
// ajustSingleRowDimensions provides a function to ajust single row
// dimensions.
func (f *File) ajustSingleRowDimensions(r *xlsxRow, offset int) {
r.R += offset
for i, col := range r.C {
row, _ := strconv.Atoi(strings.Map(intOnlyMapF, col.R))
r.C[i].R = string(strings.Map(letterOnlyMapF, col.R)) + strconv.Itoa(row+offset)
}
}
// adjustHyperlinks provides a function to update hyperlinks when inserting or
// deleting rows or columns.
func (f *File) adjustHyperlinks(sheet string, column, rowIndex, offset int) {
xlsx := f.workSheetReader(sheet)
// order is important
if xlsx.Hyperlinks != nil && offset < 0 {
for i, v := range xlsx.Hyperlinks.Hyperlink {
axis := v.Ref
col := string(strings.Map(letterOnlyMapF, axis))
row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
yAxis := TitleToNumber(col)
if row == rowIndex || yAxis == column {
f.deleteSheetRelationships(sheet, v.RID)
if len(xlsx.Hyperlinks.Hyperlink) > 1 {
xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink[:i], xlsx.Hyperlinks.Hyperlink[i+1:]...)
} else {
xlsx.Hyperlinks = nil
}
}
}
}
if xlsx.Hyperlinks != nil {
for i, v := range xlsx.Hyperlinks.Hyperlink {
axis := v.Ref
col := string(strings.Map(letterOnlyMapF, axis))
row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
xAxis := row + offset
yAxis := TitleToNumber(col)
if rowIndex != -1 && row >= rowIndex {
xlsx.Hyperlinks.Hyperlink[i].Ref = col + strconv.Itoa(xAxis)
}
if column != -1 && yAxis >= column {
xlsx.Hyperlinks.Hyperlink[i].Ref = ToAlphaString(yAxis+offset) + strconv.Itoa(row)
}
}
}
}
// adjustMergeCellsHelper provides a function to update merged cells when
// inserting or deleting rows or columns.
func (f *File) adjustMergeCellsHelper(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
if xlsx.MergeCells != nil {
for k, v := range xlsx.MergeCells.Cells {
beg := strings.Split(v.Ref, ":")[0]
end := strings.Split(v.Ref, ":")[1]
begcol := string(strings.Map(letterOnlyMapF, beg))
begrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, beg))
begxAxis := begrow + offset
begyAxis := TitleToNumber(begcol)
endcol := string(strings.Map(letterOnlyMapF, end))
endrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, end))
endxAxis := endrow + offset
endyAxis := TitleToNumber(endcol)
if rowIndex != -1 {
if begrow > 1 && begrow >= rowIndex {
beg = begcol + strconv.Itoa(begxAxis)
}
if endrow > 1 && endrow >= rowIndex {
end = endcol + strconv.Itoa(endxAxis)
}
}
if column != -1 {
if begyAxis >= column {
beg = ToAlphaString(begyAxis+offset) + strconv.Itoa(endrow)
}
if endyAxis >= column {
end = ToAlphaString(endyAxis+offset) + strconv.Itoa(endrow)
}
}
xlsx.MergeCells.Cells[k].Ref = beg + ":" + end
}
}
}
// adjustMergeCells provides a function to update merged cells when inserting
// or deleting rows or columns.
func (f *File) adjustMergeCells(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
f.adjustMergeCellsHelper(xlsx, column, rowIndex, offset)
if xlsx.MergeCells != nil && offset < 0 {
for k, v := range xlsx.MergeCells.Cells {
beg := strings.Split(v.Ref, ":")[0]
end := strings.Split(v.Ref, ":")[1]
if beg == end {
xlsx.MergeCells.Count += offset
if len(xlsx.MergeCells.Cells) > 1 {
xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:k], xlsx.MergeCells.Cells[k+1:]...)
} else {
xlsx.MergeCells = nil
}
}
}
}
}
// adjustAutoFilter provides a function to update the auto filter when
// inserting or deleting rows or columns.
func (f *File) adjustAutoFilter(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
f.adjustAutoFilterHelper(xlsx, column, rowIndex, offset)
if xlsx.AutoFilter != nil {
beg := strings.Split(xlsx.AutoFilter.Ref, ":")[0]
end := strings.Split(xlsx.AutoFilter.Ref, ":")[1]
begcol := string(strings.Map(letterOnlyMapF, beg))
begrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, beg))
begxAxis := begrow + offset
endcol := string(strings.Map(letterOnlyMapF, end))
endrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, end))
endxAxis := endrow + offset
endyAxis := TitleToNumber(endcol)
if rowIndex != -1 {
if begrow >= rowIndex {
beg = begcol + strconv.Itoa(begxAxis)
}
if endrow >= rowIndex {
end = endcol + strconv.Itoa(endxAxis)
}
}
if column != -1 && endyAxis >= column {
end = ToAlphaString(endyAxis+offset) + strconv.Itoa(endrow)
}
xlsx.AutoFilter.Ref = beg + ":" + end
}
}
// adjustAutoFilterHelper provides a function to update the auto filter when
// inserting or deleting rows or columns.
func (f *File) adjustAutoFilterHelper(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
if xlsx.AutoFilter != nil {
beg := strings.Split(xlsx.AutoFilter.Ref, ":")[0]
end := strings.Split(xlsx.AutoFilter.Ref, ":")[1]
begcol := string(strings.Map(letterOnlyMapF, beg))
begrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, beg))
begyAxis := TitleToNumber(begcol)
endcol := string(strings.Map(letterOnlyMapF, end))
endyAxis := TitleToNumber(endcol)
endrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, end))
if (begrow == rowIndex && offset < 0) || (column == begyAxis && column == endyAxis) {
xlsx.AutoFilter = nil
for i, r := range xlsx.SheetData.Row {
if begrow < r.R && r.R <= endrow {
xlsx.SheetData.Row[i].Hidden = false
}
}
}
}
}
// GetMergeCells provides a function to get all merged cells from a worksheet currently.
func (f *File) GetMergeCells(sheet string) []MergeCell {
mergeCells := []MergeCell{}
xlsx := f.workSheetReader(sheet)
if xlsx.MergeCells != nil {
for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
ref := xlsx.MergeCells.Cells[i].Ref
axis := strings.Split(ref, ":")[0]
mergeCells = append(mergeCells, []string{ref, f.GetCellValue(sheet, axis)})
}
}
return mergeCells
}
// MergeCell define a merged cell data.
// It consists of the following structure.
// example: []string{"D4:E10", "cell value"}
type MergeCell []string
// GetCellValue returns merged cell value.
func (m *MergeCell) GetCellValue() string {
return (*m)[1]
}
// GetStartAxis returns the merge start axis.
// example: "C2"
func (m *MergeCell) GetStartAxis() string {
axis := strings.Split((*m)[0], ":")
return axis[0]
}
// GetEndAxis returns the merge end axis.
// example: "D4"
func (m *MergeCell) GetEndAxis() string {
axis := strings.Split((*m)[0], ":")
return axis[1]
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

View File

@ -1,106 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"archive/zip"
"bytes"
"fmt"
"io"
"os"
)
// NewFile provides a function to create new file by default template. For
// example:
//
// xlsx := NewFile()
//
func NewFile() *File {
file := make(map[string][]byte)
file["_rels/.rels"] = []byte(XMLHeader + templateRels)
file["docProps/app.xml"] = []byte(XMLHeader + templateDocpropsApp)
file["docProps/core.xml"] = []byte(XMLHeader + templateDocpropsCore)
file["xl/_rels/workbook.xml.rels"] = []byte(XMLHeader + templateWorkbookRels)
file["xl/theme/theme1.xml"] = []byte(XMLHeader + templateTheme)
file["xl/worksheets/sheet1.xml"] = []byte(XMLHeader + templateSheet)
file["xl/styles.xml"] = []byte(XMLHeader + templateStyles)
file["xl/workbook.xml"] = []byte(XMLHeader + templateWorkbook)
file["[Content_Types].xml"] = []byte(XMLHeader + templateContentTypes)
f := &File{
sheetMap: make(map[string]string),
Sheet: make(map[string]*xlsxWorksheet),
SheetCount: 1,
XLSX: file,
}
f.ContentTypes = f.contentTypesReader()
f.Styles = f.stylesReader()
f.WorkBook = f.workbookReader()
f.WorkBookRels = f.workbookRelsReader()
f.Sheet["xl/worksheets/sheet1.xml"] = f.workSheetReader("Sheet1")
f.sheetMap["Sheet1"] = "xl/worksheets/sheet1.xml"
f.Theme = f.themeReader()
return f
}
// Save provides a function to override the xlsx file with origin path.
func (f *File) Save() error {
if f.Path == "" {
return fmt.Errorf("no path defined for file, consider File.WriteTo or File.Write")
}
return f.SaveAs(f.Path)
}
// SaveAs provides a function to create or update to an xlsx file at the
// provided path.
func (f *File) SaveAs(name string) error {
file, err := os.OpenFile(name, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
if err != nil {
return err
}
defer file.Close()
return f.Write(file)
}
// Write provides a function to write to an io.Writer.
func (f *File) Write(w io.Writer) error {
_, err := f.WriteTo(w)
return err
}
// WriteTo implements io.WriterTo to write the file.
func (f *File) WriteTo(w io.Writer) (int64, error) {
buf, err := f.WriteToBuffer()
if err != nil {
return 0, err
}
return buf.WriteTo(w)
}
// WriteToBuffer provides a function to get bytes.Buffer from the saved file.
func (f *File) WriteToBuffer() (*bytes.Buffer, error) {
buf := new(bytes.Buffer)
zw := zip.NewWriter(buf)
f.contentTypesWriter()
f.workbookWriter()
f.workbookRelsWriter()
f.worksheetWriter()
f.styleSheetWriter()
for path, content := range f.XLSX {
fi, err := zw.Create(path)
if err != nil {
return buf, err
}
_, err = fi.Write(content)
if err != nil {
return buf, err
}
}
return buf, zw.Close()
}

View File

@ -1,8 +0,0 @@
module github.com/360EntSecGroup-Skylar/excelize
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.2.3-0.20181224173747-660f15d67dbb
)

View File

@ -1,8 +0,0 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.2.3-0.20181224173747-660f15d67dbb h1:cRItZejS4Ok67vfCdrbGIaqk86wmtQNOjVD7jSyS2aw=
github.com/stretchr/testify v1.2.3-0.20181224173747-660f15d67dbb/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=

View File

@ -1,139 +0,0 @@
// Copyright (c) 2012 Rodrigo Moraes. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package excelize
import (
"image/color"
"math"
)
// HSLModel converts any color.Color to a HSL color.
var HSLModel = color.ModelFunc(hslModel)
// HSL represents a cylindrical coordinate of points in an RGB color model.
//
// Values are in the range 0 to 1.
type HSL struct {
H, S, L float64
}
// RGBA returns the alpha-premultiplied red, green, blue and alpha values
// for the HSL.
func (c HSL) RGBA() (uint32, uint32, uint32, uint32) {
r, g, b := HSLToRGB(c.H, c.S, c.L)
return uint32(r) * 0x101, uint32(g) * 0x101, uint32(b) * 0x101, 0xffff
}
// hslModel converts a color.Color to HSL.
func hslModel(c color.Color) color.Color {
if _, ok := c.(HSL); ok {
return c
}
r, g, b, _ := c.RGBA()
h, s, l := RGBToHSL(uint8(r>>8), uint8(g>>8), uint8(b>>8))
return HSL{h, s, l}
}
// RGBToHSL converts an RGB triple to a HSL triple.
func RGBToHSL(r, g, b uint8) (h, s, l float64) {
fR := float64(r) / 255
fG := float64(g) / 255
fB := float64(b) / 255
max := math.Max(math.Max(fR, fG), fB)
min := math.Min(math.Min(fR, fG), fB)
l = (max + min) / 2
if max == min {
// Achromatic.
h, s = 0, 0
} else {
// Chromatic.
d := max - min
if l > 0.5 {
s = d / (2.0 - max - min)
} else {
s = d / (max + min)
}
switch max {
case fR:
h = (fG - fB) / d
if fG < fB {
h += 6
}
case fG:
h = (fB-fR)/d + 2
case fB:
h = (fR-fG)/d + 4
}
h /= 6
}
return
}
// HSLToRGB converts an HSL triple to a RGB triple.
func HSLToRGB(h, s, l float64) (r, g, b uint8) {
var fR, fG, fB float64
if s == 0 {
fR, fG, fB = l, l, l
} else {
var q float64
if l < 0.5 {
q = l * (1 + s)
} else {
q = l + s - s*l
}
p := 2*l - q
fR = hueToRGB(p, q, h+1.0/3)
fG = hueToRGB(p, q, h)
fB = hueToRGB(p, q, h-1.0/3)
}
r = uint8((fR * 255) + 0.5)
g = uint8((fG * 255) + 0.5)
b = uint8((fB * 255) + 0.5)
return
}
// hueToRGB is a helper function for HSLToRGB.
func hueToRGB(p, q, t float64) float64 {
if t < 0 {
t++
}
if t > 1 {
t--
}
if t < 1.0/6 {
return p + (q-p)*6*t
}
if t < 0.5 {
return q
}
if t < 2.0/3 {
return p + (q-p)*(2.0/3-t)*6
}
return p
}

View File

@ -1,229 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"archive/zip"
"bytes"
"io"
"log"
"math"
"strconv"
"strings"
"unicode"
)
// ReadZipReader can be used to read an XLSX in memory without touching the
// filesystem.
func ReadZipReader(r *zip.Reader) (map[string][]byte, int, error) {
fileList := make(map[string][]byte)
worksheets := 0
for _, v := range r.File {
fileList[v.Name] = readFile(v)
if len(v.Name) > 18 {
if v.Name[0:19] == "xl/worksheets/sheet" {
worksheets++
}
}
}
return fileList, worksheets, nil
}
// readXML provides a function to read XML content as string.
func (f *File) readXML(name string) []byte {
if content, ok := f.XLSX[name]; ok {
return content
}
return []byte{}
}
// saveFileList provides a function to update given file content in file list
// of XLSX.
func (f *File) saveFileList(name string, content []byte) {
newContent := make([]byte, 0, len(XMLHeader)+len(content))
newContent = append(newContent, []byte(XMLHeader)...)
newContent = append(newContent, content...)
f.XLSX[name] = newContent
}
// Read file content as string in a archive file.
func readFile(file *zip.File) []byte {
rc, err := file.Open()
if err != nil {
log.Fatal(err)
}
buff := bytes.NewBuffer(nil)
_, _ = io.Copy(buff, rc)
rc.Close()
return buff.Bytes()
}
// ToAlphaString provides a function to convert integer to Excel sheet column
// title. For example convert 36 to column title AK:
//
// excelize.ToAlphaString(36)
//
func ToAlphaString(value int) string {
if value < 0 {
return ""
}
var ans string
i := value + 1
for i > 0 {
ans = string((i-1)%26+65) + ans
i = (i - 1) / 26
}
return ans
}
// TitleToNumber provides a function to convert Excel sheet column title to
// int (this function doesn't do value check currently). For example convert
// AK and ak to column title 36:
//
// excelize.TitleToNumber("AK")
// excelize.TitleToNumber("ak")
//
func TitleToNumber(s string) int {
weight := 0.0
sum := 0
for i := len(s) - 1; i >= 0; i-- {
ch := int(s[i])
if int(s[i]) >= int('a') && int(s[i]) <= int('z') {
ch = int(s[i]) - 32
}
sum = sum + (ch-int('A')+1)*int(math.Pow(26, weight))
weight++
}
return sum - 1
}
// letterOnlyMapF is used in conjunction with strings.Map to return only the
// characters A-Z and a-z in a string.
func letterOnlyMapF(rune rune) rune {
switch {
case 'A' <= rune && rune <= 'Z':
return rune
case 'a' <= rune && rune <= 'z':
return rune - 32
}
return -1
}
// intOnlyMapF is used in conjunction with strings.Map to return only the
// numeric portions of a string.
func intOnlyMapF(rune rune) rune {
if rune >= 48 && rune < 58 {
return rune
}
return -1
}
// boolPtr returns a pointer to a bool with the given value.
func boolPtr(b bool) *bool { return &b }
// defaultTrue returns true if b is nil, or the pointed value.
func defaultTrue(b *bool) bool {
if b == nil {
return true
}
return *b
}
// axisLowerOrEqualThan returns true if axis1 <= axis2 axis1/axis2 can be
// either a column or a row axis, e.g. "A", "AAE", "42", "1", etc.
//
// For instance, the following comparisons are all true:
//
// "A" <= "B"
// "A" <= "AA"
// "B" <= "AA"
// "BC" <= "ABCD" (in a XLSX sheet, the BC col comes before the ABCD col)
// "1" <= "2"
// "2" <= "11" (in a XLSX sheet, the row 2 comes before the row 11)
// and so on
func axisLowerOrEqualThan(axis1, axis2 string) bool {
if len(axis1) < len(axis2) {
return true
} else if len(axis1) > len(axis2) {
return false
} else {
return axis1 <= axis2
}
}
// getCellColRow returns the two parts of a cell identifier (its col and row)
// as strings
//
// For instance:
//
// "C220" => "C", "220"
// "aaef42" => "aaef", "42"
// "" => "", ""
func getCellColRow(cell string) (col, row string) {
for index, rune := range cell {
if unicode.IsDigit(rune) {
return cell[:index], cell[index:]
}
}
return cell, ""
}
// parseFormatSet provides a method to convert format string to []byte and
// handle empty string.
func parseFormatSet(formatSet string) []byte {
if formatSet != "" {
return []byte(formatSet)
}
return []byte("{}")
}
// namespaceStrictToTransitional provides a method to convert Strict and
// Transitional namespaces.
func namespaceStrictToTransitional(content []byte) []byte {
var namespaceTranslationDic = map[string]string{
StrictSourceRelationship: SourceRelationship,
StrictSourceRelationshipChart: SourceRelationshipChart,
StrictSourceRelationshipComments: SourceRelationshipComments,
StrictSourceRelationshipImage: SourceRelationshipImage,
StrictNameSpaceSpreadSheet: NameSpaceSpreadSheet,
}
for s, n := range namespaceTranslationDic {
content = bytes.Replace(content, []byte(s), []byte(n), -1)
}
return content
}
// genSheetPasswd provides a method to generate password for worksheet
// protection by given plaintext. When an Excel sheet is being protected with
// a password, a 16-bit (two byte) long hash is generated. To verify a
// password, it is compared to the hash. Obviously, if the input data volume
// is great, numerous passwords will match the same hash. Here is the
// algorithm to create the hash value:
//
// take the ASCII values of all characters shift left the first character 1 bit, the second 2 bits and so on (use only the lower 15 bits and rotate all higher bits, the highest bit of the 16-bit value is always 0 [signed short])
// XOR all these values
// XOR the count of characters
// XOR the constant 0xCE4B
func genSheetPasswd(plaintext string) string {
var password int64 = 0x0000
var charPos uint = 1
for _, v := range plaintext {
value := int64(v) << charPos
charPos++
rotatedBits := value >> 15 // rotated bits beyond bit 15
value &= 0x7fff // first 15 bits
password ^= (value | rotatedBits)
}
password ^= int64(len(plaintext))
password ^= 0xCE4B
return strings.ToUpper(strconv.FormatInt(password, 16))
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

View File

@ -1,533 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"image"
"io/ioutil"
"os"
"path"
"path/filepath"
"strconv"
"strings"
)
// parseFormatPictureSet provides a function to parse the format settings of
// the picture with default value.
func parseFormatPictureSet(formatSet string) (*formatPicture, error) {
format := formatPicture{
FPrintsWithSheet: true,
FLocksWithSheet: false,
NoChangeAspect: false,
OffsetX: 0,
OffsetY: 0,
XScale: 1.0,
YScale: 1.0,
}
err := json.Unmarshal(parseFormatSet(formatSet), &format)
return &format, err
}
// AddPicture provides the method to add picture in a sheet by given picture
// format set (such as offset, scale, aspect ratio setting and print settings)
// and file path. For example:
//
// package main
//
// import (
// "fmt"
// _ "image/gif"
// _ "image/jpeg"
// _ "image/png"
//
// "github.com/360EntSecGroup-Skylar/excelize"
// )
//
// func main() {
// xlsx := excelize.NewFile()
// // Insert a picture.
// err := xlsx.AddPicture("Sheet1", "A2", "./image1.jpg", "")
// if err != nil {
// fmt.Println(err)
// }
// // Insert a picture scaling in the cell with location hyperlink.
// err = xlsx.AddPicture("Sheet1", "D2", "./image1.png", `{"x_scale": 0.5, "y_scale": 0.5, "hyperlink": "#Sheet2!D8", "hyperlink_type": "Location"}`)
// if err != nil {
// fmt.Println(err)
// }
// // Insert a picture offset in the cell with external hyperlink, printing and positioning support.
// err = xlsx.AddPicture("Sheet1", "H2", "./image3.gif", `{"x_offset": 15, "y_offset": 10, "hyperlink": "https://github.com/360EntSecGroup-Skylar/excelize", "hyperlink_type": "External", "print_obj": true, "lock_aspect_ratio": false, "locked": false, "positioning": "oneCell"}`)
// if err != nil {
// fmt.Println(err)
// }
// err = xlsx.SaveAs("./Book1.xlsx")
// if err != nil {
// fmt.Println(err)
// }
// }
//
// LinkType defines two types of hyperlink "External" for web site or
// "Location" for moving to one of cell in this workbook. When the
// "hyperlink_type" is "Location", coordinates need to start with "#".
//
// Positioning defines two types of the position of a picture in an Excel
// spreadsheet, "oneCell" (Move but don't size with cells) or "absolute"
// (Don't move or size with cells). If you don't set this parameter, default
// positioning is move and size with cells.
func (f *File) AddPicture(sheet, cell, picture, format string) error {
var err error
// Check picture exists first.
if _, err = os.Stat(picture); os.IsNotExist(err) {
return err
}
ext, ok := supportImageTypes[path.Ext(picture)]
if !ok {
return errors.New("unsupported image extension")
}
file, _ := ioutil.ReadFile(picture)
_, name := filepath.Split(picture)
return f.AddPictureFromBytes(sheet, cell, format, name, ext, file)
}
// AddPictureFromBytes provides the method to add picture in a sheet by given
// picture format set (such as offset, scale, aspect ratio setting and print
// settings), file base name, extension name and file bytes. For example:
//
// package main
//
// import (
// "fmt"
// _ "image/jpeg"
// "io/ioutil"
//
// "github.com/360EntSecGroup-Skylar/excelize"
// )
//
// func main() {
// xlsx := excelize.NewFile()
//
// file, err := ioutil.ReadFile("./image1.jpg")
// if err != nil {
// fmt.Println(err)
// }
// err = xlsx.AddPictureFromBytes("Sheet1", "A2", "", "Excel Logo", ".jpg", file)
// if err != nil {
// fmt.Println(err)
// }
// err = xlsx.SaveAs("./Book1.xlsx")
// if err != nil {
// fmt.Println(err)
// }
// }
//
func (f *File) AddPictureFromBytes(sheet, cell, format, name, extension string, file []byte) error {
var err error
var drawingHyperlinkRID int
var hyperlinkType string
ext, ok := supportImageTypes[extension]
if !ok {
return errors.New("unsupported image extension")
}
formatSet, err := parseFormatPictureSet(format)
if err != nil {
return err
}
image, _, err := image.DecodeConfig(bytes.NewReader(file))
if err != nil {
return err
}
// Read sheet data.
xlsx := f.workSheetReader(sheet)
// Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
drawingID := f.countDrawings() + 1
pictureID := f.countMedia() + 1
drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
drawingID, drawingXML = f.prepareDrawing(xlsx, drawingID, sheet, drawingXML)
drawingRID := f.addDrawingRelationships(drawingID, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, hyperlinkType)
// Add picture with hyperlink.
if formatSet.Hyperlink != "" && formatSet.HyperlinkType != "" {
if formatSet.HyperlinkType == "External" {
hyperlinkType = formatSet.HyperlinkType
}
drawingHyperlinkRID = f.addDrawingRelationships(drawingID, SourceRelationshipHyperLink, formatSet.Hyperlink, hyperlinkType)
}
f.addDrawingPicture(sheet, drawingXML, cell, name, image.Width, image.Height, drawingRID, drawingHyperlinkRID, formatSet)
f.addMedia(file, ext)
f.addContentTypePart(drawingID, "drawings")
return err
}
// addSheetRelationships provides a function to add
// xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name, relationship
// type and target.
func (f *File) addSheetRelationships(sheet, relType, target, targetMode string) int {
name, ok := f.sheetMap[trimSheetName(sheet)]
if !ok {
name = strings.ToLower(sheet) + ".xml"
}
var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
var sheetRels xlsxWorkbookRels
var rID = 1
var ID bytes.Buffer
ID.WriteString("rId")
ID.WriteString(strconv.Itoa(rID))
_, ok = f.XLSX[rels]
if ok {
ID.Reset()
_ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(rels)), &sheetRels)
rID = len(sheetRels.Relationships) + 1
ID.WriteString("rId")
ID.WriteString(strconv.Itoa(rID))
}
sheetRels.Relationships = append(sheetRels.Relationships, xlsxWorkbookRelation{
ID: ID.String(),
Type: relType,
Target: target,
TargetMode: targetMode,
})
output, _ := xml.Marshal(sheetRels)
f.saveFileList(rels, output)
return rID
}
// deleteSheetRelationships provides a function to delete relationships in
// xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
// relationship index.
func (f *File) deleteSheetRelationships(sheet, rID string) {
name, ok := f.sheetMap[trimSheetName(sheet)]
if !ok {
name = strings.ToLower(sheet) + ".xml"
}
var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
var sheetRels xlsxWorkbookRels
_ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(rels)), &sheetRels)
for k, v := range sheetRels.Relationships {
if v.ID == rID {
sheetRels.Relationships = append(sheetRels.Relationships[:k], sheetRels.Relationships[k+1:]...)
}
}
output, _ := xml.Marshal(sheetRels)
f.saveFileList(rels, output)
}
// addSheetLegacyDrawing provides a function to add legacy drawing element to
// xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
func (f *File) addSheetLegacyDrawing(sheet string, rID int) {
xlsx := f.workSheetReader(sheet)
xlsx.LegacyDrawing = &xlsxLegacyDrawing{
RID: "rId" + strconv.Itoa(rID),
}
}
// addSheetDrawing provides a function to add drawing element to
// xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
func (f *File) addSheetDrawing(sheet string, rID int) {
xlsx := f.workSheetReader(sheet)
xlsx.Drawing = &xlsxDrawing{
RID: "rId" + strconv.Itoa(rID),
}
}
// addSheetPicture provides a function to add picture element to
// xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
func (f *File) addSheetPicture(sheet string, rID int) {
xlsx := f.workSheetReader(sheet)
xlsx.Picture = &xlsxPicture{
RID: "rId" + strconv.Itoa(rID),
}
}
// countDrawings provides a function to get drawing files count storage in the
// folder xl/drawings.
func (f *File) countDrawings() int {
count := 0
for k := range f.XLSX {
if strings.Contains(k, "xl/drawings/drawing") {
count++
}
}
return count
}
// addDrawingPicture provides a function to add picture by given sheet,
// drawingXML, cell, file name, width, height relationship index and format
// sets.
func (f *File) addDrawingPicture(sheet, drawingXML, cell, file string, width, height, rID, hyperlinkRID int, formatSet *formatPicture) {
cell = strings.ToUpper(cell)
fromCol := string(strings.Map(letterOnlyMapF, cell))
fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
row := fromRow - 1
col := TitleToNumber(fromCol)
width = int(float64(width) * formatSet.XScale)
height = int(float64(height) * formatSet.YScale)
colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 := f.positionObjectPixels(sheet, col, row, formatSet.OffsetX, formatSet.OffsetY, width, height)
content := xlsxWsDr{}
content.A = NameSpaceDrawingML
content.Xdr = NameSpaceDrawingMLSpreadSheet
cNvPrID := f.drawingParser(drawingXML, &content)
twoCellAnchor := xdrCellAnchor{}
twoCellAnchor.EditAs = formatSet.Positioning
from := xlsxFrom{}
from.Col = colStart
from.ColOff = formatSet.OffsetX * EMU
from.Row = rowStart
from.RowOff = formatSet.OffsetY * EMU
to := xlsxTo{}
to.Col = colEnd
to.ColOff = x2 * EMU
to.Row = rowEnd
to.RowOff = y2 * EMU
twoCellAnchor.From = &from
twoCellAnchor.To = &to
pic := xlsxPic{}
pic.NvPicPr.CNvPicPr.PicLocks.NoChangeAspect = formatSet.NoChangeAspect
pic.NvPicPr.CNvPr.ID = f.countCharts() + f.countMedia() + 1
pic.NvPicPr.CNvPr.Descr = file
pic.NvPicPr.CNvPr.Name = "Picture " + strconv.Itoa(cNvPrID)
if hyperlinkRID != 0 {
pic.NvPicPr.CNvPr.HlinkClick = &xlsxHlinkClick{
R: SourceRelationship,
RID: "rId" + strconv.Itoa(hyperlinkRID),
}
}
pic.BlipFill.Blip.R = SourceRelationship
pic.BlipFill.Blip.Embed = "rId" + strconv.Itoa(rID)
pic.SpPr.PrstGeom.Prst = "rect"
twoCellAnchor.Pic = &pic
twoCellAnchor.ClientData = &xdrClientData{
FLocksWithSheet: formatSet.FLocksWithSheet,
FPrintsWithSheet: formatSet.FPrintsWithSheet,
}
content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
output, _ := xml.Marshal(content)
f.saveFileList(drawingXML, output)
}
// addDrawingRelationships provides a function to add image part relationships
// in the file xl/drawings/_rels/drawing%d.xml.rels by given drawing index,
// relationship type and target.
func (f *File) addDrawingRelationships(index int, relType, target, targetMode string) int {
var rels = "xl/drawings/_rels/drawing" + strconv.Itoa(index) + ".xml.rels"
var drawingRels xlsxWorkbookRels
var rID = 1
var ID bytes.Buffer
ID.WriteString("rId")
ID.WriteString(strconv.Itoa(rID))
_, ok := f.XLSX[rels]
if ok {
ID.Reset()
_ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(rels)), &drawingRels)
rID = len(drawingRels.Relationships) + 1
ID.WriteString("rId")
ID.WriteString(strconv.Itoa(rID))
}
drawingRels.Relationships = append(drawingRels.Relationships, xlsxWorkbookRelation{
ID: ID.String(),
Type: relType,
Target: target,
TargetMode: targetMode,
})
output, _ := xml.Marshal(drawingRels)
f.saveFileList(rels, output)
return rID
}
// countMedia provides a function to get media files count storage in the
// folder xl/media/image.
func (f *File) countMedia() int {
count := 0
for k := range f.XLSX {
if strings.Contains(k, "xl/media/image") {
count++
}
}
return count
}
// addMedia provides a function to add picture into folder xl/media/image by
// given file and extension name.
func (f *File) addMedia(file []byte, ext string) {
count := f.countMedia()
media := "xl/media/image" + strconv.Itoa(count+1) + ext
f.XLSX[media] = file
}
// setContentTypePartImageExtensions provides a function to set the content
// type for relationship parts and the Main Document part.
func (f *File) setContentTypePartImageExtensions() {
var imageTypes = map[string]bool{"jpeg": false, "png": false, "gif": false}
content := f.contentTypesReader()
for _, v := range content.Defaults {
_, ok := imageTypes[v.Extension]
if ok {
imageTypes[v.Extension] = true
}
}
for k, v := range imageTypes {
if !v {
content.Defaults = append(content.Defaults, xlsxDefault{
Extension: k,
ContentType: "image/" + k,
})
}
}
}
// setContentTypePartVMLExtensions provides a function to set the content type
// for relationship parts and the Main Document part.
func (f *File) setContentTypePartVMLExtensions() {
vml := false
content := f.contentTypesReader()
for _, v := range content.Defaults {
if v.Extension == "vml" {
vml = true
}
}
if !vml {
content.Defaults = append(content.Defaults, xlsxDefault{
Extension: "vml",
ContentType: "application/vnd.openxmlformats-officedocument.vmlDrawing",
})
}
}
// addContentTypePart provides a function to add content type part
// relationships in the file [Content_Types].xml by given index.
func (f *File) addContentTypePart(index int, contentType string) {
setContentType := map[string]func(){
"comments": f.setContentTypePartVMLExtensions,
"drawings": f.setContentTypePartImageExtensions,
}
partNames := map[string]string{
"chart": "/xl/charts/chart" + strconv.Itoa(index) + ".xml",
"comments": "/xl/comments" + strconv.Itoa(index) + ".xml",
"drawings": "/xl/drawings/drawing" + strconv.Itoa(index) + ".xml",
"table": "/xl/tables/table" + strconv.Itoa(index) + ".xml",
}
contentTypes := map[string]string{
"chart": "application/vnd.openxmlformats-officedocument.drawingml.chart+xml",
"comments": "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
"drawings": "application/vnd.openxmlformats-officedocument.drawing+xml",
"table": "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",
}
s, ok := setContentType[contentType]
if ok {
s()
}
content := f.contentTypesReader()
for _, v := range content.Overrides {
if v.PartName == partNames[contentType] {
return
}
}
content.Overrides = append(content.Overrides, xlsxOverride{
PartName: partNames[contentType],
ContentType: contentTypes[contentType],
})
}
// getSheetRelationshipsTargetByID provides a function to get Target attribute
// value in xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
// relationship index.
func (f *File) getSheetRelationshipsTargetByID(sheet, rID string) string {
name, ok := f.sheetMap[trimSheetName(sheet)]
if !ok {
name = strings.ToLower(sheet) + ".xml"
}
var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
var sheetRels xlsxWorkbookRels
_ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(rels)), &sheetRels)
for _, v := range sheetRels.Relationships {
if v.ID == rID {
return v.Target
}
}
return ""
}
// GetPicture provides a function to get picture base name and raw content
// embed in XLSX by given worksheet and cell name. This function returns the
// file name in XLSX and file contents as []byte data types. For example:
//
// xlsx, err := excelize.OpenFile("./Book1.xlsx")
// if err != nil {
// fmt.Println(err)
// return
// }
// file, raw := xlsx.GetPicture("Sheet1", "A2")
// if file == "" {
// return
// }
// err := ioutil.WriteFile(file, raw, 0644)
// if err != nil {
// fmt.Println(err)
// }
//
func (f *File) GetPicture(sheet, cell string) (string, []byte) {
xlsx := f.workSheetReader(sheet)
if xlsx.Drawing == nil {
return "", []byte{}
}
target := f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
drawingXML := strings.Replace(target, "..", "xl", -1)
_, ok := f.XLSX[drawingXML]
if !ok {
return "", nil
}
decodeWsDr := decodeWsDr{}
_ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(drawingXML)), &decodeWsDr)
cell = strings.ToUpper(cell)
fromCol := string(strings.Map(letterOnlyMapF, cell))
fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
row := fromRow - 1
col := TitleToNumber(fromCol)
drawingRelationships := strings.Replace(strings.Replace(target, "../drawings", "xl/drawings/_rels", -1), ".xml", ".xml.rels", -1)
for _, anchor := range decodeWsDr.TwoCellAnchor {
decodeTwoCellAnchor := decodeTwoCellAnchor{}
_ = xml.Unmarshal([]byte("<decodeTwoCellAnchor>"+anchor.Content+"</decodeTwoCellAnchor>"), &decodeTwoCellAnchor)
if decodeTwoCellAnchor.From != nil && decodeTwoCellAnchor.Pic != nil {
if decodeTwoCellAnchor.From.Col == col && decodeTwoCellAnchor.From.Row == row {
xlsxWorkbookRelation := f.getDrawingRelationships(drawingRelationships, decodeTwoCellAnchor.Pic.BlipFill.Blip.Embed)
_, ok := supportImageTypes[filepath.Ext(xlsxWorkbookRelation.Target)]
if ok {
return filepath.Base(xlsxWorkbookRelation.Target), []byte(f.XLSX[strings.Replace(xlsxWorkbookRelation.Target, "..", "xl", -1)])
}
}
}
}
return "", []byte{}
}
// getDrawingRelationships provides a function to get drawing relationships
// from xl/drawings/_rels/drawing%s.xml.rels by given file name and
// relationship ID.
func (f *File) getDrawingRelationships(rels, rID string) *xlsxWorkbookRelation {
_, ok := f.XLSX[rels]
if !ok {
return nil
}
var drawingRels xlsxWorkbookRels
_ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(rels)), &drawingRels)
for _, v := range drawingRels.Relationships {
if v.ID == rID {
return &v
}
}
return nil
}

View File

@ -1,510 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"math"
"strconv"
"strings"
)
// GetRows return all the rows in a sheet by given worksheet name (case
// sensitive). For example:
//
// for _, row := range xlsx.GetRows("Sheet1") {
// for _, colCell := range row {
// fmt.Print(colCell, "\t")
// }
// fmt.Println()
// }
//
func (f *File) GetRows(sheet string) [][]string {
xlsx := f.workSheetReader(sheet)
name, ok := f.sheetMap[trimSheetName(sheet)]
if !ok {
return [][]string{}
}
if xlsx != nil {
output, _ := xml.Marshal(f.Sheet[name])
f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
}
xml.NewDecoder(bytes.NewReader(f.readXML(name)))
d := f.sharedStringsReader()
var inElement string
var r xlsxRow
tr, tc := f.getTotalRowsCols(name)
rows := make([][]string, tr)
for i := range rows {
rows[i] = make([]string, tc+1)
}
var row int
decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
for {
token, _ := decoder.Token()
if token == nil {
break
}
switch startElement := token.(type) {
case xml.StartElement:
inElement = startElement.Name.Local
if inElement == "row" {
r = xlsxRow{}
_ = decoder.DecodeElement(&r, &startElement)
cr := r.R - 1
for _, colCell := range r.C {
c := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
val, _ := colCell.getValueFrom(f, d)
rows[cr][c] = val
if val != "" {
row = r.R
}
}
}
default:
}
}
return rows[:row]
}
// Rows defines an iterator to a sheet
type Rows struct {
decoder *xml.Decoder
token xml.Token
err error
f *File
}
// Next will return true if find the next row element.
func (rows *Rows) Next() bool {
for {
rows.token, rows.err = rows.decoder.Token()
if rows.err == io.EOF {
rows.err = nil
}
if rows.token == nil {
return false
}
switch startElement := rows.token.(type) {
case xml.StartElement:
inElement := startElement.Name.Local
if inElement == "row" {
return true
}
}
}
}
// Error will return the error when the find next row element
func (rows *Rows) Error() error {
return rows.err
}
// Columns return the current row's column values
func (rows *Rows) Columns() []string {
if rows.token == nil {
return []string{}
}
startElement := rows.token.(xml.StartElement)
r := xlsxRow{}
_ = rows.decoder.DecodeElement(&r, &startElement)
d := rows.f.sharedStringsReader()
row := make([]string, len(r.C))
for _, colCell := range r.C {
c := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
val, _ := colCell.getValueFrom(rows.f, d)
row[c] = val
}
return row
}
// ErrSheetNotExist defines an error of sheet is not exist
type ErrSheetNotExist struct {
SheetName string
}
func (err ErrSheetNotExist) Error() string {
return fmt.Sprintf("Sheet %s is not exist", string(err.SheetName))
}
// Rows return a rows iterator. For example:
//
// rows, err := xlsx.Rows("Sheet1")
// for rows.Next() {
// for _, colCell := range rows.Columns() {
// fmt.Print(colCell, "\t")
// }
// fmt.Println()
// }
//
func (f *File) Rows(sheet string) (*Rows, error) {
xlsx := f.workSheetReader(sheet)
name, ok := f.sheetMap[trimSheetName(sheet)]
if !ok {
return nil, ErrSheetNotExist{sheet}
}
if xlsx != nil {
output, _ := xml.Marshal(f.Sheet[name])
f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
}
return &Rows{
f: f,
decoder: xml.NewDecoder(bytes.NewReader(f.readXML(name))),
}, nil
}
// getTotalRowsCols provides a function to get total columns and rows in a
// worksheet.
func (f *File) getTotalRowsCols(name string) (int, int) {
decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
var inElement string
var r xlsxRow
var tr, tc int
for {
token, _ := decoder.Token()
if token == nil {
break
}
switch startElement := token.(type) {
case xml.StartElement:
inElement = startElement.Name.Local
if inElement == "row" {
r = xlsxRow{}
_ = decoder.DecodeElement(&r, &startElement)
tr = r.R
for _, colCell := range r.C {
col := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
if col > tc {
tc = col
}
}
}
default:
}
}
return tr, tc
}
// SetRowHeight provides a function to set the height of a single row. For
// example, set the height of the first row in Sheet1:
//
// xlsx.SetRowHeight("Sheet1", 1, 50)
//
func (f *File) SetRowHeight(sheet string, row int, height float64) {
xlsx := f.workSheetReader(sheet)
cells := 0
rowIdx := row - 1
completeRow(xlsx, row, cells)
xlsx.SheetData.Row[rowIdx].Ht = height
xlsx.SheetData.Row[rowIdx].CustomHeight = true
}
// getRowHeight provides a function to get row height in pixels by given sheet
// name and row index.
func (f *File) getRowHeight(sheet string, row int) int {
xlsx := f.workSheetReader(sheet)
for _, v := range xlsx.SheetData.Row {
if v.R == row+1 && v.Ht != 0 {
return int(convertRowHeightToPixels(v.Ht))
}
}
// Optimisation for when the row heights haven't changed.
return int(defaultRowHeightPixels)
}
// GetRowHeight provides a function to get row height by given worksheet name
// and row index. For example, get the height of the first row in Sheet1:
//
// xlsx.GetRowHeight("Sheet1", 1)
//
func (f *File) GetRowHeight(sheet string, row int) float64 {
xlsx := f.workSheetReader(sheet)
for _, v := range xlsx.SheetData.Row {
if v.R == row && v.Ht != 0 {
return v.Ht
}
}
// Optimisation for when the row heights haven't changed.
return defaultRowHeightPixels
}
// sharedStringsReader provides a function to get the pointer to the structure
// after deserialization of xl/sharedStrings.xml.
func (f *File) sharedStringsReader() *xlsxSST {
if f.SharedStrings == nil {
var sharedStrings xlsxSST
ss := f.readXML("xl/sharedStrings.xml")
if len(ss) == 0 {
ss = f.readXML("xl/SharedStrings.xml")
}
_ = xml.Unmarshal(namespaceStrictToTransitional(ss), &sharedStrings)
f.SharedStrings = &sharedStrings
}
return f.SharedStrings
}
// getValueFrom return a value from a column/row cell, this function is
// inteded to be used with for range on rows an argument with the xlsx opened
// file.
func (xlsx *xlsxC) getValueFrom(f *File, d *xlsxSST) (string, error) {
switch xlsx.T {
case "s":
xlsxSI := 0
xlsxSI, _ = strconv.Atoi(xlsx.V)
if len(d.SI[xlsxSI].R) > 0 {
value := ""
for _, v := range d.SI[xlsxSI].R {
value += v.T
}
return value, nil
}
return f.formattedValue(xlsx.S, d.SI[xlsxSI].T), nil
case "str":
return f.formattedValue(xlsx.S, xlsx.V), nil
case "inlineStr":
return f.formattedValue(xlsx.S, xlsx.IS.T), nil
default:
return f.formattedValue(xlsx.S, xlsx.V), nil
}
}
// SetRowVisible provides a function to set visible of a single row by given
// worksheet name and row index. For example, hide row 2 in Sheet1:
//
// xlsx.SetRowVisible("Sheet1", 2, false)
//
func (f *File) SetRowVisible(sheet string, rowIndex int, visible bool) {
xlsx := f.workSheetReader(sheet)
rows := rowIndex + 1
cells := 0
completeRow(xlsx, rows, cells)
if visible {
xlsx.SheetData.Row[rowIndex].Hidden = false
return
}
xlsx.SheetData.Row[rowIndex].Hidden = true
}
// GetRowVisible provides a function to get visible of a single row by given
// worksheet name and row index. For example, get visible state of row 2 in
// Sheet1:
//
// xlsx.GetRowVisible("Sheet1", 2)
//
func (f *File) GetRowVisible(sheet string, rowIndex int) bool {
xlsx := f.workSheetReader(sheet)
rows := rowIndex + 1
cells := 0
completeRow(xlsx, rows, cells)
return !xlsx.SheetData.Row[rowIndex].Hidden
}
// SetRowOutlineLevel provides a function to set outline level number of a
// single row by given worksheet name and row index. For example, outline row
// 2 in Sheet1 to level 1:
//
// xlsx.SetRowOutlineLevel("Sheet1", 2, 1)
//
func (f *File) SetRowOutlineLevel(sheet string, rowIndex int, level uint8) {
xlsx := f.workSheetReader(sheet)
rows := rowIndex + 1
cells := 0
completeRow(xlsx, rows, cells)
xlsx.SheetData.Row[rowIndex].OutlineLevel = level
}
// GetRowOutlineLevel provides a function to get outline level number of a
// single row by given worksheet name and row index. For example, get outline
// number of row 2 in Sheet1:
//
// xlsx.GetRowOutlineLevel("Sheet1", 2)
//
func (f *File) GetRowOutlineLevel(sheet string, rowIndex int) uint8 {
xlsx := f.workSheetReader(sheet)
rows := rowIndex + 1
cells := 0
completeRow(xlsx, rows, cells)
return xlsx.SheetData.Row[rowIndex].OutlineLevel
}
// RemoveRow provides a function to remove single row by given worksheet name
// and row index. For example, remove row 3 in Sheet1:
//
// xlsx.RemoveRow("Sheet1", 2)
//
func (f *File) RemoveRow(sheet string, row int) {
if row < 0 {
return
}
xlsx := f.workSheetReader(sheet)
row++
for i, r := range xlsx.SheetData.Row {
if r.R == row {
xlsx.SheetData.Row = append(xlsx.SheetData.Row[:i], xlsx.SheetData.Row[i+1:]...)
f.adjustHelper(sheet, -1, row, -1)
return
}
}
}
// InsertRow provides a function to insert a new row after given row index.
// For example, create a new row before row 3 in Sheet1:
//
// xlsx.InsertRow("Sheet1", 2)
//
func (f *File) InsertRow(sheet string, row int) {
if row < 0 {
return
}
row++
f.adjustHelper(sheet, -1, row, 1)
}
// DuplicateRow inserts a copy of specified row below specified
//
// xlsx.DuplicateRow("Sheet1", 2)
//
func (f *File) DuplicateRow(sheet string, row int) {
if row < 0 {
return
}
row2 := row + 1
f.adjustHelper(sheet, -1, row2, 1)
xlsx := f.workSheetReader(sheet)
idx := -1
idx2 := -1
for i, r := range xlsx.SheetData.Row {
if r.R == row {
idx = i
} else if r.R == row2 {
idx2 = i
}
if idx != -1 && idx2 != -1 {
break
}
}
if idx == -1 || (idx2 == -1 && len(xlsx.SheetData.Row) >= row2) {
return
}
rowData := xlsx.SheetData.Row[idx]
cols := make([]xlsxC, 0, len(rowData.C))
rowData.C = append(cols, rowData.C...)
f.ajustSingleRowDimensions(&rowData, 1)
if idx2 != -1 {
xlsx.SheetData.Row[idx2] = rowData
} else {
xlsx.SheetData.Row = append(xlsx.SheetData.Row, rowData)
}
}
// checkRow provides a function to check and fill each column element for all
// rows and make that is continuous in a worksheet of XML. For example:
//
// <row r="15" spans="1:22" x14ac:dyDescent="0.2">
// <c r="A15" s="2" />
// <c r="B15" s="2" />
// <c r="F15" s="1" />
// <c r="G15" s="1" />
// </row>
//
// in this case, we should to change it to
//
// <row r="15" spans="1:22" x14ac:dyDescent="0.2">
// <c r="A15" s="2" />
// <c r="B15" s="2" />
// <c r="C15" s="2" />
// <c r="D15" s="2" />
// <c r="E15" s="2" />
// <c r="F15" s="1" />
// <c r="G15" s="1" />
// </row>
//
// Noteice: this method could be very slow for large spreadsheets (more than
// 3000 rows one sheet).
func checkRow(xlsx *xlsxWorksheet) {
buffer := bytes.Buffer{}
for k := range xlsx.SheetData.Row {
lenCol := len(xlsx.SheetData.Row[k].C)
if lenCol > 0 {
endR := string(strings.Map(letterOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
endRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, xlsx.SheetData.Row[k].C[lenCol-1].R))
endCol := TitleToNumber(endR) + 1
if lenCol < endCol {
oldRow := xlsx.SheetData.Row[k].C
xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
tmp := []xlsxC{}
for i := 0; i < endCol; i++ {
buffer.WriteString(ToAlphaString(i))
buffer.WriteString(strconv.Itoa(endRow))
tmp = append(tmp, xlsxC{
R: buffer.String(),
})
buffer.Reset()
}
xlsx.SheetData.Row[k].C = tmp
for _, y := range oldRow {
colAxis := TitleToNumber(string(strings.Map(letterOnlyMapF, y.R)))
xlsx.SheetData.Row[k].C[colAxis] = y
}
}
}
}
}
// completeRow provides a function to check and fill each column element for a
// single row and make that is continuous in a worksheet of XML by given row
// index and axis.
func completeRow(xlsx *xlsxWorksheet, row, cell int) {
currentRows := len(xlsx.SheetData.Row)
if currentRows > 1 {
lastRow := xlsx.SheetData.Row[currentRows-1].R
if lastRow >= row {
row = lastRow
}
}
for i := currentRows; i < row; i++ {
xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
R: i + 1,
})
}
buffer := bytes.Buffer{}
for ii := currentRows; ii < row; ii++ {
start := len(xlsx.SheetData.Row[ii].C)
if start == 0 {
for iii := start; iii < cell; iii++ {
buffer.WriteString(ToAlphaString(iii))
buffer.WriteString(strconv.Itoa(ii + 1))
xlsx.SheetData.Row[ii].C = append(xlsx.SheetData.Row[ii].C, xlsxC{
R: buffer.String(),
})
buffer.Reset()
}
}
}
}
// convertRowHeightToPixels provides a function to convert the height of a
// cell from user's units to pixels. If the height hasn't been set by the user
// we use the default value. If the row is hidden it has a value of zero.
func convertRowHeightToPixels(height float64) float64 {
var pixels float64
if height == 0 {
return pixels
}
pixels = math.Ceil(4.0 / 3.0 * height)
return pixels
}

View File

@ -1,428 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"encoding/json"
"encoding/xml"
"strconv"
"strings"
)
// parseFormatShapeSet provides a function to parse the format settings of the
// shape with default value.
func parseFormatShapeSet(formatSet string) (*formatShape, error) {
format := formatShape{
Width: 160,
Height: 160,
Format: formatPicture{
FPrintsWithSheet: true,
FLocksWithSheet: false,
NoChangeAspect: false,
OffsetX: 0,
OffsetY: 0,
XScale: 1.0,
YScale: 1.0,
},
}
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}
// AddShape provides the method to add shape in a sheet by given worksheet
// index, shape format set (such as offset, scale, aspect ratio setting and
// print settings) and properties set. For example, add text box (rect shape)
// in Sheet1:
//
// xlsx.AddShape("Sheet1", "G6", `{"type":"rect","color":{"line":"#4286F4","fill":"#8eb9ff"},"paragraph":[{"text":"Rectangle Shape","font":{"bold":true,"italic":true,"family":"Berlin Sans FB Demi","size":36,"color":"#777777","underline":"sng"}}],"width":180,"height": 90}`)
//
// The following shows the type of shape supported by excelize:
//
// accentBorderCallout1 (Callout 1 with Border and Accent Shape)
// accentBorderCallout2 (Callout 2 with Border and Accent Shape)
// accentBorderCallout3 (Callout 3 with Border and Accent Shape)
// accentCallout1 (Callout 1 Shape)
// accentCallout2 (Callout 2 Shape)
// accentCallout3 (Callout 3 Shape)
// actionButtonBackPrevious (Back or Previous Button Shape)
// actionButtonBeginning (Beginning Button Shape)
// actionButtonBlank (Blank Button Shape)
// actionButtonDocument (Document Button Shape)
// actionButtonEnd (End Button Shape)
// actionButtonForwardNext (Forward or Next Button Shape)
// actionButtonHelp (Help Button Shape)
// actionButtonHome (Home Button Shape)
// actionButtonInformation (Information Button Shape)
// actionButtonMovie (Movie Button Shape)
// actionButtonReturn (Return Button Shape)
// actionButtonSound (Sound Button Shape)
// arc (Curved Arc Shape)
// bentArrow (Bent Arrow Shape)
// bentConnector2 (Bent Connector 2 Shape)
// bentConnector3 (Bent Connector 3 Shape)
// bentConnector4 (Bent Connector 4 Shape)
// bentConnector5 (Bent Connector 5 Shape)
// bentUpArrow (Bent Up Arrow Shape)
// bevel (Bevel Shape)
// blockArc (Block Arc Shape)
// borderCallout1 (Callout 1 with Border Shape)
// borderCallout2 (Callout 2 with Border Shape)
// borderCallout3 (Callout 3 with Border Shape)
// bracePair (Brace Pair Shape)
// bracketPair (Bracket Pair Shape)
// callout1 (Callout 1 Shape)
// callout2 (Callout 2 Shape)
// callout3 (Callout 3 Shape)
// can (Can Shape)
// chartPlus (Chart Plus Shape)
// chartStar (Chart Star Shape)
// chartX (Chart X Shape)
// chevron (Chevron Shape)
// chord (Chord Shape)
// circularArrow (Circular Arrow Shape)
// cloud (Cloud Shape)
// cloudCallout (Callout Cloud Shape)
// corner (Corner Shape)
// cornerTabs (Corner Tabs Shape)
// cube (Cube Shape)
// curvedConnector2 (Curved Connector 2 Shape)
// curvedConnector3 (Curved Connector 3 Shape)
// curvedConnector4 (Curved Connector 4 Shape)
// curvedConnector5 (Curved Connector 5 Shape)
// curvedDownArrow (Curved Down Arrow Shape)
// curvedLeftArrow (Curved Left Arrow Shape)
// curvedRightArrow (Curved Right Arrow Shape)
// curvedUpArrow (Curved Up Arrow Shape)
// decagon (Decagon Shape)
// diagStripe (Diagonal Stripe Shape)
// diamond (Diamond Shape)
// dodecagon (Dodecagon Shape)
// donut (Donut Shape)
// doubleWave (Double Wave Shape)
// downArrow (Down Arrow Shape)
// downArrowCallout (Callout Down Arrow Shape)
// ellipse (Ellipse Shape)
// ellipseRibbon (Ellipse Ribbon Shape)
// ellipseRibbon2 (Ellipse Ribbon 2 Shape)
// flowChartAlternateProcess (Alternate Process Flow Shape)
// flowChartCollate (Collate Flow Shape)
// flowChartConnector (Connector Flow Shape)
// flowChartDecision (Decision Flow Shape)
// flowChartDelay (Delay Flow Shape)
// flowChartDisplay (Display Flow Shape)
// flowChartDocument (Document Flow Shape)
// flowChartExtract (Extract Flow Shape)
// flowChartInputOutput (Input Output Flow Shape)
// flowChartInternalStorage (Internal Storage Flow Shape)
// flowChartMagneticDisk (Magnetic Disk Flow Shape)
// flowChartMagneticDrum (Magnetic Drum Flow Shape)
// flowChartMagneticTape (Magnetic Tape Flow Shape)
// flowChartManualInput (Manual Input Flow Shape)
// flowChartManualOperation (Manual Operation Flow Shape)
// flowChartMerge (Merge Flow Shape)
// flowChartMultidocument (Multi-Document Flow Shape)
// flowChartOfflineStorage (Offline Storage Flow Shape)
// flowChartOffpageConnector (Off-Page Connector Flow Shape)
// flowChartOnlineStorage (Online Storage Flow Shape)
// flowChartOr (Or Flow Shape)
// flowChartPredefinedProcess (Predefined Process Flow Shape)
// flowChartPreparation (Preparation Flow Shape)
// flowChartProcess (Process Flow Shape)
// flowChartPunchedCard (Punched Card Flow Shape)
// flowChartPunchedTape (Punched Tape Flow Shape)
// flowChartSort (Sort Flow Shape)
// flowChartSummingJunction (Summing Junction Flow Shape)
// flowChartTerminator (Terminator Flow Shape)
// foldedCorner (Folded Corner Shape)
// frame (Frame Shape)
// funnel (Funnel Shape)
// gear6 (Gear 6 Shape)
// gear9 (Gear 9 Shape)
// halfFrame (Half Frame Shape)
// heart (Heart Shape)
// heptagon (Heptagon Shape)
// hexagon (Hexagon Shape)
// homePlate (Home Plate Shape)
// horizontalScroll (Horizontal Scroll Shape)
// irregularSeal1 (Irregular Seal 1 Shape)
// irregularSeal2 (Irregular Seal 2 Shape)
// leftArrow (Left Arrow Shape)
// leftArrowCallout (Callout Left Arrow Shape)
// leftBrace (Left Brace Shape)
// leftBracket (Left Bracket Shape)
// leftCircularArrow (Left Circular Arrow Shape)
// leftRightArrow (Left Right Arrow Shape)
// leftRightArrowCallout (Callout Left Right Arrow Shape)
// leftRightCircularArrow (Left Right Circular Arrow Shape)
// leftRightRibbon (Left Right Ribbon Shape)
// leftRightUpArrow (Left Right Up Arrow Shape)
// leftUpArrow (Left Up Arrow Shape)
// lightningBolt (Lightning Bolt Shape)
// line (Line Shape)
// lineInv (Line Inverse Shape)
// mathDivide (Divide Math Shape)
// mathEqual (Equal Math Shape)
// mathMinus (Minus Math Shape)
// mathMultiply (Multiply Math Shape)
// mathNotEqual (Not Equal Math Shape)
// mathPlus (Plus Math Shape)
// moon (Moon Shape)
// nonIsoscelesTrapezoid (Non-Isosceles Trapezoid Shape)
// noSmoking (No Smoking Shape)
// notchedRightArrow (Notched Right Arrow Shape)
// octagon (Octagon Shape)
// parallelogram (Parallelogram Shape)
// pentagon (Pentagon Shape)
// pie (Pie Shape)
// pieWedge (Pie Wedge Shape)
// plaque (Plaque Shape)
// plaqueTabs (Plaque Tabs Shape)
// plus (Plus Shape)
// quadArrow (Quad-Arrow Shape)
// quadArrowCallout (Callout Quad-Arrow Shape)
// rect (Rectangle Shape)
// ribbon (Ribbon Shape)
// ribbon2 (Ribbon 2 Shape)
// rightArrow (Right Arrow Shape)
// rightArrowCallout (Callout Right Arrow Shape)
// rightBrace (Right Brace Shape)
// rightBracket (Right Bracket Shape)
// round1Rect (One Round Corner Rectangle Shape)
// round2DiagRect (Two Diagonal Round Corner Rectangle Shape)
// round2SameRect (Two Same-side Round Corner Rectangle Shape)
// roundRect (Round Corner Rectangle Shape)
// rtTriangle (Right Triangle Shape)
// smileyFace (Smiley Face Shape)
// snip1Rect (One Snip Corner Rectangle Shape)
// snip2DiagRect (Two Diagonal Snip Corner Rectangle Shape)
// snip2SameRect (Two Same-side Snip Corner Rectangle Shape)
// snipRoundRect (One Snip One Round Corner Rectangle Shape)
// squareTabs (Square Tabs Shape)
// star10 (Ten Pointed Star Shape)
// star12 (Twelve Pointed Star Shape)
// star16 (Sixteen Pointed Star Shape)
// star24 (Twenty Four Pointed Star Shape)
// star32 (Thirty Two Pointed Star Shape)
// star4 (Four Pointed Star Shape)
// star5 (Five Pointed Star Shape)
// star6 (Six Pointed Star Shape)
// star7 (Seven Pointed Star Shape)
// star8 (Eight Pointed Star Shape)
// straightConnector1 (Straight Connector 1 Shape)
// stripedRightArrow (Striped Right Arrow Shape)
// sun (Sun Shape)
// swooshArrow (Swoosh Arrow Shape)
// teardrop (Teardrop Shape)
// trapezoid (Trapezoid Shape)
// triangle (Triangle Shape)
// upArrow (Up Arrow Shape)
// upArrowCallout (Callout Up Arrow Shape)
// upDownArrow (Up Down Arrow Shape)
// upDownArrowCallout (Callout Up Down Arrow Shape)
// uturnArrow (U-Turn Arrow Shape)
// verticalScroll (Vertical Scroll Shape)
// wave (Wave Shape)
// wedgeEllipseCallout (Callout Wedge Ellipse Shape)
// wedgeRectCallout (Callout Wedge Rectangle Shape)
// wedgeRoundRectCallout (Callout Wedge Round Rectangle Shape)
//
// The following shows the type of text underline supported by excelize:
//
// none
// words
// sng
// dbl
// heavy
// dotted
// dottedHeavy
// dash
// dashHeavy
// dashLong
// dashLongHeavy
// dotDash
// dotDashHeavy
// dotDotDash
// dotDotDashHeavy
// wavy
// wavyHeavy
// wavyDbl
//
func (f *File) AddShape(sheet, cell, format string) error {
formatSet, err := parseFormatShapeSet(format)
if err != nil {
return err
}
// Read sheet data.
xlsx := f.workSheetReader(sheet)
// Add first shape for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
drawingID := f.countDrawings() + 1
drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
sheetRelationshipsDrawingXML := "../drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
if xlsx.Drawing != nil {
// The worksheet already has a shape or chart relationships, use the relationships drawing ../drawings/drawing%d.xml.
sheetRelationshipsDrawingXML = f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
drawingID, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(sheetRelationshipsDrawingXML, "../drawings/drawing"), ".xml"))
drawingXML = strings.Replace(sheetRelationshipsDrawingXML, "..", "xl", -1)
} else {
// Add first shape for given sheet.
rID := f.addSheetRelationships(sheet, SourceRelationshipDrawingML, sheetRelationshipsDrawingXML, "")
f.addSheetDrawing(sheet, rID)
}
f.addDrawingShape(sheet, drawingXML, cell, formatSet)
f.addContentTypePart(drawingID, "drawings")
return err
}
// addDrawingShape provides a function to add preset geometry by given sheet,
// drawingXMLand format sets.
func (f *File) addDrawingShape(sheet, drawingXML, cell string, formatSet *formatShape) {
textUnderlineType := map[string]bool{"none": true, "words": true, "sng": true, "dbl": true, "heavy": true, "dotted": true, "dottedHeavy": true, "dash": true, "dashHeavy": true, "dashLong": true, "dashLongHeavy": true, "dotDash": true, "dotDashHeavy": true, "dotDotDash": true, "dotDotDashHeavy": true, "wavy": true, "wavyHeavy": true, "wavyDbl": true}
cell = strings.ToUpper(cell)
fromCol := string(strings.Map(letterOnlyMapF, cell))
fromRow, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
row := fromRow - 1
col := TitleToNumber(fromCol)
width := int(float64(formatSet.Width) * formatSet.Format.XScale)
height := int(float64(formatSet.Height) * formatSet.Format.YScale)
colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 := f.positionObjectPixels(sheet, col, row, formatSet.Format.OffsetX, formatSet.Format.OffsetY, width, height)
content := xlsxWsDr{}
content.A = NameSpaceDrawingML
content.Xdr = NameSpaceDrawingMLSpreadSheet
cNvPrID := f.drawingParser(drawingXML, &content)
twoCellAnchor := xdrCellAnchor{}
twoCellAnchor.EditAs = formatSet.Format.Positioning
from := xlsxFrom{}
from.Col = colStart
from.ColOff = formatSet.Format.OffsetX * EMU
from.Row = rowStart
from.RowOff = formatSet.Format.OffsetY * EMU
to := xlsxTo{}
to.Col = colEnd
to.ColOff = x2 * EMU
to.Row = rowEnd
to.RowOff = y2 * EMU
twoCellAnchor.From = &from
twoCellAnchor.To = &to
shape := xdrSp{
NvSpPr: &xdrNvSpPr{
CNvPr: &xlsxCNvPr{
ID: cNvPrID,
Name: "Shape " + strconv.Itoa(cNvPrID),
},
CNvSpPr: &xdrCNvSpPr{
TxBox: true,
},
},
SpPr: &xlsxSpPr{
PrstGeom: xlsxPrstGeom{
Prst: formatSet.Type,
},
},
Style: &xdrStyle{
LnRef: setShapeRef(formatSet.Color.Line, 2),
FillRef: setShapeRef(formatSet.Color.Fill, 1),
EffectRef: setShapeRef(formatSet.Color.Effect, 0),
FontRef: &aFontRef{
Idx: "minor",
SchemeClr: &attrValString{
Val: "tx1",
},
},
},
TxBody: &xdrTxBody{
BodyPr: &aBodyPr{
VertOverflow: "clip",
HorzOverflow: "clip",
Wrap: "none",
RtlCol: false,
Anchor: "t",
},
},
}
if len(formatSet.Paragraph) < 1 {
formatSet.Paragraph = []formatShapeParagraph{
{
Font: formatFont{
Bold: false,
Italic: false,
Underline: "none",
Family: "Calibri",
Size: 11,
Color: "#000000",
},
Text: " ",
},
}
}
for _, p := range formatSet.Paragraph {
u := p.Font.Underline
_, ok := textUnderlineType[u]
if !ok {
u = "none"
}
text := p.Text
if text == "" {
text = " "
}
paragraph := &aP{
R: &aR{
RPr: aRPr{
I: p.Font.Italic,
B: p.Font.Bold,
Lang: "en-US",
AltLang: "en-US",
U: u,
Sz: p.Font.Size * 100,
Latin: &aLatin{Typeface: p.Font.Family},
SolidFill: &aSolidFill{
SrgbClr: &attrValString{
Val: strings.Replace(strings.ToUpper(p.Font.Color), "#", "", -1),
},
},
},
T: text,
},
EndParaRPr: &aEndParaRPr{
Lang: "en-US",
},
}
shape.TxBody.P = append(shape.TxBody.P, paragraph)
}
twoCellAnchor.Sp = &shape
twoCellAnchor.ClientData = &xdrClientData{
FLocksWithSheet: formatSet.Format.FLocksWithSheet,
FPrintsWithSheet: formatSet.Format.FPrintsWithSheet,
}
content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
output, _ := xml.Marshal(content)
f.saveFileList(drawingXML, output)
}
// setShapeRef provides a function to set color with hex model by given actual
// color value.
func setShapeRef(color string, i int) *aRef {
if color == "" {
return &aRef{
Idx: 0,
ScrgbClr: &aScrgbClr{
R: 0,
G: 0,
B: 0,
},
}
}
return &aRef{
Idx: i,
SrgbClr: &attrValString{
Val: strings.Replace(strings.ToUpper(color), "#", "", -1),
},
}
}

View File

@ -1,792 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"regexp"
"strconv"
"strings"
"unicode/utf8"
"github.com/mohae/deepcopy"
)
// NewSheet provides function to create a new sheet by given worksheet name.
// When creating a new XLSX file, the default sheet will be created. Returns
// the number of sheets in the workbook (file) after appending the new sheet.
func (f *File) NewSheet(name string) int {
// Check if the worksheet already exists
if f.GetSheetIndex(name) != 0 {
return f.SheetCount
}
f.DeleteSheet(name)
f.SheetCount++
wb := f.workbookReader()
sheetID := 0
for _, v := range wb.Sheets.Sheet {
if v.SheetID > sheetID {
sheetID = v.SheetID
}
}
sheetID++
// Update docProps/app.xml
f.setAppXML()
// Update [Content_Types].xml
f.setContentTypes(sheetID)
// Create new sheet /xl/worksheets/sheet%d.xml
f.setSheet(sheetID, name)
// Update xl/_rels/workbook.xml.rels
rID := f.addXlsxWorkbookRels(sheetID)
// Update xl/workbook.xml
f.setWorkbook(name, sheetID, rID)
return sheetID
}
// contentTypesReader provides a function to get the pointer to the
// [Content_Types].xml structure after deserialization.
func (f *File) contentTypesReader() *xlsxTypes {
if f.ContentTypes == nil {
var content xlsxTypes
_ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML("[Content_Types].xml")), &content)
f.ContentTypes = &content
}
return f.ContentTypes
}
// contentTypesWriter provides a function to save [Content_Types].xml after
// serialize structure.
func (f *File) contentTypesWriter() {
if f.ContentTypes != nil {
output, _ := xml.Marshal(f.ContentTypes)
f.saveFileList("[Content_Types].xml", output)
}
}
// workbookReader provides a function to get the pointer to the xl/workbook.xml
// structure after deserialization.
func (f *File) workbookReader() *xlsxWorkbook {
if f.WorkBook == nil {
var content xlsxWorkbook
_ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML("xl/workbook.xml")), &content)
f.WorkBook = &content
}
return f.WorkBook
}
// workbookWriter provides a function to save xl/workbook.xml after serialize
// structure.
func (f *File) workbookWriter() {
if f.WorkBook != nil {
output, _ := xml.Marshal(f.WorkBook)
f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpaceBytes(output))
}
}
// worksheetWriter provides a function to save xl/worksheets/sheet%d.xml after
// serialize structure.
func (f *File) worksheetWriter() {
for path, sheet := range f.Sheet {
if sheet != nil {
for k, v := range sheet.SheetData.Row {
f.Sheet[path].SheetData.Row[k].C = trimCell(v.C)
}
output, _ := xml.Marshal(sheet)
f.saveFileList(path, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
ok := f.checked[path]
if ok {
f.checked[path] = false
}
}
}
}
// trimCell provides a function to trim blank cells which created by completeCol.
func trimCell(column []xlsxC) []xlsxC {
col := make([]xlsxC, len(column))
i := 0
for _, c := range column {
if c.S != 0 || c.V != "" || c.F != nil || c.T != "" {
col[i] = c
i++
}
}
return col[0:i]
}
// setContentTypes provides a function to read and update property of contents
// type of XLSX.
func (f *File) setContentTypes(index int) {
content := f.contentTypesReader()
content.Overrides = append(content.Overrides, xlsxOverride{
PartName: "/xl/worksheets/sheet" + strconv.Itoa(index) + ".xml",
ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
})
}
// setSheet provides a function to update sheet property by given index.
func (f *File) setSheet(index int, name string) {
var xlsx xlsxWorksheet
xlsx.Dimension.Ref = "A1"
xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
WorkbookViewID: 0,
})
path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
f.sheetMap[trimSheetName(name)] = path
f.Sheet[path] = &xlsx
}
// setWorkbook update workbook property of XLSX. Maximum 31 characters are
// allowed in sheet title.
func (f *File) setWorkbook(name string, sheetID, rid int) {
content := f.workbookReader()
content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
Name: trimSheetName(name),
SheetID: sheetID,
ID: "rId" + strconv.Itoa(rid),
})
}
// workbookRelsReader provides a function to read and unmarshal workbook
// relationships of XLSX file.
func (f *File) workbookRelsReader() *xlsxWorkbookRels {
if f.WorkBookRels == nil {
var content xlsxWorkbookRels
_ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML("xl/_rels/workbook.xml.rels")), &content)
f.WorkBookRels = &content
}
return f.WorkBookRels
}
// workbookRelsWriter provides a function to save xl/_rels/workbook.xml.rels after
// serialize structure.
func (f *File) workbookRelsWriter() {
if f.WorkBookRels != nil {
output, _ := xml.Marshal(f.WorkBookRels)
f.saveFileList("xl/_rels/workbook.xml.rels", output)
}
}
// addXlsxWorkbookRels update workbook relationships property of XLSX.
func (f *File) addXlsxWorkbookRels(sheet int) int {
content := f.workbookRelsReader()
rID := 0
for _, v := range content.Relationships {
t, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
if t > rID {
rID = t
}
}
rID++
ID := bytes.Buffer{}
ID.WriteString("rId")
ID.WriteString(strconv.Itoa(rID))
target := bytes.Buffer{}
target.WriteString("worksheets/sheet")
target.WriteString(strconv.Itoa(sheet))
target.WriteString(".xml")
content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
ID: ID.String(),
Target: target.String(),
Type: SourceRelationshipWorkSheet,
})
return rID
}
// setAppXML update docProps/app.xml file of XML.
func (f *File) setAppXML() {
f.saveFileList("docProps/app.xml", []byte(templateDocpropsApp))
}
// replaceRelationshipsNameSpaceBytes; Some tools that read XLSX files have
// very strict requirements about the structure of the input XML. In
// particular both Numbers on the Mac and SAS dislike inline XML namespace
// declarations, or namespace prefixes that don't match the ones that Excel
// itself uses. This is a problem because the Go XML library doesn't multiple
// namespace declarations in a single element of a document. This function is
// a horrible hack to fix that after the XML marshalling is completed.
func replaceRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
oldXmlns := []byte(`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
newXmlns := []byte(`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x15" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main">`)
return bytes.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
}
// SetActiveSheet provides function to set default active worksheet of XLSX by
// given index. Note that active index is different from the index returned by
// function GetSheetMap(). It should be greater than 0 and less than total
// worksheet numbers.
func (f *File) SetActiveSheet(index int) {
if index < 1 {
index = 1
}
wb := f.workbookReader()
for activeTab, sheet := range wb.Sheets.Sheet {
if sheet.SheetID == index {
if len(wb.BookViews.WorkBookView) > 0 {
wb.BookViews.WorkBookView[0].ActiveTab = activeTab
} else {
wb.BookViews.WorkBookView = append(wb.BookViews.WorkBookView, xlsxWorkBookView{
ActiveTab: activeTab,
})
}
}
}
for idx, name := range f.GetSheetMap() {
xlsx := f.workSheetReader(name)
if len(xlsx.SheetViews.SheetView) > 0 {
xlsx.SheetViews.SheetView[0].TabSelected = false
}
if index == idx {
if len(xlsx.SheetViews.SheetView) > 0 {
xlsx.SheetViews.SheetView[0].TabSelected = true
} else {
xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
TabSelected: true,
})
}
}
}
}
// GetActiveSheetIndex provides a function to get active sheet index of the
// XLSX. If not found the active sheet will be return integer 0.
func (f *File) GetActiveSheetIndex() int {
for idx, name := range f.GetSheetMap() {
xlsx := f.workSheetReader(name)
for _, sheetView := range xlsx.SheetViews.SheetView {
if sheetView.TabSelected {
return idx
}
}
}
return 0
}
// SetSheetName provides a function to set the worksheet name be given old and new
// worksheet name. Maximum 31 characters are allowed in sheet title and this
// function only changes the name of the sheet and will not update the sheet
// name in the formula or reference associated with the cell. So there may be
// problem formula error or reference missing.
func (f *File) SetSheetName(oldName, newName string) {
oldName = trimSheetName(oldName)
newName = trimSheetName(newName)
content := f.workbookReader()
for k, v := range content.Sheets.Sheet {
if v.Name == oldName {
content.Sheets.Sheet[k].Name = newName
f.sheetMap[newName] = f.sheetMap[oldName]
delete(f.sheetMap, oldName)
}
}
}
// GetSheetName provides a function to get worksheet name of XLSX by given
// worksheet index. If given sheet index is invalid, will return an empty
// string.
func (f *File) GetSheetName(index int) string {
content := f.workbookReader()
rels := f.workbookRelsReader()
for _, rel := range rels.Relationships {
rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
if rID == index {
for _, v := range content.Sheets.Sheet {
if v.ID == rel.ID {
return v.Name
}
}
}
}
return ""
}
// GetSheetIndex provides a function to get worksheet index of XLSX by given sheet
// name. If given worksheet name is invalid, will return an integer type value
// 0.
func (f *File) GetSheetIndex(name string) int {
content := f.workbookReader()
rels := f.workbookRelsReader()
for _, v := range content.Sheets.Sheet {
if v.Name == name {
for _, rel := range rels.Relationships {
if v.ID == rel.ID {
rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
return rID
}
}
}
}
return 0
}
// GetSheetMap provides a function to get worksheet name and index map of XLSX.
// For example:
//
// xlsx, err := excelize.OpenFile("./Book1.xlsx")
// if err != nil {
// return
// }
// for index, name := range xlsx.GetSheetMap() {
// fmt.Println(index, name)
// }
//
func (f *File) GetSheetMap() map[int]string {
content := f.workbookReader()
rels := f.workbookRelsReader()
sheetMap := map[int]string{}
for _, v := range content.Sheets.Sheet {
for _, rel := range rels.Relationships {
relStr := strings.SplitN(rel.Target, "worksheets/sheet", 2)
if rel.ID == v.ID && len(relStr) == 2 {
rID, _ := strconv.Atoi(strings.TrimSuffix(relStr[1], ".xml"))
sheetMap[rID] = v.Name
}
}
}
return sheetMap
}
// getSheetMap provides a function to get worksheet name and XML file path map of
// XLSX.
func (f *File) getSheetMap() map[string]string {
maps := make(map[string]string)
for idx, name := range f.GetSheetMap() {
maps[name] = "xl/worksheets/sheet" + strconv.Itoa(idx) + ".xml"
}
return maps
}
// SetSheetBackground provides a function to set background picture by given
// worksheet name and file path.
func (f *File) SetSheetBackground(sheet, picture string) error {
var err error
// Check picture exists first.
if _, err = os.Stat(picture); os.IsNotExist(err) {
return err
}
ext, ok := supportImageTypes[path.Ext(picture)]
if !ok {
return errors.New("unsupported image extension")
}
pictureID := f.countMedia() + 1
rID := f.addSheetRelationships(sheet, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, "")
f.addSheetPicture(sheet, rID)
file, _ := ioutil.ReadFile(picture)
f.addMedia(file, ext)
f.setContentTypePartImageExtensions()
return err
}
// DeleteSheet provides a function to delete worksheet in a workbook by given
// worksheet name. Use this method with caution, which will affect changes in
// references such as formulas, charts, and so on. If there is any referenced
// value of the deleted worksheet, it will cause a file error when you open it.
// This function will be invalid when only the one worksheet is left.
func (f *File) DeleteSheet(name string) {
content := f.workbookReader()
for k, v := range content.Sheets.Sheet {
if v.Name == trimSheetName(name) && len(content.Sheets.Sheet) > 1 {
content.Sheets.Sheet = append(content.Sheets.Sheet[:k], content.Sheets.Sheet[k+1:]...)
sheet := "xl/worksheets/sheet" + strconv.Itoa(v.SheetID) + ".xml"
rels := "xl/worksheets/_rels/sheet" + strconv.Itoa(v.SheetID) + ".xml.rels"
target := f.deleteSheetFromWorkbookRels(v.ID)
f.deleteSheetFromContentTypes(target)
delete(f.sheetMap, name)
delete(f.XLSX, sheet)
delete(f.XLSX, rels)
delete(f.Sheet, sheet)
f.SheetCount--
}
}
f.SetActiveSheet(len(f.GetSheetMap()))
}
// deleteSheetFromWorkbookRels provides a function to remove worksheet
// relationships by given relationships ID in the file
// xl/_rels/workbook.xml.rels.
func (f *File) deleteSheetFromWorkbookRels(rID string) string {
content := f.workbookRelsReader()
for k, v := range content.Relationships {
if v.ID == rID {
content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
return v.Target
}
}
return ""
}
// deleteSheetFromContentTypes provides a function to remove worksheet
// relationships by given target name in the file [Content_Types].xml.
func (f *File) deleteSheetFromContentTypes(target string) {
content := f.contentTypesReader()
for k, v := range content.Overrides {
if v.PartName == "/xl/"+target {
content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
}
}
}
// CopySheet provides a function to duplicate a worksheet by gave source and
// target worksheet index. Note that currently doesn't support duplicate
// workbooks that contain tables, charts or pictures. For Example:
//
// // Sheet1 already exists...
// index := xlsx.NewSheet("Sheet2")
// err := xlsx.CopySheet(1, index)
// return err
//
func (f *File) CopySheet(from, to int) error {
if from < 1 || to < 1 || from == to || f.GetSheetName(from) == "" || f.GetSheetName(to) == "" {
return errors.New("invalid worksheet index")
}
f.copySheet(from, to)
return nil
}
// copySheet provides a function to duplicate a worksheet by gave source and
// target worksheet name.
func (f *File) copySheet(from, to int) {
sheet := f.workSheetReader("sheet" + strconv.Itoa(from))
worksheet := deepcopy.Copy(sheet).(*xlsxWorksheet)
path := "xl/worksheets/sheet" + strconv.Itoa(to) + ".xml"
if len(worksheet.SheetViews.SheetView) > 0 {
worksheet.SheetViews.SheetView[0].TabSelected = false
}
worksheet.Drawing = nil
worksheet.TableParts = nil
worksheet.PageSetUp = nil
f.Sheet[path] = worksheet
toRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(to) + ".xml.rels"
fromRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(from) + ".xml.rels"
_, ok := f.XLSX[fromRels]
if ok {
f.XLSX[toRels] = f.XLSX[fromRels]
}
}
// SetSheetVisible provides a function to set worksheet visible by given worksheet
// name. A workbook must contain at least one visible worksheet. If the given
// worksheet has been activated, this setting will be invalidated. Sheet state
// values as defined by http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.sheetstatevalues.aspx
//
// visible
// hidden
// veryHidden
//
// For example, hide Sheet1:
//
// xlsx.SetSheetVisible("Sheet1", false)
//
func (f *File) SetSheetVisible(name string, visible bool) {
name = trimSheetName(name)
content := f.workbookReader()
if visible {
for k, v := range content.Sheets.Sheet {
if v.Name == name {
content.Sheets.Sheet[k].State = ""
}
}
return
}
count := 0
for _, v := range content.Sheets.Sheet {
if v.State != "hidden" {
count++
}
}
for k, v := range content.Sheets.Sheet {
xlsx := f.workSheetReader(f.GetSheetMap()[k])
tabSelected := false
if len(xlsx.SheetViews.SheetView) > 0 {
tabSelected = xlsx.SheetViews.SheetView[0].TabSelected
}
if v.Name == name && count > 1 && !tabSelected {
content.Sheets.Sheet[k].State = "hidden"
}
}
}
// parseFormatPanesSet provides a function to parse the panes settings.
func parseFormatPanesSet(formatSet string) (*formatPanes, error) {
format := formatPanes{}
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}
// SetPanes provides a function to create and remove freeze panes and split panes
// by given worksheet name and panes format set.
//
// activePane defines the pane that is active. The possible values for this
// attribute are defined in the following table:
//
// Enumeration Value | Description
// --------------------------------+-------------------------------------------------------------
// bottomLeft (Bottom Left Pane) | Bottom left pane, when both vertical and horizontal
// | splits are applied.
// |
// | This value is also used when only a horizontal split has
// | been applied, dividing the pane into upper and lower
// | regions. In that case, this value specifies the bottom
// | pane.
// |
// bottomRight (Bottom Right Pane) | Bottom right pane, when both vertical and horizontal
// | splits are applied.
// |
// topLeft (Top Left Pane) | Top left pane, when both vertical and horizontal splits
// | are applied.
// |
// | This value is also used when only a horizontal split has
// | been applied, dividing the pane into upper and lower
// | regions. In that case, this value specifies the top pane.
// |
// | This value is also used when only a vertical split has
// | been applied, dividing the pane into right and left
// | regions. In that case, this value specifies the left pane
// |
// topRight (Top Right Pane) | Top right pane, when both vertical and horizontal
// | splits are applied.
// |
// | This value is also used when only a vertical split has
// | been applied, dividing the pane into right and left
// | regions. In that case, this value specifies the right
// | pane.
//
// Pane state type is restricted to the values supported currently listed in the following table:
//
// Enumeration Value | Description
// --------------------------------+-------------------------------------------------------------
// frozen (Frozen) | Panes are frozen, but were not split being frozen. In
// | this state, when the panes are unfrozen again, a single
// | pane results, with no split.
// |
// | In this state, the split bars are not adjustable.
// |
// split (Split) | Panes are split, but not frozen. In this state, the split
// | bars are adjustable by the user.
//
// x_split (Horizontal Split Position): Horizontal position of the split, in
// 1/20th of a point; 0 (zero) if none. If the pane is frozen, this value
// indicates the number of columns visible in the top pane.
//
// y_split (Vertical Split Position): Vertical position of the split, in 1/20th
// of a point; 0 (zero) if none. If the pane is frozen, this value indicates the
// number of rows visible in the left pane. The possible values for this
// attribute are defined by the W3C XML Schema double datatype.
//
// top_left_cell: Location of the top left visible cell in the bottom right pane
// (when in Left-To-Right mode).
//
// sqref (Sequence of References): Range of the selection. Can be non-contiguous
// set of ranges.
//
// An example of how to freeze column A in the Sheet1 and set the active cell on
// Sheet1!K16:
//
// xlsx.SetPanes("Sheet1", `{"freeze":true,"split":false,"x_split":1,"y_split":0,"top_left_cell":"B1","active_pane":"topRight","panes":[{"sqref":"K16","active_cell":"K16","pane":"topRight"}]}`)
//
// An example of how to freeze rows 1 to 9 in the Sheet1 and set the active cell
// ranges on Sheet1!A11:XFD11:
//
// xlsx.SetPanes("Sheet1", `{"freeze":true,"split":false,"x_split":0,"y_split":9,"top_left_cell":"A34","active_pane":"bottomLeft","panes":[{"sqref":"A11:XFD11","active_cell":"A11","pane":"bottomLeft"}]}`)
//
// An example of how to create split panes in the Sheet1 and set the active cell
// on Sheet1!J60:
//
// xlsx.SetPanes("Sheet1", `{"freeze":false,"split":true,"x_split":3270,"y_split":1800,"top_left_cell":"N57","active_pane":"bottomLeft","panes":[{"sqref":"I36","active_cell":"I36"},{"sqref":"G33","active_cell":"G33","pane":"topRight"},{"sqref":"J60","active_cell":"J60","pane":"bottomLeft"},{"sqref":"O60","active_cell":"O60","pane":"bottomRight"}]}`)
//
// An example of how to unfreeze and remove all panes on Sheet1:
//
// xlsx.SetPanes("Sheet1", `{"freeze":false,"split":false}`)
//
func (f *File) SetPanes(sheet, panes string) {
fs, _ := parseFormatPanesSet(panes)
xlsx := f.workSheetReader(sheet)
p := &xlsxPane{
ActivePane: fs.ActivePane,
TopLeftCell: fs.TopLeftCell,
XSplit: float64(fs.XSplit),
YSplit: float64(fs.YSplit),
}
if fs.Freeze {
p.State = "frozen"
}
xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = p
if !(fs.Freeze) && !(fs.Split) {
if len(xlsx.SheetViews.SheetView) > 0 {
xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Pane = nil
}
}
s := []*xlsxSelection{}
for _, p := range fs.Panes {
s = append(s, &xlsxSelection{
ActiveCell: p.ActiveCell,
Pane: p.Pane,
SQRef: p.SQRef,
})
}
xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Selection = s
}
// GetSheetVisible provides a function to get worksheet visible by given worksheet
// name. For example, get visible state of Sheet1:
//
// xlsx.GetSheetVisible("Sheet1")
//
func (f *File) GetSheetVisible(name string) bool {
content := f.workbookReader()
visible := false
for k, v := range content.Sheets.Sheet {
if v.Name == trimSheetName(name) {
if content.Sheets.Sheet[k].State == "" || content.Sheets.Sheet[k].State == "visible" {
visible = true
}
}
}
return visible
}
// SearchSheet provides a function to get coordinates by given worksheet name,
// cell value, and regular expression. The function doesn't support searching
// on the calculated result, formatted numbers and conditional lookup
// currently. If it is a merged cell, it will return the coordinates of the
// upper left corner of the merged area.
//
// An example of search the coordinates of the value of "100" on Sheet1:
//
// xlsx.SearchSheet("Sheet1", "100")
//
// An example of search the coordinates where the numerical value in the range
// of "0-9" of Sheet1 is described:
//
// xlsx.SearchSheet("Sheet1", "[0-9]", true)
//
func (f *File) SearchSheet(sheet, value string, reg ...bool) []string {
var regSearch bool
for _, r := range reg {
regSearch = r
}
xlsx := f.workSheetReader(sheet)
result := []string{}
name, ok := f.sheetMap[trimSheetName(sheet)]
if !ok {
return result
}
if xlsx != nil {
output, _ := xml.Marshal(f.Sheet[name])
f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
}
xml.NewDecoder(bytes.NewReader(f.readXML(name)))
d := f.sharedStringsReader()
var inElement string
var r xlsxRow
decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
for {
token, _ := decoder.Token()
if token == nil {
break
}
switch startElement := token.(type) {
case xml.StartElement:
inElement = startElement.Name.Local
if inElement == "row" {
r = xlsxRow{}
_ = decoder.DecodeElement(&r, &startElement)
for _, colCell := range r.C {
val, _ := colCell.getValueFrom(f, d)
if regSearch {
regex := regexp.MustCompile(value)
if !regex.MatchString(val) {
continue
}
} else {
if val != value {
continue
}
}
result = append(result, fmt.Sprintf("%s%d", strings.Map(letterOnlyMapF, colCell.R), r.R))
}
}
default:
}
}
return result
}
// ProtectSheet provides a function to prevent other users from accidentally
// or deliberately changing, moving, or deleting data in a worksheet. For
// example, protect Sheet1 with protection settings:
//
// xlsx.ProtectSheet("Sheet1", &excelize.FormatSheetProtection{
// Password: "password",
// EditScenarios: false,
// })
//
func (f *File) ProtectSheet(sheet string, settings *FormatSheetProtection) {
xlsx := f.workSheetReader(sheet)
if settings == nil {
settings = &FormatSheetProtection{
EditObjects: true,
EditScenarios: true,
SelectLockedCells: true,
}
}
xlsx.SheetProtection = &xlsxSheetProtection{
AutoFilter: settings.AutoFilter,
DeleteColumns: settings.DeleteColumns,
DeleteRows: settings.DeleteRows,
FormatCells: settings.FormatCells,
FormatColumns: settings.FormatColumns,
FormatRows: settings.FormatRows,
InsertColumns: settings.InsertColumns,
InsertHyperlinks: settings.InsertHyperlinks,
InsertRows: settings.InsertRows,
Objects: settings.EditObjects,
PivotTables: settings.PivotTables,
Scenarios: settings.EditScenarios,
SelectLockedCells: settings.SelectLockedCells,
SelectUnlockedCells: settings.SelectUnlockedCells,
Sheet: true,
Sort: settings.Sort,
}
if settings.Password != "" {
xlsx.SheetProtection.Password = genSheetPasswd(settings.Password)
}
}
// UnprotectSheet provides a function to unprotect an Excel worksheet.
func (f *File) UnprotectSheet(sheet string) {
xlsx := f.workSheetReader(sheet)
xlsx.SheetProtection = nil
}
// trimSheetName provides a function to trim invaild characters by given worksheet
// name.
func trimSheetName(name string) string {
r := []rune{}
for _, v := range name {
switch v {
case 58, 92, 47, 63, 42, 91, 93: // replace :\/?*[]
continue
default:
r = append(r, v)
}
}
name = string(r)
if utf8.RuneCountInString(name) > 31 {
name = string([]rune(name)[0:31])
}
return name
}

View File

@ -1,168 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
// SheetPrOption is an option of a view of a worksheet. See SetSheetPrOptions().
type SheetPrOption interface {
setSheetPrOption(view *xlsxSheetPr)
}
// SheetPrOptionPtr is a writable SheetPrOption. See GetSheetPrOptions().
type SheetPrOptionPtr interface {
SheetPrOption
getSheetPrOption(view *xlsxSheetPr)
}
type (
// CodeName is a SheetPrOption
CodeName string
// EnableFormatConditionsCalculation is a SheetPrOption
EnableFormatConditionsCalculation bool
// Published is a SheetPrOption
Published bool
// FitToPage is a SheetPrOption
FitToPage bool
// AutoPageBreaks is a SheetPrOption
AutoPageBreaks bool
// OutlineSummaryBelow is an outlinePr, within SheetPr option
OutlineSummaryBelow bool
)
func (o OutlineSummaryBelow) setSheetPrOption(pr *xlsxSheetPr) {
if pr.OutlinePr == nil {
pr.OutlinePr = new(xlsxOutlinePr)
}
pr.OutlinePr.SummaryBelow = bool(o)
}
func (o *OutlineSummaryBelow) getSheetPrOption(pr *xlsxSheetPr) {
// Excel default: true
if pr == nil || pr.OutlinePr == nil {
*o = true
return
}
*o = OutlineSummaryBelow(defaultTrue(&pr.OutlinePr.SummaryBelow))
}
func (o CodeName) setSheetPrOption(pr *xlsxSheetPr) {
pr.CodeName = string(o)
}
func (o *CodeName) getSheetPrOption(pr *xlsxSheetPr) {
if pr == nil {
*o = ""
return
}
*o = CodeName(pr.CodeName)
}
func (o EnableFormatConditionsCalculation) setSheetPrOption(pr *xlsxSheetPr) {
pr.EnableFormatConditionsCalculation = boolPtr(bool(o))
}
func (o *EnableFormatConditionsCalculation) getSheetPrOption(pr *xlsxSheetPr) {
if pr == nil {
*o = true
return
}
*o = EnableFormatConditionsCalculation(defaultTrue(pr.EnableFormatConditionsCalculation))
}
func (o Published) setSheetPrOption(pr *xlsxSheetPr) {
pr.Published = boolPtr(bool(o))
}
func (o *Published) getSheetPrOption(pr *xlsxSheetPr) {
if pr == nil {
*o = true
return
}
*o = Published(defaultTrue(pr.Published))
}
func (o FitToPage) setSheetPrOption(pr *xlsxSheetPr) {
if pr.PageSetUpPr == nil {
if !o {
return
}
pr.PageSetUpPr = new(xlsxPageSetUpPr)
}
pr.PageSetUpPr.FitToPage = bool(o)
}
func (o *FitToPage) getSheetPrOption(pr *xlsxSheetPr) {
// Excel default: false
if pr == nil || pr.PageSetUpPr == nil {
*o = false
return
}
*o = FitToPage(pr.PageSetUpPr.FitToPage)
}
func (o AutoPageBreaks) setSheetPrOption(pr *xlsxSheetPr) {
if pr.PageSetUpPr == nil {
if !o {
return
}
pr.PageSetUpPr = new(xlsxPageSetUpPr)
}
pr.PageSetUpPr.AutoPageBreaks = bool(o)
}
func (o *AutoPageBreaks) getSheetPrOption(pr *xlsxSheetPr) {
// Excel default: false
if pr == nil || pr.PageSetUpPr == nil {
*o = false
return
}
*o = AutoPageBreaks(pr.PageSetUpPr.AutoPageBreaks)
}
// SetSheetPrOptions provides a function to sets worksheet properties.
//
// Available options:
// CodeName(string)
// EnableFormatConditionsCalculation(bool)
// Published(bool)
// FitToPage(bool)
// AutoPageBreaks(bool)
// OutlineSummaryBelow(bool)
func (f *File) SetSheetPrOptions(name string, opts ...SheetPrOption) error {
sheet := f.workSheetReader(name)
pr := sheet.SheetPr
if pr == nil {
pr = new(xlsxSheetPr)
sheet.SheetPr = pr
}
for _, opt := range opts {
opt.setSheetPrOption(pr)
}
return nil
}
// GetSheetPrOptions provides a function to gets worksheet properties.
//
// Available options:
// CodeName(string)
// EnableFormatConditionsCalculation(bool)
// Published(bool)
// FitToPage(bool)
// AutoPageBreaks(bool)
// OutlineSummaryBelow(bool)
func (f *File) GetSheetPrOptions(name string, opts ...SheetPrOptionPtr) error {
sheet := f.workSheetReader(name)
pr := sheet.SheetPr
for _, opt := range opts {
opt.getSheetPrOption(pr)
}
return nil
}

View File

@ -1,171 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "fmt"
// SheetViewOption is an option of a view of a worksheet. See SetSheetViewOptions().
type SheetViewOption interface {
setSheetViewOption(view *xlsxSheetView)
}
// SheetViewOptionPtr is a writable SheetViewOption. See GetSheetViewOptions().
type SheetViewOptionPtr interface {
SheetViewOption
getSheetViewOption(view *xlsxSheetView)
}
type (
// DefaultGridColor is a SheetViewOption.
DefaultGridColor bool
// RightToLeft is a SheetViewOption.
RightToLeft bool
// ShowFormulas is a SheetViewOption.
ShowFormulas bool
// ShowGridLines is a SheetViewOption.
ShowGridLines bool
// ShowRowColHeaders is a SheetViewOption.
ShowRowColHeaders bool
// ZoomScale is a SheetViewOption.
ZoomScale float64
// TopLeftCell is a SheetViewOption.
TopLeftCell string
/* TODO
// ShowWhiteSpace is a SheetViewOption.
ShowWhiteSpace bool
// ShowZeros is a SheetViewOption.
ShowZeros bool
// WindowProtection is a SheetViewOption.
WindowProtection bool
*/
)
// Defaults for each option are described in XML schema for CT_SheetView
func (o TopLeftCell) setSheetViewOption(view *xlsxSheetView) {
view.TopLeftCell = string(o)
}
func (o *TopLeftCell) getSheetViewOption(view *xlsxSheetView) {
*o = TopLeftCell(string(view.TopLeftCell))
}
func (o DefaultGridColor) setSheetViewOption(view *xlsxSheetView) {
view.DefaultGridColor = boolPtr(bool(o))
}
func (o *DefaultGridColor) getSheetViewOption(view *xlsxSheetView) {
*o = DefaultGridColor(defaultTrue(view.DefaultGridColor)) // Excel default: true
}
func (o RightToLeft) setSheetViewOption(view *xlsxSheetView) {
view.RightToLeft = bool(o) // Excel default: false
}
func (o *RightToLeft) getSheetViewOption(view *xlsxSheetView) {
*o = RightToLeft(view.RightToLeft)
}
func (o ShowFormulas) setSheetViewOption(view *xlsxSheetView) {
view.ShowFormulas = bool(o) // Excel default: false
}
func (o *ShowFormulas) getSheetViewOption(view *xlsxSheetView) {
*o = ShowFormulas(view.ShowFormulas) // Excel default: false
}
func (o ShowGridLines) setSheetViewOption(view *xlsxSheetView) {
view.ShowGridLines = boolPtr(bool(o))
}
func (o *ShowGridLines) getSheetViewOption(view *xlsxSheetView) {
*o = ShowGridLines(defaultTrue(view.ShowGridLines)) // Excel default: true
}
func (o ShowRowColHeaders) setSheetViewOption(view *xlsxSheetView) {
view.ShowRowColHeaders = boolPtr(bool(o))
}
func (o *ShowRowColHeaders) getSheetViewOption(view *xlsxSheetView) {
*o = ShowRowColHeaders(defaultTrue(view.ShowRowColHeaders)) // Excel default: true
}
func (o ZoomScale) setSheetViewOption(view *xlsxSheetView) {
//This attribute is restricted to values ranging from 10 to 400.
if float64(o) >= 10 && float64(o) <= 400 {
view.ZoomScale = float64(o)
}
}
func (o *ZoomScale) getSheetViewOption(view *xlsxSheetView) {
*o = ZoomScale(view.ZoomScale)
}
// getSheetView returns the SheetView object
func (f *File) getSheetView(sheetName string, viewIndex int) (*xlsxSheetView, error) {
xlsx := f.workSheetReader(sheetName)
if viewIndex < 0 {
if viewIndex < -len(xlsx.SheetViews.SheetView) {
return nil, fmt.Errorf("view index %d out of range", viewIndex)
}
viewIndex = len(xlsx.SheetViews.SheetView) + viewIndex
} else if viewIndex >= len(xlsx.SheetViews.SheetView) {
return nil, fmt.Errorf("view index %d out of range", viewIndex)
}
return &(xlsx.SheetViews.SheetView[viewIndex]), nil
}
// SetSheetViewOptions sets sheet view options.
// The viewIndex may be negative and if so is counted backward (-1 is the last view).
//
// Available options:
// DefaultGridColor(bool)
// RightToLeft(bool)
// ShowFormulas(bool)
// ShowGridLines(bool)
// ShowRowColHeaders(bool)
// Example:
// err = f.SetSheetViewOptions("Sheet1", -1, ShowGridLines(false))
func (f *File) SetSheetViewOptions(name string, viewIndex int, opts ...SheetViewOption) error {
view, err := f.getSheetView(name, viewIndex)
if err != nil {
return err
}
for _, opt := range opts {
opt.setSheetViewOption(view)
}
return nil
}
// GetSheetViewOptions gets the value of sheet view options.
// The viewIndex may be negative and if so is counted backward (-1 is the last view).
//
// Available options:
// DefaultGridColor(bool)
// RightToLeft(bool)
// ShowFormulas(bool)
// ShowGridLines(bool)
// ShowRowColHeaders(bool)
// Example:
// var showGridLines excelize.ShowGridLines
// err = f.GetSheetViewOptions("Sheet1", -1, &showGridLines)
func (f *File) GetSheetViewOptions(name string, viewIndex int, opts ...SheetViewOptionPtr) error {
view, err := f.getSheetView(name, viewIndex)
if err != nil {
return err
}
for _, opt := range opts {
opt.getSheetViewOption(view)
}
return nil
}

File diff suppressed because it is too large Load Diff

View File

@ -1,461 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"encoding/json"
"encoding/xml"
"fmt"
"regexp"
"strconv"
"strings"
)
// parseFormatTableSet provides a function to parse the format settings of the
// table with default value.
func parseFormatTableSet(formatSet string) (*formatTable, error) {
format := formatTable{
TableStyle: "",
ShowRowStripes: true,
}
err := json.Unmarshal(parseFormatSet(formatSet), &format)
return &format, err
}
// AddTable provides the method to add table in a worksheet by given worksheet
// name, coordinate area and format set. For example, create a table of A1:D5
// on Sheet1:
//
// xlsx.AddTable("Sheet1", "A1", "D5", ``)
//
// Create a table of F2:H6 on Sheet2 with format set:
//
// xlsx.AddTable("Sheet2", "F2", "H6", `{"table_name":"table","table_style":"TableStyleMedium2", "show_first_column":true,"show_last_column":true,"show_row_stripes":false,"show_column_stripes":true}`)
//
// Note that the table at least two lines include string type header. Multiple
// tables coordinate areas can't have an intersection.
//
// table_name: The name of the table, in the same worksheet name of the table should be unique
//
// table_style: The built-in table style names
//
// TableStyleLight1 - TableStyleLight21
// TableStyleMedium1 - TableStyleMedium28
// TableStyleDark1 - TableStyleDark11
//
func (f *File) AddTable(sheet, hcell, vcell, format string) error {
formatSet, err := parseFormatTableSet(format)
if err != nil {
return err
}
hcell = strings.ToUpper(hcell)
vcell = strings.ToUpper(vcell)
// Coordinate conversion, convert C1:B3 to 2,0,1,2.
hcol := string(strings.Map(letterOnlyMapF, hcell))
hrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, hcell))
hyAxis := hrow - 1
hxAxis := TitleToNumber(hcol)
vcol := string(strings.Map(letterOnlyMapF, vcell))
vrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, vcell))
vyAxis := vrow - 1
vxAxis := TitleToNumber(vcol)
if vxAxis < hxAxis {
vxAxis, hxAxis = hxAxis, vxAxis
}
if vyAxis < hyAxis {
vyAxis, hyAxis = hyAxis, vyAxis
}
tableID := f.countTables() + 1
sheetRelationshipsTableXML := "../tables/table" + strconv.Itoa(tableID) + ".xml"
tableXML := strings.Replace(sheetRelationshipsTableXML, "..", "xl", -1)
// Add first table for given sheet.
rID := f.addSheetRelationships(sheet, SourceRelationshipTable, sheetRelationshipsTableXML, "")
f.addSheetTable(sheet, rID)
f.addTable(sheet, tableXML, hxAxis, hyAxis, vxAxis, vyAxis, tableID, formatSet)
f.addContentTypePart(tableID, "table")
return err
}
// countTables provides a function to get table files count storage in the
// folder xl/tables.
func (f *File) countTables() int {
count := 0
for k := range f.XLSX {
if strings.Contains(k, "xl/tables/table") {
count++
}
}
return count
}
// addSheetTable provides a function to add tablePart element to
// xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
func (f *File) addSheetTable(sheet string, rID int) {
xlsx := f.workSheetReader(sheet)
table := &xlsxTablePart{
RID: "rId" + strconv.Itoa(rID),
}
if xlsx.TableParts == nil {
xlsx.TableParts = &xlsxTableParts{}
}
xlsx.TableParts.Count++
xlsx.TableParts.TableParts = append(xlsx.TableParts.TableParts, table)
}
// addTable provides a function to add table by given worksheet name,
// coordinate area and format set.
func (f *File) addTable(sheet, tableXML string, hxAxis, hyAxis, vxAxis, vyAxis, i int, formatSet *formatTable) {
// Correct the minimum number of rows, the table at least two lines.
if hyAxis == vyAxis {
vyAxis++
}
// Correct table reference coordinate area, such correct C1:B3 to B1:C3.
ref := ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
tableColumn := []*xlsxTableColumn{}
idx := 0
for i := hxAxis; i <= vxAxis; i++ {
idx++
cell := ToAlphaString(i) + strconv.Itoa(hyAxis+1)
name := f.GetCellValue(sheet, cell)
if _, err := strconv.Atoi(name); err == nil {
f.SetCellStr(sheet, cell, name)
}
if name == "" {
name = "Column" + strconv.Itoa(idx)
f.SetCellStr(sheet, cell, name)
}
tableColumn = append(tableColumn, &xlsxTableColumn{
ID: idx,
Name: name,
})
}
name := formatSet.TableName
if name == "" {
name = "Table" + strconv.Itoa(i)
}
t := xlsxTable{
XMLNS: NameSpaceSpreadSheet,
ID: i,
Name: name,
DisplayName: name,
Ref: ref,
AutoFilter: &xlsxAutoFilter{
Ref: ref,
},
TableColumns: &xlsxTableColumns{
Count: idx,
TableColumn: tableColumn,
},
TableStyleInfo: &xlsxTableStyleInfo{
Name: formatSet.TableStyle,
ShowFirstColumn: formatSet.ShowFirstColumn,
ShowLastColumn: formatSet.ShowLastColumn,
ShowRowStripes: formatSet.ShowRowStripes,
ShowColumnStripes: formatSet.ShowColumnStripes,
},
}
table, _ := xml.Marshal(t)
f.saveFileList(tableXML, table)
}
// parseAutoFilterSet provides a function to parse the settings of the auto
// filter.
func parseAutoFilterSet(formatSet string) (*formatAutoFilter, error) {
format := formatAutoFilter{}
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}
// AutoFilter provides the method to add auto filter in a worksheet by given
// worksheet name, coordinate area and settings. An autofilter in Excel is a
// way of filtering a 2D range of data based on some simple criteria. For
// example applying an autofilter to a cell range A1:D4 in the Sheet1:
//
// err = xlsx.AutoFilter("Sheet1", "A1", "D4", "")
//
// Filter data in an autofilter:
//
// err = xlsx.AutoFilter("Sheet1", "A1", "D4", `{"column":"B","expression":"x != blanks"}`)
//
// column defines the filter columns in a autofilter range based on simple
// criteria
//
// It isn't sufficient to just specify the filter condition. You must also
// hide any rows that don't match the filter condition. Rows are hidden using
// the SetRowVisible() method. Excelize can't filter rows automatically since
// this isn't part of the file format.
//
// Setting a filter criteria for a column:
//
// expression defines the conditions, the following operators are available
// for setting the filter criteria:
//
// ==
// !=
// >
// <
// >=
// <=
// and
// or
//
// An expression can comprise a single statement or two statements separated
// by the 'and' and 'or' operators. For example:
//
// x < 2000
// x > 2000
// x == 2000
// x > 2000 and x < 5000
// x == 2000 or x == 5000
//
// Filtering of blank or non-blank data can be achieved by using a value of
// Blanks or NonBlanks in the expression:
//
// x == Blanks
// x == NonBlanks
//
// Excel also allows some simple string matching operations:
//
// x == b* // begins with b
// x != b* // doesnt begin with b
// x == *b // ends with b
// x != *b // doesnt end with b
// x == *b* // contains b
// x != *b* // doesn't contains b
//
// You can also use '*' to match any character or number and '?' to match any
// single character or number. No other regular expression quantifier is
// supported by Excel's filters. Excel's regular expression characters can be
// escaped using '~'.
//
// The placeholder variable x in the above examples can be replaced by any
// simple string. The actual placeholder name is ignored internally so the
// following are all equivalent:
//
// x < 2000
// col < 2000
// Price < 2000
//
func (f *File) AutoFilter(sheet, hcell, vcell, format string) error {
formatSet, _ := parseAutoFilterSet(format)
hcell = strings.ToUpper(hcell)
vcell = strings.ToUpper(vcell)
// Coordinate conversion, convert C1:B3 to 2,0,1,2.
hcol := string(strings.Map(letterOnlyMapF, hcell))
hrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, hcell))
hyAxis := hrow - 1
hxAxis := TitleToNumber(hcol)
vcol := string(strings.Map(letterOnlyMapF, vcell))
vrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, vcell))
vyAxis := vrow - 1
vxAxis := TitleToNumber(vcol)
if vxAxis < hxAxis {
vxAxis, hxAxis = hxAxis, vxAxis
}
if vyAxis < hyAxis {
vyAxis, hyAxis = hyAxis, vyAxis
}
ref := ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
refRange := vxAxis - hxAxis
return f.autoFilter(sheet, ref, refRange, hxAxis, formatSet)
}
// autoFilter provides a function to extract the tokens from the filter
// expression. The tokens are mainly non-whitespace groups.
func (f *File) autoFilter(sheet, ref string, refRange, hxAxis int, formatSet *formatAutoFilter) error {
xlsx := f.workSheetReader(sheet)
if xlsx.SheetPr != nil {
xlsx.SheetPr.FilterMode = true
}
xlsx.SheetPr = &xlsxSheetPr{FilterMode: true}
filter := &xlsxAutoFilter{
Ref: ref,
}
xlsx.AutoFilter = filter
if formatSet.Column == "" || formatSet.Expression == "" {
return nil
}
col := TitleToNumber(formatSet.Column)
offset := col - hxAxis
if offset < 0 || offset > refRange {
return fmt.Errorf("incorrect index of column '%s'", formatSet.Column)
}
filter.FilterColumn = &xlsxFilterColumn{
ColID: offset,
}
re := regexp.MustCompile(`"(?:[^"]|"")*"|\S+`)
token := re.FindAllString(formatSet.Expression, -1)
if len(token) != 3 && len(token) != 7 {
return fmt.Errorf("incorrect number of tokens in criteria '%s'", formatSet.Expression)
}
expressions, tokens, err := f.parseFilterExpression(formatSet.Expression, token)
if err != nil {
return err
}
f.writeAutoFilter(filter, expressions, tokens)
xlsx.AutoFilter = filter
return nil
}
// writeAutoFilter provides a function to check for single or double custom
// filters as default filters and handle them accordingly.
func (f *File) writeAutoFilter(filter *xlsxAutoFilter, exp []int, tokens []string) {
if len(exp) == 1 && exp[0] == 2 {
// Single equality.
filters := []*xlsxFilter{}
filters = append(filters, &xlsxFilter{Val: tokens[0]})
filter.FilterColumn.Filters = &xlsxFilters{Filter: filters}
} else if len(exp) == 3 && exp[0] == 2 && exp[1] == 1 && exp[2] == 2 {
// Double equality with "or" operator.
filters := []*xlsxFilter{}
for _, v := range tokens {
filters = append(filters, &xlsxFilter{Val: v})
}
filter.FilterColumn.Filters = &xlsxFilters{Filter: filters}
} else {
// Non default custom filter.
expRel := map[int]int{0: 0, 1: 2}
andRel := map[int]bool{0: true, 1: false}
for k, v := range tokens {
f.writeCustomFilter(filter, exp[expRel[k]], v)
if k == 1 {
filter.FilterColumn.CustomFilters.And = andRel[exp[k]]
}
}
}
}
// writeCustomFilter provides a function to write the <customFilter> element.
func (f *File) writeCustomFilter(filter *xlsxAutoFilter, operator int, val string) {
operators := map[int]string{
1: "lessThan",
2: "equal",
3: "lessThanOrEqual",
4: "greaterThan",
5: "notEqual",
6: "greaterThanOrEqual",
22: "equal",
}
customFilter := xlsxCustomFilter{
Operator: operators[operator],
Val: val,
}
if filter.FilterColumn.CustomFilters != nil {
filter.FilterColumn.CustomFilters.CustomFilter = append(filter.FilterColumn.CustomFilters.CustomFilter, &customFilter)
} else {
customFilters := []*xlsxCustomFilter{}
customFilters = append(customFilters, &customFilter)
filter.FilterColumn.CustomFilters = &xlsxCustomFilters{CustomFilter: customFilters}
}
}
// parseFilterExpression provides a function to converts the tokens of a
// possibly conditional expression into 1 or 2 sub expressions for further
// parsing.
//
// Examples:
//
// ('x', '==', 2000) -> exp1
// ('x', '>', 2000, 'and', 'x', '<', 5000) -> exp1 and exp2
//
func (f *File) parseFilterExpression(expression string, tokens []string) ([]int, []string, error) {
expressions := []int{}
t := []string{}
if len(tokens) == 7 {
// The number of tokens will be either 3 (for 1 expression) or 7 (for 2
// expressions).
conditional := 0
c := tokens[3]
re, _ := regexp.Match(`(or|\|\|)`, []byte(c))
if re {
conditional = 1
}
expression1, token1, err := f.parseFilterTokens(expression, tokens[0:3])
if err != nil {
return expressions, t, err
}
expression2, token2, err := f.parseFilterTokens(expression, tokens[4:7])
if err != nil {
return expressions, t, err
}
expressions = []int{expression1[0], conditional, expression2[0]}
t = []string{token1, token2}
} else {
exp, token, err := f.parseFilterTokens(expression, tokens)
if err != nil {
return expressions, t, err
}
expressions = exp
t = []string{token}
}
return expressions, t, nil
}
// parseFilterTokens provides a function to parse the 3 tokens of a filter
// expression and return the operator and token.
func (f *File) parseFilterTokens(expression string, tokens []string) ([]int, string, error) {
operators := map[string]int{
"==": 2,
"=": 2,
"=~": 2,
"eq": 2,
"!=": 5,
"!~": 5,
"ne": 5,
"<>": 5,
"<": 1,
"<=": 3,
">": 4,
">=": 6,
}
operator, ok := operators[strings.ToLower(tokens[1])]
if !ok {
// Convert the operator from a number to a descriptive string.
return []int{}, "", fmt.Errorf("unknown operator: %s", tokens[1])
}
token := tokens[2]
// Special handling for Blanks/NonBlanks.
re, _ := regexp.Match("blanks|nonblanks", []byte(strings.ToLower(token)))
if re {
// Only allow Equals or NotEqual in this context.
if operator != 2 && operator != 5 {
return []int{operator}, token, fmt.Errorf("the operator '%s' in expression '%s' is not valid in relation to Blanks/NonBlanks'", tokens[1], expression)
}
token = strings.ToLower(token)
// The operator should always be 2 (=) to flag a "simple" equality in
// the binary record. Therefore we convert <> to =.
if token == "blanks" {
if operator == 5 {
token = " "
}
} else {
if operator == 5 {
operator = 2
token = "blanks"
} else {
operator = 5
token = " "
}
}
}
// if the string token contains an Excel match character then change the
// operator type to indicate a non "simple" equality.
re, _ = regexp.Match("[*?]", []byte(token))
if operator == 2 && re {
operator = 22
}
return []int{operator}, token, nil
}

File diff suppressed because one or more lines are too long

View File

@ -1,144 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"
// vmlDrawing directly maps the root element in the file
// xl/drawings/vmlDrawing%d.vml.
type vmlDrawing struct {
XMLName xml.Name `xml:"xml"`
XMLNSv string `xml:"xmlns:v,attr"`
XMLNSo string `xml:"xmlns:o,attr"`
XMLNSx string `xml:"xmlns:x,attr"`
XMLNSmv string `xml:"xmlns:mv,attr"`
Shapelayout *xlsxShapelayout `xml:"o:shapelayout"`
Shapetype *xlsxShapetype `xml:"v:shapetype"`
Shape []xlsxShape `xml:"v:shape"`
}
// xlsxShapelayout directly maps the shapelayout element. This element contains
// child elements that store information used in the editing and layout of
// shapes.
type xlsxShapelayout struct {
Ext string `xml:"v:ext,attr"`
IDmap *xlsxIDmap `xml:"o:idmap"`
}
// xlsxIDmap directly maps the idmap element.
type xlsxIDmap struct {
Ext string `xml:"v:ext,attr"`
Data int `xml:"data,attr"`
}
// xlsxShape directly maps the shape element.
type xlsxShape struct {
XMLName xml.Name `xml:"v:shape"`
ID string `xml:"id,attr"`
Type string `xml:"type,attr"`
Style string `xml:"style,attr"`
Fillcolor string `xml:"fillcolor,attr"`
Insetmode string `xml:"urn:schemas-microsoft-com:office:office insetmode,attr,omitempty"`
Strokecolor string `xml:"strokecolor,attr,omitempty"`
Val string `xml:",innerxml"`
}
// xlsxShapetype directly maps the shapetype element.
type xlsxShapetype struct {
ID string `xml:"id,attr"`
Coordsize string `xml:"coordsize,attr"`
Spt int `xml:"o:spt,attr"`
Path string `xml:"path,attr"`
Stroke *xlsxStroke `xml:"v:stroke"`
VPath *vPath `xml:"v:path"`
}
// xlsxStroke directly maps the stroke element.
type xlsxStroke struct {
Joinstyle string `xml:"joinstyle,attr"`
}
// vPath directly maps the v:path element.
type vPath struct {
Gradientshapeok string `xml:"gradientshapeok,attr,omitempty"`
Connecttype string `xml:"o:connecttype,attr"`
}
// vFill directly maps the v:fill element. This element must be defined within a
// Shape element.
type vFill struct {
Angle int `xml:"angle,attr,omitempty"`
Color2 string `xml:"color2,attr"`
Type string `xml:"type,attr,omitempty"`
Fill *oFill `xml:"o:fill"`
}
// oFill directly maps the o:fill element.
type oFill struct {
Ext string `xml:"v:ext,attr"`
Type string `xml:"type,attr,omitempty"`
}
// vShadow directly maps the v:shadow element. This element must be defined
// within a Shape element. In addition, the On attribute must be set to True.
type vShadow struct {
On string `xml:"on,attr"`
Color string `xml:"color,attr,omitempty"`
Obscured string `xml:"obscured,attr"`
}
// vTextbox directly maps the v:textbox element. This element must be defined
// within a Shape element.
type vTextbox struct {
Style string `xml:"style,attr"`
Div *xlsxDiv `xml:"div"`
}
// xlsxDiv directly maps the div element.
type xlsxDiv struct {
Style string `xml:"style,attr"`
}
// xClientData (Attached Object Data) directly maps the x:ClientData element.
// This element specifies data associated with objects attached to a
// spreadsheet. While this element might contain any of the child elements
// below, only certain combinations are meaningful. The ObjectType attribute
// determines the kind of object the element represents and which subset of
// child elements is appropriate. Relevant groups are identified for each child
// element.
type xClientData struct {
ObjectType string `xml:"ObjectType,attr"`
MoveWithCells string `xml:"x:MoveWithCells,omitempty"`
SizeWithCells string `xml:"x:SizeWithCells,omitempty"`
Anchor string `xml:"x:Anchor"`
AutoFill string `xml:"x:AutoFill"`
Row int `xml:"x:Row"`
Column int `xml:"x:Column"`
}
// decodeVmlDrawing defines the structure used to parse the file
// xl/drawings/vmlDrawing%d.vml.
type decodeVmlDrawing struct {
Shape []decodeShape `xml:"urn:schemas-microsoft-com:vml shape"`
}
// decodeShape defines the structure used to parse the particular shape element.
type decodeShape struct {
Val string `xml:",innerxml"`
}
// encodeShape defines the structure used to re-serialization shape element.
type encodeShape struct {
Fill *vFill `xml:"v:fill"`
Shadow *vShadow `xml:"v:shadow"`
Path *vPath `xml:"v:path"`
Textbox *vTextbox `xml:"v:textbox"`
ClientData *xClientData `xml:"x:ClientData"`
}

View File

@ -1,623 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"
// xlsxChartSpace directly maps the c:chartSpace element. The chart namespace in
// DrawingML is for representing visualizations of numeric data with column
// charts, pie charts, scatter charts, or other types of charts.
type xlsxChartSpace struct {
XMLName xml.Name `xml:"c:chartSpace"`
XMLNSc string `xml:"xmlns:c,attr"`
XMLNSa string `xml:"xmlns:a,attr"`
XMLNSr string `xml:"xmlns:r,attr"`
XMLNSc16r2 string `xml:"xmlns:c16r2,attr"`
Date1904 *attrValBool `xml:"c:date1904"`
Lang *attrValString `xml:"c:lang"`
RoundedCorners *attrValBool `xml:"c:roundedCorners"`
Chart cChart `xml:"c:chart"`
SpPr *cSpPr `xml:"c:spPr"`
TxPr *cTxPr `xml:"c:txPr"`
PrintSettings *cPrintSettings `xml:"c:printSettings"`
}
// cThicknessSpPr directly maps the element that specifies the thickness of the
// walls or floor as a percentage of the largest dimension of the plot volume
// and SpPr element.
type cThicknessSpPr struct {
Thickness *attrValInt `xml:"c:thickness"`
SpPr *cSpPr `xml:"c:spPr"`
}
// cChart (Chart) directly maps the c:chart element. This element specifies a
// title.
type cChart struct {
Title *cTitle `xml:"c:title"`
AutoTitleDeleted *cAutoTitleDeleted `xml:"c:autoTitleDeleted"`
View3D *cView3D `xml:"c:view3D"`
Floor *cThicknessSpPr `xml:"c:floor"`
SideWall *cThicknessSpPr `xml:"c:sideWall"`
BackWall *cThicknessSpPr `xml:"c:backWall"`
PlotArea *cPlotArea `xml:"c:plotArea"`
Legend *cLegend `xml:"c:legend"`
PlotVisOnly *attrValBool `xml:"c:plotVisOnly"`
DispBlanksAs *attrValString `xml:"c:dispBlanksAs"`
ShowDLblsOverMax *attrValBool `xml:"c:showDLblsOverMax"`
}
// cTitle (Title) directly maps the c:title element. This element specifies a
// title.
type cTitle struct {
Tx cTx `xml:"c:tx,omitempty"`
Layout string `xml:"c:layout,omitempty"`
Overlay attrValBool `xml:"c:overlay,omitempty"`
SpPr cSpPr `xml:"c:spPr,omitempty"`
TxPr cTxPr `xml:"c:txPr,omitempty"`
}
// cTx (Chart Text) directly maps the c:tx element. This element specifies text
// to use on a chart, including rich text formatting.
type cTx struct {
StrRef *cStrRef `xml:"c:strRef"`
Rich *cRich `xml:"c:rich,omitempty"`
}
// cRich (Rich Text) directly maps the c:rich element. This element contains a
// string with rich text formatting.
type cRich struct {
BodyPr aBodyPr `xml:"a:bodyPr,omitempty"`
LstStyle string `xml:"a:lstStyle,omitempty"`
P aP `xml:"a:p"`
}
// aBodyPr (Body Properties) directly maps the a:bodyPr element. This element
// defines the body properties for the text body within a shape.
type aBodyPr struct {
Anchor string `xml:"anchor,attr,omitempty"`
AnchorCtr bool `xml:"anchorCtr,attr"`
Rot int `xml:"rot,attr"`
BIns float64 `xml:"bIns,attr,omitempty"`
CompatLnSpc bool `xml:"compatLnSpc,attr,omitempty"`
ForceAA bool `xml:"forceAA,attr,omitempty"`
FromWordArt bool `xml:"fromWordArt,attr,omitempty"`
HorzOverflow string `xml:"horzOverflow,attr,omitempty"`
LIns float64 `xml:"lIns,attr,omitempty"`
NumCol int `xml:"numCol,attr,omitempty"`
RIns float64 `xml:"rIns,attr,omitempty"`
RtlCol bool `xml:"rtlCol,attr,omitempty"`
SpcCol int `xml:"spcCol,attr,omitempty"`
SpcFirstLastPara bool `xml:"spcFirstLastPara,attr"`
TIns float64 `xml:"tIns,attr,omitempty"`
Upright bool `xml:"upright,attr,omitempty"`
Vert string `xml:"vert,attr,omitempty"`
VertOverflow string `xml:"vertOverflow,attr,omitempty"`
Wrap string `xml:"wrap,attr,omitempty"`
}
// aP (Paragraph) directly maps the a:p element. This element specifies a
// paragraph of content in the document.
type aP struct {
PPr *aPPr `xml:"a:pPr"`
R *aR `xml:"a:r"`
EndParaRPr *aEndParaRPr `xml:"a:endParaRPr"`
}
// aPPr (Paragraph Properties) directly maps the a:pPr element. This element
// specifies a set of paragraph properties which shall be applied to the
// contents of the parent paragraph after all style/numbering/table properties
// have been applied to the text. These properties are defined as direct
// formatting, since they are directly applied to the paragraph and supersede
// any formatting from styles.
type aPPr struct {
DefRPr aRPr `xml:"a:defRPr"`
}
// aSolidFill (Solid Fill) directly maps the solidFill element. This element
// specifies a solid color fill. The shape is filled entirely with the specified
// color.
type aSolidFill struct {
SchemeClr *aSchemeClr `xml:"a:schemeClr"`
SrgbClr *attrValString `xml:"a:srgbClr"`
}
// aSchemeClr (Scheme Color) directly maps the a:schemeClr element. This
// element specifies a color bound to a user's theme. As with all elements which
// define a color, it is possible to apply a list of color transforms to the
// base color defined.
type aSchemeClr struct {
Val string `xml:"val,attr,omitempty"`
LumMod *attrValInt `xml:"a:lumMod"`
LumOff *attrValInt `xml:"a:lumOff"`
}
// attrValInt directly maps the val element with integer data type as an
// attribute。
type attrValInt struct {
Val int `xml:"val,attr"`
}
// attrValFloat directly maps the val element with float64 data type as an
// attribute。
type attrValFloat struct {
Val float64 `xml:"val,attr"`
}
// attrValBool directly maps the val element with boolean data type as an
// attribute。
type attrValBool struct {
Val bool `xml:"val,attr"`
}
// attrValString directly maps the val element with string data type as an
// attribute。
type attrValString struct {
Val string `xml:"val,attr"`
}
// aCs directly maps the a:cs element.
type aCs struct {
Typeface string `xml:"typeface,attr"`
}
// aEa directly maps the a:ea element.
type aEa struct {
Typeface string `xml:"typeface,attr"`
}
// aLatin (Latin Font) directly maps the a:latin element. This element
// specifies that a Latin font be used for a specific run of text. This font is
// specified with a typeface attribute much like the others but is specifically
// classified as a Latin font.
type aLatin struct {
Typeface string `xml:"typeface,attr"`
}
// aR directly maps the a:r element.
type aR struct {
RPr aRPr `xml:"a:rPr,omitempty"`
T string `xml:"a:t,omitempty"`
}
// aRPr (Run Properties) directly maps the c:rPr element. This element
// specifies a set of run properties which shall be applied to the contents of
// the parent run after all style formatting has been applied to the text. These
// properties are defined as direct formatting, since they are directly applied
// to the run and supersede any formatting from styles.
type aRPr struct {
AltLang string `xml:"altLang,attr,omitempty"`
B bool `xml:"b,attr"`
Baseline int `xml:"baseline,attr"`
Bmk string `xml:"bmk,attr,omitempty"`
Cap string `xml:"cap,attr,omitempty"`
Dirty bool `xml:"dirty,attr,omitempty"`
Err bool `xml:"err,attr,omitempty"`
I bool `xml:"i,attr"`
Kern int `xml:"kern,attr"`
Kumimoji bool `xml:"kumimoji,attr,omitempty"`
Lang string `xml:"lang,attr,omitempty"`
NoProof bool `xml:"noProof,attr,omitempty"`
NormalizeH bool `xml:"normalizeH,attr,omitempty"`
SmtClean bool `xml:"smtClean,attr,omitempty"`
SmtID uint64 `xml:"smtId,attr,omitempty"`
Spc int `xml:"spc,attr"`
Strike string `xml:"strike,attr,omitempty"`
Sz int `xml:"sz,attr,omitempty"`
U string `xml:"u,attr,omitempty"`
SolidFill *aSolidFill `xml:"a:solidFill"`
Latin *aLatin `xml:"a:latin"`
Ea *aEa `xml:"a:ea"`
Cs *aCs `xml:"a:cs"`
}
// cSpPr (Shape Properties) directly maps the c:spPr element. This element
// specifies the visual shape properties that can be applied to a shape. These
// properties include the shape fill, outline, geometry, effects, and 3D
// orientation.
type cSpPr struct {
NoFill *string `xml:"a:noFill"`
SolidFill *aSolidFill `xml:"a:solidFill"`
Ln *aLn `xml:"a:ln"`
Sp3D *aSp3D `xml:"a:sp3d"`
EffectLst *string `xml:"a:effectLst"`
}
// aSp3D (3-D Shape Properties) directly maps the a:sp3d element. This element
// defines the 3D properties associated with a particular shape in DrawingML.
// The 3D properties which can be applied to a shape are top and bottom bevels,
// a contour and an extrusion.
type aSp3D struct {
ContourW int `xml:"contourW,attr"`
ContourClr *aContourClr `xml:"a:contourClr"`
}
// aContourClr (Contour Color) directly maps the a:contourClr element. This
// element defines the color for the contour on a shape. The contour of a shape
// is a solid filled line which surrounds the outer edges of the shape.
type aContourClr struct {
SchemeClr *aSchemeClr `xml:"a:schemeClr"`
}
// aLn (Outline) directly maps the a:ln element. This element specifies an
// outline style that can be applied to a number of different objects such as
// shapes and text. The line allows for the specifying of many different types
// of outlines including even line dashes and bevels.
type aLn struct {
Algn string `xml:"algn,attr,omitempty"`
Cap string `xml:"cap,attr,omitempty"`
Cmpd string `xml:"cmpd,attr,omitempty"`
W int `xml:"w,attr,omitempty"`
NoFill string `xml:"a:noFill,omitempty"`
Round string `xml:"a:round,omitempty"`
SolidFill *aSolidFill `xml:"a:solidFill"`
}
// cTxPr (Text Properties) directly maps the c:txPr element. This element
// specifies text formatting. The lstStyle element is not supported.
type cTxPr struct {
BodyPr aBodyPr `xml:"a:bodyPr,omitempty"`
LstStyle string `xml:"a:lstStyle,omitempty"`
P aP `xml:"a:p,omitempty"`
}
// aEndParaRPr (End Paragraph Run Properties) directly maps the a:endParaRPr
// element. This element specifies the text run properties that are to be used
// if another run is inserted after the last run specified. This effectively
// saves the run property state so that it can be applied when the user enters
// additional text. If this element is omitted, then the application can
// determine which default properties to apply. It is recommended that this
// element be specified at the end of the list of text runs within the paragraph
// so that an orderly list is maintained.
type aEndParaRPr struct {
Lang string `xml:"lang,attr"`
AltLang string `xml:"altLang,attr,omitempty"`
Sz int `xml:"sz,attr,omitempty"`
}
// cAutoTitleDeleted (Auto Title Is Deleted) directly maps the
// c:autoTitleDeleted element. This element specifies the title shall not be
// shown for this chart.
type cAutoTitleDeleted struct {
Val bool `xml:"val,attr"`
}
// cView3D (View In 3D) directly maps the c:view3D element. This element
// specifies the 3-D view of the chart.
type cView3D struct {
RotX *attrValInt `xml:"c:rotX"`
RotY *attrValInt `xml:"c:rotY"`
DepthPercent *attrValInt `xml:"c:depthPercent"`
RAngAx *attrValInt `xml:"c:rAngAx"`
}
// cPlotArea directly maps the c:plotArea element. This element specifies the
// plot area of the chart.
type cPlotArea struct {
Layout *string `xml:"c:layout"`
AreaChart *cCharts `xml:"c:areaChart"`
Area3DChart *cCharts `xml:"c:area3DChart"`
BarChart *cCharts `xml:"c:barChart"`
Bar3DChart *cCharts `xml:"c:bar3DChart"`
DoughnutChart *cCharts `xml:"c:doughnutChart"`
LineChart *cCharts `xml:"c:lineChart"`
PieChart *cCharts `xml:"c:pieChart"`
Pie3DChart *cCharts `xml:"c:pie3DChart"`
RadarChart *cCharts `xml:"c:radarChart"`
ScatterChart *cCharts `xml:"c:scatterChart"`
CatAx []*cAxs `xml:"c:catAx"`
ValAx []*cAxs `xml:"c:valAx"`
SpPr *cSpPr `xml:"c:spPr"`
}
// cCharts specifies the common element of the chart.
type cCharts struct {
BarDir *attrValString `xml:"c:barDir"`
Grouping *attrValString `xml:"c:grouping"`
RadarStyle *attrValString `xml:"c:radarStyle"`
ScatterStyle *attrValString `xml:"c:scatterStyle"`
VaryColors *attrValBool `xml:"c:varyColors"`
Ser *[]cSer `xml:"c:ser"`
DLbls *cDLbls `xml:"c:dLbls"`
HoleSize *attrValInt `xml:"c:holeSize"`
Smooth *attrValBool `xml:"c:smooth"`
Overlap *attrValInt `xml:"c:overlap"`
AxID []*attrValInt `xml:"c:axId"`
}
// cAxs directly maps the c:catAx and c:valAx element.
type cAxs struct {
AxID *attrValInt `xml:"c:axId"`
Scaling *cScaling `xml:"c:scaling"`
Delete *attrValBool `xml:"c:delete"`
AxPos *attrValString `xml:"c:axPos"`
NumFmt *cNumFmt `xml:"c:numFmt"`
MajorTickMark *attrValString `xml:"c:majorTickMark"`
MinorTickMark *attrValString `xml:"c:minorTickMark"`
TickLblPos *attrValString `xml:"c:tickLblPos"`
SpPr *cSpPr `xml:"c:spPr"`
TxPr *cTxPr `xml:"c:txPr"`
CrossAx *attrValInt `xml:"c:crossAx"`
Crosses *attrValString `xml:"c:crosses"`
CrossBetween *attrValString `xml:"c:crossBetween"`
Auto *attrValBool `xml:"c:auto"`
LblAlgn *attrValString `xml:"c:lblAlgn"`
LblOffset *attrValInt `xml:"c:lblOffset"`
NoMultiLvlLbl *attrValBool `xml:"c:noMultiLvlLbl"`
}
// cScaling directly maps the c:scaling element. This element contains
// additional axis settings.
type cScaling struct {
Orientation *attrValString `xml:"c:orientation"`
Max *attrValFloat `xml:"c:max"`
Min *attrValFloat `xml:"c:min"`
}
// cNumFmt (Numbering Format) directly maps the c:numFmt element. This element
// specifies number formatting for the parent element.
type cNumFmt struct {
FormatCode string `xml:"formatCode,attr"`
SourceLinked bool `xml:"sourceLinked,attr"`
}
// cSer directly maps the c:ser element. This element specifies a series on a
// chart.
type cSer struct {
IDx *attrValInt `xml:"c:idx"`
Order *attrValInt `xml:"c:order"`
Tx *cTx `xml:"c:tx"`
SpPr *cSpPr `xml:"c:spPr"`
DPt []*cDPt `xml:"c:dPt"`
DLbls *cDLbls `xml:"c:dLbls"`
Marker *cMarker `xml:"c:marker"`
InvertIfNegative *attrValBool `xml:"c:invertIfNegative"`
Cat *cCat `xml:"c:cat"`
Val *cVal `xml:"c:val"`
XVal *cCat `xml:"c:xVal"`
YVal *cVal `xml:"c:yVal"`
Smooth *attrValBool `xml:"c:smooth"`
}
// cMarker (Marker) directly maps the c:marker element. This element specifies a
// data marker.
type cMarker struct {
Symbol *attrValString `xml:"c:symbol"`
Size *attrValInt `xml:"c:size"`
SpPr *cSpPr `xml:"c:spPr"`
}
// cDPt (Data Point) directly maps the c:dPt element. This element specifies a
// single data point.
type cDPt struct {
IDx *attrValInt `xml:"c:idx"`
Bubble3D *attrValBool `xml:"c:bubble3D"`
SpPr *cSpPr `xml:"c:spPr"`
}
// cCat (Category Axis Data) directly maps the c:cat element. This element
// specifies the data used for the category axis.
type cCat struct {
StrRef *cStrRef `xml:"c:strRef"`
}
// cStrRef (String Reference) directly maps the c:strRef element. This element
// specifies a reference to data for a single data label or title with a cache
// of the last values used.
type cStrRef struct {
F string `xml:"c:f"`
StrCache *cStrCache `xml:"c:strCache"`
}
// cStrCache (String Cache) directly maps the c:strCache element. This element
// specifies the last string data used for a chart.
type cStrCache struct {
Pt []*cPt `xml:"c:pt"`
PtCount *attrValInt `xml:"c:ptCount"`
}
// cPt directly maps the c:pt element. This element specifies data for a
// particular data point.
type cPt struct {
IDx int `xml:"idx,attr"`
V *string `xml:"c:v"`
}
// cVal directly maps the c:val element. This element specifies the data values
// which shall be used to define the location of data markers on a chart.
type cVal struct {
NumRef *cNumRef `xml:"c:numRef"`
}
// cNumRef directly maps the c:numRef element. This element specifies a
// reference to numeric data with a cache of the last values used.
type cNumRef struct {
F string `xml:"c:f"`
NumCache *cNumCache `xml:"c:numCache"`
}
// cNumCache directly maps the c:numCache element. This element specifies the
// last data shown on the chart for a series.
type cNumCache struct {
FormatCode string `xml:"c:formatCode"`
Pt []*cPt `xml:"c:pt"`
PtCount *attrValInt `xml:"c:ptCount"`
}
// cDLbls (Data Lables) directly maps the c:dLbls element. This element serves
// as a root element that specifies the settings for the data labels for an
// entire series or the entire chart. It contains child elements that specify
// the specific formatting and positioning settings.
type cDLbls struct {
ShowLegendKey *attrValBool `xml:"c:showLegendKey"`
ShowVal *attrValBool `xml:"c:showVal"`
ShowCatName *attrValBool `xml:"c:showCatName"`
ShowSerName *attrValBool `xml:"c:showSerName"`
ShowPercent *attrValBool `xml:"c:showPercent"`
ShowBubbleSize *attrValBool `xml:"c:showBubbleSize"`
ShowLeaderLines *attrValBool `xml:"c:showLeaderLines"`
}
// cLegend (Legend) directly maps the c:legend element. This element specifies
// the legend.
type cLegend struct {
Layout *string `xml:"c:layout"`
LegendPos *attrValString `xml:"c:legendPos"`
Overlay *attrValBool `xml:"c:overlay"`
SpPr *cSpPr `xml:"c:spPr"`
TxPr *cTxPr `xml:"c:txPr"`
}
// cPrintSettings directly maps the c:printSettings element. This element
// specifies the print settings for the chart.
type cPrintSettings struct {
HeaderFooter *string `xml:"c:headerFooter"`
PageMargins *cPageMargins `xml:"c:pageMargins"`
PageSetup *string `xml:"c:pageSetup"`
}
// cPageMargins directly maps the c:pageMargins element. This element specifies
// the page margins for a chart.
type cPageMargins struct {
B float64 `xml:"b,attr"`
Footer float64 `xml:"footer,attr"`
Header float64 `xml:"header,attr"`
L float64 `xml:"l,attr"`
R float64 `xml:"r,attr"`
T float64 `xml:"t,attr"`
}
// formatChartAxis directly maps the format settings of the chart axis.
type formatChartAxis struct {
Crossing string `json:"crossing"`
MajorTickMark string `json:"major_tick_mark"`
MinorTickMark string `json:"minor_tick_mark"`
MinorUnitType string `json:"minor_unit_type"`
MajorUnit int `json:"major_unit"`
MajorUnitType string `json:"major_unit_type"`
DisplayUnits string `json:"display_units"`
DisplayUnitsVisible bool `json:"display_units_visible"`
DateAxis bool `json:"date_axis"`
ReverseOrder bool `json:"reverse_order"`
Maximum float64 `json:"maximum"`
Minimum float64 `json:"minimum"`
NumFormat string `json:"num_format"`
NumFont struct {
Color string `json:"color"`
Bold bool `json:"bold"`
Italic bool `json:"italic"`
Underline bool `json:"underline"`
} `json:"num_font"`
NameLayout formatLayout `json:"name_layout"`
}
type formatChartDimension struct {
Width int `json:"width"`
Height int `json:"height"`
}
// formatChart directly maps the format settings of the chart.
type formatChart struct {
Type string `json:"type"`
Series []formatChartSeries `json:"series"`
Format formatPicture `json:"format"`
Dimension formatChartDimension `json:"dimension"`
Legend formatChartLegend `json:"legend"`
Title formatChartTitle `json:"title"`
XAxis formatChartAxis `json:"x_axis"`
YAxis formatChartAxis `json:"y_axis"`
Chartarea struct {
Border struct {
None bool `json:"none"`
} `json:"border"`
Fill struct {
Color string `json:"color"`
} `json:"fill"`
Pattern struct {
Pattern string `json:"pattern"`
FgColor string `json:"fg_color"`
BgColor string `json:"bg_color"`
} `json:"pattern"`
} `json:"chartarea"`
Plotarea struct {
ShowBubbleSize bool `json:"show_bubble_size"`
ShowCatName bool `json:"show_cat_name"`
ShowLeaderLines bool `json:"show_leader_lines"`
ShowPercent bool `json:"show_percent"`
ShowSerName bool `json:"show_series_name"`
ShowVal bool `json:"show_val"`
Gradient struct {
Colors []string `json:"colors"`
} `json:"gradient"`
Border struct {
Color string `json:"color"`
Width int `json:"width"`
DashType string `json:"dash_type"`
} `json:"border"`
Fill struct {
Color string `json:"color"`
} `json:"fill"`
Layout formatLayout `json:"layout"`
} `json:"plotarea"`
ShowBlanksAs string `json:"show_blanks_as"`
ShowHiddenData bool `json:"show_hidden_data"`
SetRotation int `json:"set_rotation"`
SetHoleSize int `json:"set_hole_size"`
}
// formatChartLegend directly maps the format settings of the chart legend.
type formatChartLegend struct {
None bool `json:"none"`
DeleteSeries []int `json:"delete_series"`
Font formatFont `json:"font"`
Layout formatLayout `json:"layout"`
Position string `json:"position"`
ShowLegendEntry bool `json:"show_legend_entry"`
ShowLegendKey bool `json:"show_legend_key"`
}
// formatChartSeries directly maps the format settings of the chart series.
type formatChartSeries struct {
Name string `json:"name"`
Categories string `json:"categories"`
Values string `json:"values"`
Line struct {
None bool `json:"none"`
Color string `json:"color"`
} `json:"line"`
Marker struct {
Type string `json:"type"`
Size int `json:"size"`
Width float64 `json:"width"`
Border struct {
Color string `json:"color"`
None bool `json:"none"`
} `json:"border"`
Fill struct {
Color string `json:"color"`
None bool `json:"none"`
} `json:"fill"`
} `json:"marker"`
}
// formatChartTitle directly maps the format settings of the chart title.
type formatChartTitle struct {
None bool `json:"none"`
Name string `json:"name"`
Overlay bool `json:"overlay"`
Layout formatLayout `json:"layout"`
}
// formatLayout directly maps the format settings of the element layout.
type formatLayout struct {
X float64 `json:"x"`
Y float64 `json:"y"`
Width float64 `json:"width"`
Height float64 `json:"height"`
}

View File

@ -1,72 +0,0 @@
// Copyright 2016 - 2019 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"
// xlsxComments directly maps the comments element from the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main. A comment is a
// rich text note that is attached to and associated with a cell, separate from
// other cell content. Comment content is stored separate from the cell, and is
// displayed in a drawing object (like a text box) that is separate from, but
// associated with, a cell. Comments are used as reminders, such as noting how a
// complex formula works, or to provide feedback to other users. Comments can
// also be used to explain assumptions made in a formula or to call out
// something special about the cell.
type xlsxComments struct {
XMLName xml.Name `xml:"http://schemas.openxmlformats.org/spreadsheetml/2006/main comments"`
Authors []xlsxAuthor `xml:"authors"`
CommentList xlsxCommentList `xml:"commentList"`
}
// xlsxAuthor directly maps the author element. This element holds a string
// representing the name of a single author of comments. Every comment shall
// have an author. The maximum length of the author string is an implementation
// detail, but a good guideline is 255 chars.
type xlsxAuthor struct {
Author string `xml:"author"`
}
// xlsxCommentList (List of Comments) directly maps the xlsxCommentList element.
// This element is a container that holds a list of comments for the sheet.
type xlsxCommentList struct {
Comment []xlsxComment `xml:"comment"`
}
// xlsxComment directly maps the comment element. This element represents a
// single user entered comment. Each comment shall have an author and can
// optionally contain richly formatted text.
type xlsxComment struct {
Ref string `xml:"ref,attr"`
AuthorID int `xml:"authorId,attr"`
Text xlsxText `xml:"text"`
}
// xlsxText directly maps the text element. This element contains rich text
// which represents the text of a comment. The maximum length for this text is a
// spreadsheet application implementation detail. A recommended guideline is
// 32767 chars.
type xlsxText struct {
R []xlsxR `xml:"r"`
}
// formatComment directly maps the format settings of the comment.
type formatComment struct {
Author string `json:"author"`
Text string `json:"text"`
}
// Comment directly maps the comment information.
type Comment struct {
Author string `json:"author"`
AuthorID int `json:"author_id"`
Ref string `json:"ref"`
Text string `json:"text"`
}

Some files were not shown because too many files have changed in this diff Show More