Compare commits

...

146 Commits

Author SHA1 Message Date
hoteas
541c82410e 修正bug 2022-10-21 04:28:51 +08:00
hoteas
b680112fdb 修正bug 2022-10-20 15:49:49 +08:00
hoteas
4ab5ab9ff4 时间由指针改回对象 2022-10-20 09:08:23 +08:00
hoteas
b425024359 升级流程引擎配置文件版本 2022-10-20 09:00:44 +08:00
hoteas
78337c14ec 升级流程引擎配置文件版本 2022-10-19 21:32:34 +08:00
hoteas
cdba8af129 升级流程引擎配置文件版本 2022-10-19 21:29:38 +08:00
hoteas
9a7426180d 增加单表某字段权限及类型控制功能 2022-10-19 03:37:52 +08:00
hoteas
b7131603c4 增加备注功能 2022-10-08 17:32:37 +08:00
hoteas
2f3a5a0a59 增加壁纸及壁纸地址缓存 2022-10-08 16:52:42 +08:00
hoteas
c2468a7389 增加两个参数 2022-09-16 07:10:45 +08:00
hoteas
b6ba3486d6 IP获取真实条件修改 2022-09-02 00:04:23 +08:00
hoteas
f59e909d30 修复下载插件bug 2022-08-31 19:15:47 +08:00
hoteas
3bb47de45a 修复下载插件bug 2022-08-31 19:10:41 +08:00
hoteas
c71973850e 修复下载插件bug 2022-08-31 19:10:08 +08:00
hoteas
65f062b860 数据库操作bug 2022-08-31 11:20:58 +08:00
hoteas
7b502fed36 数据库操作bug 2022-08-31 11:14:45 +08:00
hoteas
fd6b15bdaf 修正查询bug 2022-08-30 06:21:46 +08:00
hoteas
f31bf24ec2 增加mongodb驱动,简单版本 2022-08-30 04:44:37 +08:00
hoteas
30edb4d9fa 增加mongodb驱动,简单版本 2022-08-30 04:05:17 +08:00
hoteas
a32c3a1589 增加mongodb驱动,简单版本 2022-08-30 03:30:27 +08:00
hoteas
127e027940 修复重复执行context.View()的bug 2022-08-25 14:06:31 +08:00
hoteas
2ee0838d8a 树状结构优化 2022-08-25 13:06:26 +08:00
hoteas
72c23499f2 树状结构优化 2022-08-25 13:02:44 +08:00
hoteas
96d8868694 数据库错误操作优化 2022-08-25 05:01:50 +08:00
hoteas
1533a57cb8 数据库错误操作优化 2022-08-25 03:48:09 +08:00
hoteas
615f52d2e4 数据库错误操作优化 2022-08-25 03:44:58 +08:00
hoteas
f7dfd4ec77 增加记录IP 2022-08-21 03:49:56 +08:00
hoteas
2276aa12ef Merge remote-tracking branch 'origin/master' 2022-08-20 22:38:40 +08:00
hoteas
6505594fd0 增加记录IP 2022-08-20 22:38:15 +08:00
hoteas
c55e26021b 数据库错误操作优化 2022-08-20 11:20:03 +08:00
hoteas
78420a692f 检索升级 2022-08-19 17:58:18 +08:00
hoteas
6d9af149ad 数据库错误操作优化 2022-08-18 13:40:02 +08:00
hoteas
253cad35ef 数据库错误操作优化 2022-08-18 13:28:02 +08:00
hoteas
47c8736f34 数据库错误操作优化 2022-08-18 12:33:01 +08:00
hoteas
dcce8ace9e 数据库事务操作优化 2022-08-18 11:36:23 +08:00
hoteas
125ccc5c3b 数据库操作优化 2022-08-17 17:10:12 +08:00
hoteas
432d59d483 数据库操作优化 2022-08-17 16:42:46 +08:00
hoteas
60f222b011 数据库操作优化 2022-08-17 16:35:52 +08:00
hoteas
7a8b86ed12 数据库操作优化,优化系统管理后台代码生成逻辑 2022-08-17 16:02:36 +08:00
hoteas
b940afa6b0 数据库操作优化 2022-08-15 05:59:06 +08:00
hoteas
8afd00ff86 修复登录bug 2022-08-11 10:41:35 +08:00
hoteas
8992fd6d3a 解决BUG 2022-08-11 10:18:48 +08:00
hoteas
524a892480 修复bug 2022-08-08 04:34:26 +08:00
hoteas
c420e23edb 修复bug 2022-08-08 02:37:15 +08:00
hoteas
7419e03d67 解决bug 2022-08-04 12:14:18 +08:00
hoteas
9425544d1c 修复bug 2022-08-04 02:41:41 +08:00
hoteas
a8d78832df 修复配置bug 2022-08-03 12:07:55 +08:00
hoteas
adfb2236dc V2.0封测 2022-08-02 03:02:57 +08:00
hoteas
6034598bb4 权限管理优化 2022-08-01 18:48:08 +08:00
hoteas
6fe44cb1cb 权限管理优化 2022-08-01 16:45:24 +08:00
hoteas
39d67d1775 增加导出功能 2022-08-01 03:40:09 +08:00
hoteas
a8f9f12bb8 大岗山水电站初版完成 2022-07-28 12:08:47 +08:00
hoteas
2c1abb1d11 大岗山水电站初版完成 2022-07-28 11:08:51 +08:00
hoteas
21e0219568 V2半封测 2022-07-27 17:09:56 +08:00
hoteas
952c3a1243 技术性调整 2022-07-26 17:37:17 +08:00
hoteas
33cd7ebd6b 技术性调整 2022-07-25 05:44:38 +08:00
hoteas
be02b3418d 技术性调整 2022-07-25 05:37:19 +08:00
hoteas
f390617167 技术性调整 2022-07-24 00:00:36 +08:00
hoteas
f7410200e3 增加权限管理 2022-07-21 00:24:39 +08:00
hoteas
9cfdfbac78 增加权限管理 2022-07-18 19:45:06 +08:00
hoteas
b015e78fa0 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	example/config/configNote.json
#	var.go
2022-07-18 19:44:52 +08:00
hoteas
bb9092c3e5 增加权限管理 2022-07-18 19:44:00 +08:00
hoteas
cc1bad8d3f 技术性调整 2022-07-18 08:46:09 +08:00
hoteas
8f7380d796 优化日志及config 2022-07-11 19:13:20 +08:00
hoteas
f37b9aee70 优化日志及config 2022-07-11 11:07:17 +08:00
hoteas
1ab9027c93 技术性调整 2022-07-08 09:55:02 +08:00
hoteas
96d341aaab 修复数据库及时间bug 2022-06-21 00:06:34 +08:00
hoteas
1f25f511cc 增加mysql断线重连优化 2022-06-14 11:29:54 +08:00
hoteas
07c7a628d1 增加time兼容性 2022-06-14 09:52:49 +08:00
hoteas
d7a59845eb 接口层复用 2022-06-09 04:05:50 +08:00
hoteas
98619083a1 接口层复用 2022-06-09 03:54:33 +08:00
hoteas
c8a9038efe 数据库where增加[##]操作 2022-05-27 15:00:44 +08:00
hoteas
b638d8bd65 增加vendor 2022-05-24 13:49:25 +08:00
hoteas
77753a123f 删除example代码 2022-05-19 15:45:51 +08:00
2c9d475a45 导出功能修改关联salesman关联关系 2022-05-18 17:52:49 +08:00
3540209b26 科创券优化 2022-05-17 12:31:47 +08:00
797681d76c 添source_type字段(券的来源:1-vip获得,2-认证获得,3-拉新获得),用来判断券的来源,
userinfo接口返回企业统一社会信用代码和营业执照路径
2022-05-13 18:43:35 +08:00
0ec83f9a95 科服券列表+领券,企业认证,购买vip领券 2022-05-13 15:50:45 +08:00
ec798bd624 科服券列表+领券,企业认证,购买vip领券 2022-05-13 15:45:50 +08:00
6b57201e59 Merge branch 'zct-v2-dengluyang' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-13 15:34:53 +08:00
4e35dfe6ed 科服券列表+领券,企业认证,购买vip领券 2022-05-13 15:34:15 +08:00
hoteas
970bdb0157 增加time类型直接转换 2022-05-13 15:31:55 +08:00
d656faf915 Merge branch 'zct-v2-dengluyang' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-13 09:36:46 +08:00
hoteas
2ecc70288e 打印影响延迟优化 2022-05-13 09:30:09 +08:00
hoteas
ce95cdc021 打印影响延迟优化 2022-05-12 18:27:01 +08:00
22130c7afe vip当日购买信息导出excel的sql调整,添加新字段:用户关联parentid时间,用户关联salesmanid时间 2022-05-11 18:19:30 +08:00
d85c65faef Merge branch 'zct-v2-dengluyang' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-11 18:17:40 +08:00
hoteas
c9f33eefec 打印影响延迟优化 2022-05-11 14:55:28 +08:00
hoteas
1826e76a34 打印影响延迟优化 2022-05-11 13:56:53 +08:00
b9a6b7af22 Merge branch 'zct-v2-dengluyang' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-11 09:51:35 +08:00
hoteas
95bfea4feb 对政策匹配进行优化 2022-05-11 00:44:52 +08:00
e4bb8ac94a vip当日购买信息导出excel 2022-05-10 19:47:20 +08:00
d7a49bf56d vip当日购买信息导出excel 2022-05-10 19:45:00 +08:00
3d1a1670cc Merge branch 'zct-v2-dengluyang' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-10 19:43:36 +08:00
hoteas
7de6a79611 对政策匹配进行优化 2022-05-10 12:54:24 +08:00
83198b39cb Merge branch 'zct-v2-dengluyang' of https://code.hoteas.com/golang/hotime into zhoupengwei
 Conflicts:
	example/app/declare.go
	example/provider/company.go
2022-05-10 09:43:03 +08:00
hoteas
db0724f09b 对政策匹配进行优化 2022-05-09 19:19:15 +08:00
hoteas
c1b013c926 对政策匹配进行优化 2022-05-09 15:07:01 +08:00
40bc84ea3d Merge branch 'zct-v2' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-07 20:56:36 +08:00
e977a97013 Merge pull request '修复 bug 客户管理领域信息没存起来,高层次人才单选的形式存储的' (#1) from liyun into zct-v2
Reviewed-on: golang/hotime#1
2022-05-07 12:55:28 +00:00
michael
9330f7f5ea 修复 bug 客户管理领域信息没存起来,高层次人才单选的形式存储的 2022-05-07 20:47:58 +08:00
d20bcc162c Merge branch 'zct-v2' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-07 17:11:27 +08:00
hoteas
b48ad793da 修正企服商那边不显示名称问题 2022-05-07 13:55:57 +08:00
hoteas
3754734130 临时增加state为1企服商列表不显示企业 2022-05-07 11:08:11 +08:00
hoteas
918b88332b 增加限制条件 2022-05-07 11:02:12 +08:00
hoteas
9ba182d65c 增加限制条件 2022-05-06 13:08:13 +08:00
hoteas
8cf54ce25b 增加限制条件 2022-05-06 11:35:40 +08:00
hoteas
22d00739ff 增加join的orm兼容性 2022-05-05 18:33:27 +08:00
hoteas
3b2a317d2b 增加U盘登录 2022-05-05 16:07:01 +08:00
afa9b173ba Merge branch 'zct-v2' of https://code.hoteas.com/golang/hotime into zhoupengwei 2022-05-05 10:44:10 +08:00
hoteas
53f24c033c 初步版本修正 2022-05-05 00:29:30 +08:00
1ffcaaef8e 只在main.go中加了双//,测试是否能够提交成功 2022-05-04 21:50:52 +08:00
hoteas
62ba00270a 调优 2022-05-03 22:40:02 +08:00
hoteas
fe31335cf5 验证数据 2022-05-03 15:17:27 +08:00
hoteas
b709b58fef 基础整理 2022-05-03 09:41:18 +08:00
hoteas
76b220aa5d 基础整理 2022-05-03 08:09:25 +08:00
hoteas
dbf8f91696 基础整理 2022-05-02 15:42:54 +08:00
hoteas
335e8730da 用户登录 2022-05-02 15:39:50 +08:00
hoteas
cbed318832 科创地图打包 2022-04-29 17:58:14 +08:00
hoteas
31a6568cbe 科创地图打包 2022-04-29 03:08:32 +08:00
hoteas
2aa86361e1 增加普通时间类型,以及增加富文本类型 2022-04-28 14:44:56 +08:00
hoteas
2a21dad90a Merge branch 'zct-wechat' into zct-manage
# Conflicts:
#	example/config/config.json
#	example/main.go
#	example/zct_manage.exe
2022-04-26 09:24:51 +08:00
hoteas
bae9f60012 增加普通时间类型,以及增加富文本类型 2022-04-25 20:08:16 +08:00
hoteas
79d1189803 增加普通时间类型,以及增加富文本类型 2022-04-25 19:58:49 +08:00
hoteas
c3d0c8921b 系统优化 2022-04-22 15:48:17 +08:00
hoteas
1da98a058b 系统优化 2022-04-21 02:20:37 +08:00
hoteas
152386c5a0 系统优化 2022-04-21 02:20:27 +08:00
hoteas
5e2845d3a1 系统优化 2022-04-20 22:49:07 +08:00
hoteas
bab49c9a66 系统优化 2022-04-20 22:47:58 +08:00
hoteas
1d3bfcaee5 系统优化 2022-04-20 18:36:05 +08:00
hoteas
a37a33321f 系统优化 2022-04-18 06:28:01 +08:00
48042ecce4 系统优化 2022-03-29 05:31:02 +08:00
5d8227d8bb 初步完成 2022-03-28 04:52:10 +08:00
38d3d77c59 初步完成 2022-03-28 01:14:09 +08:00
fec195b3a1 框架优化 2022-03-26 16:53:40 +08:00
hoteas
5945ed64c6 框架优化 2022-03-16 09:58:24 +08:00
hoteas
ce515d991a 框架优化 2022-03-14 16:48:19 +08:00
hoteas
cb04dc6c34 框架优化 2022-03-13 17:02:19 +08:00
hoteas
17905c2d21 框架优化 2022-03-13 05:13:32 +08:00
hoteas
b7c243823a 框架优化 2022-03-13 05:06:28 +08:00
hoteas
ebea14c74f Merge remote-tracking branch 'origin/master' into rfcb
# Conflicts:
#	code.go
2022-03-13 02:16:31 +08:00
hoteas
d6ef790010 优化整体 2022-03-13 02:00:40 +08:00
hoteas
5c64580378 优化整体 2022-03-13 01:48:54 +08:00
hoteas
e49164fa81 使用go mod 2022-03-13 01:12:29 +08:00
hoteas
8265e24add 使用go mod 2022-03-13 01:00:59 +08:00
hoteas
2e65138222 hotimego V1.0.1 2022-03-12 23:57:48 +08:00
1288 changed files with 670331 additions and 1060 deletions

3
.gitignore vendored
View File

@ -1,3 +1,4 @@
/.idea/*
.idea
/example/config/app.json
/example/config/app.json
/example/tpt/demo/

0
.tgitconfig Normal file
View File

22
LICENSE
View File

@ -7,17 +7,17 @@ AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution
as defined by Sections 1 through 9 of that document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
@ -26,31 +26,31 @@ or indirect, to cause the direction or management of such entity, whether
by contract or otherwise, or (ii) ownership of fifty percent (50%) or more
of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions
granted by that License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation
or translation of a Source form, including but not limited to compiled object
code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form,
made available under the License, as indicated by a copyright notice that
is included in or attached to the work (an example is provided in the Appendix
below).
"Derivative Works" shall mean any work, whether in Source or Object form,
that is based on (or derived from) the Work and for which the editorial revisions,
@ -59,7 +59,7 @@ original work of authorship. For the purposes of that License, Derivative
Works shall not include works that remain separable from, or merely link (or
bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative
@ -74,7 +74,7 @@ for the purpose of discussing and improving the Work, but excluding communicatio
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently incorporated
@ -142,7 +142,7 @@ any additional terms or conditions. Notwithstanding the above, nothing herein
shall supersede or modify the terms of any separate license agreement you
may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names,
6. Trademarks. that License does not grant permission to use the trade names,
trademarks, service marks, or product names of the Licensor, except as required
for reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.

View File

@ -1,14 +1,14 @@
package hotime
import (
. "./cache"
"./code"
. "./common"
. "./db"
. "./log"
. "code.hoteas.com/golang/hotime/cache"
"code.hoteas.com/golang/hotime/code"
. "code.hoteas.com/golang/hotime/common"
. "code.hoteas.com/golang/hotime/db"
. "code.hoteas.com/golang/hotime/log"
"database/sql"
"fmt"
"github.com/sirupsen/logrus"
"io"
"io/ioutil"
"net/http"
"net/url"
@ -20,17 +20,15 @@ import (
)
type Application struct {
*code.MakeCode
MakeCodeRouter Router
MakeCodeRouter map[string]*code.MakeCode
MethodRouter
Router
ContextBase
Error
Log *logrus.Logger
WebConnectLog *logrus.Logger
Port string //端口号
TLSPort string //ssl访问端口号
connectListener []func(this *Context) bool //所有的访问监听,true按原计划继续使用false表示有监听器处理
connectListener []func(that *Context) bool //所有的访问监听,true按原计划继续使用false表示有监听器处理
connectDbFunc func(err ...*Error) (master, slave *sql.DB)
configPath string
Config Map
@ -71,7 +69,21 @@ func (that *Application) Run(router Router) {
that.Router = Router{}
}
for k, v := range router {
that.Router[k] = v
if that.Router[k] == nil {
that.Router[k] = v
}
//直达接口层复用
for k1, v1 := range v {
if that.Router[k][k1] == nil {
that.Router[k][k1] = v1
}
for k2, v2 := range v1 {
that.Router[k][k1][k2] = v2
}
}
}
//重新设置MethodRouter//直达路由
that.MethodRouter = MethodRouter{}
@ -225,10 +237,8 @@ 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)
if that.Error.GetError() != nil {
fmt.Println(that.Error.GetError().Error())
}
//文件如果损坏则不写入配置防止配置文件数据丢失
@ -255,15 +265,21 @@ 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 连接判断,返回true继续传输至控制层false则停止传输
func (that *Application) SetConnectListener(lis func(this *Context) bool) {
// SetConnectListener 连接判断,返回false继续传输至控制层true则停止传输
func (that *Application) SetConnectListener(lis func(that *Context) (isFinished bool)) {
that.connectListener = append(that.connectListener, lis)
}
//网络错误
//func (this *Application) session(w http.ResponseWriter, req *http.Request) {
//func (that *Application) session(w http.ResponseWriter, req *http.Request) {
//
//}
@ -341,14 +357,18 @@ 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, ":"))
//负载均衡优化
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")
}
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, ":"))
}
that.WebConnectLog.Infoln(ipStr, context.Req.Method,
@ -358,16 +378,17 @@ func (that *Application) handler(w http.ResponseWriter, req *http.Request) {
}()
//访问拦截true继续false暂停
connectListenerLen := len(that.connectListener)
if connectListenerLen != 0 {
for i := 0; i < connectListenerLen; i++ {
connectListenerLen := len(that.connectListener) - 1
if !that.connectListener[i](&context) {
context.View()
return
}
for true {
if connectListenerLen < 0 {
break
}
if that.connectListener[connectListenerLen](&context) {
context.View()
return
}
connectListenerLen--
}
//接口服务
@ -526,45 +547,59 @@ func (that *Application) crossDomain(context *Context, sessionId string) {
}
//Init 初始化application
func Init(config string) Application {
func Init(config string) *Application {
appIns := Application{}
//手动模式,
appIns.SetConfig(config)
SetDB(&appIns)
appIns.SetCache()
appIns.MakeCode = &code.MakeCode{}
codeConfig := appIns.Config.GetMap("codeConfig")
appIns.MakeCodeRouter = Router{}
codeConfig := appIns.Config.GetSlice("codeConfig")
if codeConfig != nil {
for k, _ := range codeConfig {
if appIns.Config.GetInt("mode") == 2 {
appIns.MakeCode.Db2JSON(k, codeConfig.GetString(k), &appIns.Db, true)
appIns.MakeCodeRouter[k] = Proj{}
} else if appIns.Config.GetInt("mode") == 3 {
appIns.MakeCode.Db2JSON(k, codeConfig.GetString(k), &appIns.Db, false)
appIns.MakeCodeRouter[k] = Proj{}
} else {
appIns.MakeCode.Db2JSON(k, codeConfig.GetString(k), nil, false)
appIns.MakeCodeRouter[k] = Proj{}
codeMake := codeConfig.GetMap(k)
if codeMake == nil {
continue
}
//codeMake["table"] = k
if appIns.MakeCodeRouter == nil {
appIns.MakeCodeRouter = map[string]*code.MakeCode{}
}
if codeMake.GetString("name") == "" {
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.Router == nil {
appIns.Router = Router{}
}
appIns.Router[k] = TptProject
for k1, _ := range appIns.MakeCode.TableColumns {
appIns.Router[k][k1] = appIns.Router[k]["hotimeCommon"]
//appIns.Router[codeMake.GetString("name")] = TptProject
appIns.Router[codeMake.GetString("name")] = Proj{}
for k2, _ := range TptProject {
appIns.Router[codeMake.GetString("name")][k2] = Ctr{}
for k3, v3 := range TptProject[k2] {
appIns.Router[codeMake.GetString("name")][k2][k3] = v3
}
}
setMakeCodeLintener(k, &appIns)
for k1, _ := range appIns.MakeCodeRouter[codeMake.GetString("name")].TableColumns {
appIns.Router[codeMake.GetString("name")][k1] = appIns.Router[codeMake.GetString("name")]["hotimeCommon"]
}
setMakeCodeListener(codeMake.GetString("name"), &appIns)
}
}
return appIns
return &appIns
}
// SetDB 智能数据库设置
@ -584,6 +619,8 @@ func SetMysqlDB(appIns *Application, config Map) {
appIns.Db.Type = "mysql"
appIns.Db.DBName = config.GetString("name")
appIns.Db.Prefix = config.GetString("prefix")
appIns.Db.Log = appIns.Log
appIns.Db.Mode = appIns.Config.GetCeilInt("mode")
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
//master数据库配置
query := config.GetString("user") + ":" + config.GetString("password") +
@ -613,6 +650,8 @@ func SetSqliteDB(appIns *Application, config Map) {
appIns.Db.Type = "sqlite"
appIns.Db.Prefix = config.GetString("prefix")
appIns.Db.Mode = appIns.Config.GetCeilInt("mode")
appIns.Db.Log = appIns.Log
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
db, e := sql.Open("sqlite3", config.GetString("path"))
if e != nil && len(err) != 0 {
@ -624,84 +663,56 @@ func SetSqliteDB(appIns *Application, config Map) {
})
}
func setMakeCodeLintener(name string, appIns *Application) {
appIns.SetConnectListener(func(context *Context) bool {
func setMakeCodeListener(name string, appIns *Application) {
appIns.SetConnectListener(func(context *Context) (isFinished bool) {
codeIns := appIns.MakeCodeRouter[name]
if len(context.RouterString) < 2 || appIns.MakeCodeRouter[context.RouterString[0]] == nil {
return true
return isFinished
}
if len(context.RouterString) > 1 && context.RouterString[0] == name {
if context.RouterString[1] == "hotime" && context.RouterString[2] == "login" {
return true
return isFinished
}
if context.RouterString[1] == "hotime" && context.RouterString[2] == "logout" {
return isFinished
}
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
}
if context.Session(name+"_id").Data == nil {
context.Display(2, "你还没有登录")
return false
}
}
//文件上传接口
if len(context.RouterString) == 1 && context.RouterString[0] == "file" && context.Req.Method == "POST" {
if context.Session(name+"_id").Data == nil {
context.Display(2, "你还没有登录")
return false
}
//读取网络文件
fi, fheader, err := context.Req.FormFile("file")
if err != nil {
context.Display(3, err)
return false
}
filePath := context.Config.GetString("filePath")
if filePath == "" {
filePath = "file/2006/01/02/"
}
path := time.Now().Format(filePath)
e := os.MkdirAll(context.Config.GetString("tpt")+"/"+path, os.ModeDir)
if e != nil {
context.Display(3, e)
return false
}
filePath = path + Md5(ObjToStr(RandX(100000, 9999999))) + fheader.Filename[strings.LastIndex(fheader.Filename, "."):]
newFile, e := os.Create(context.Config.GetString("tpt") + "/" + filePath)
if e != nil {
context.Display(3, e)
return false
}
_, e = io.Copy(newFile, fi)
if e != nil {
context.Display(3, e)
return false
}
context.Display(0, filePath)
return false
}
if len(context.RouterString) < 2 || len(context.RouterString) > 3 ||
!(context.Router[context.RouterString[0]] != nil &&
context.Router[context.RouterString[0]][context.RouterString[1]] != nil) {
return true
return isFinished
}
//排除无效操作
if len(context.RouterString) == 2 &&
context.Req.Method != "GET" &&
context.Req.Method != "POST" {
return true
return isFinished
}
//排除已有接口的无效操作
if len(context.RouterString) == 3 && context.Router[context.RouterString[0]] != nil && context.Router[context.RouterString[0]][context.RouterString[1]] != nil && context.Router[context.RouterString[0]][context.RouterString[1]][context.RouterString[2]] != nil {
return isFinished
}
//列表检索
if len(context.RouterString) == 2 &&
context.Req.Method == "GET" {
if context.Router[context.RouterString[0]][context.RouterString[1]]["search"] == nil {
return true
return isFinished
}
context.Router[context.RouterString[0]][context.RouterString[1]]["search"](context)
}
@ -715,14 +726,14 @@ func setMakeCodeLintener(name string, appIns *Application) {
}
if len(context.RouterString) == 3 &&
context.Req.Method == "POST" {
return true
return isFinished
}
//查询单条
if len(context.RouterString) == 3 &&
context.Req.Method == "GET" {
if context.Router[context.RouterString[0]][context.RouterString[1]]["info"] == nil {
return true
return isFinished
}
context.Router[context.RouterString[0]][context.RouterString[1]]["info"](context)
@ -747,7 +758,8 @@ func setMakeCodeLintener(name string, appIns *Application) {
context.Router[context.RouterString[0]][context.RouterString[1]]["remove"](context)
}
context.View()
return false
//context.View()
return true
})
}

2
cache/cache.go vendored
View File

@ -1,7 +1,7 @@
package cache
import (
. "../common"
. "code.hoteas.com/golang/hotime/common"
"errors"
)

28
cache/cache_db.go vendored
View File

@ -1,7 +1,7 @@
package cache
import (
. "../common"
. "code.hoteas.com/golang/hotime/common"
"database/sql"
"encoding/json"
"strings"
@ -30,14 +30,14 @@ type CacheDb struct {
isInit bool
}
func (this *CacheDb) GetError() *Error {
func (that *CacheDb) GetError() *Error {
return this.Error
return that.Error
}
func (this *CacheDb) SetError(err *Error) {
this.Error = err
func (that *CacheDb) SetError(err *Error) {
that.Error = err
}
func (that *CacheDb) initDbTable() {
@ -58,7 +58,7 @@ func (that *CacheDb) initDbTable() {
return
}
_, e := that.Db.Exec("CREATE TABLE `" + that.Db.GetPrefix() + "cached` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `ckey` varchar(60) DEFAULT NULL, `cvalue` varchar(2000) DEFAULT NULL, `time` bigint(20) DEFAULT NULL, `endtime` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=198740 DEFAULT CHARSET=utf8")
_, e := that.Db.Exec("CREATE TABLE `" + that.Db.GetPrefix() + "cached` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `key` varchar(60) DEFAULT NULL, `value` varchar(2000) DEFAULT NULL, `time` bigint(20) DEFAULT NULL, `endtime` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=198740 DEFAULT CHARSET=utf8")
if e.GetError() == nil {
that.isInit = true
}
@ -74,8 +74,8 @@ func (that *CacheDb) initDbTable() {
}
_, e := that.Db.Exec(`CREATE TABLE "` + that.Db.GetPrefix() + `cached" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"ckey" TEXT(60),
"cvalue" TEXT(2000),
"key" TEXT(60),
"value" TEXT(2000),
"time" integer,
"endtime" integer
);`)
@ -90,7 +90,7 @@ func (that *CacheDb) initDbTable() {
//获取Cache键只能为string类型
func (that *CacheDb) get(key string) interface{} {
cached := that.Db.Get("cached", "*", Map{"ckey": key})
cached := that.Db.Get("cached", "*", Map{"key": key})
if cached == nil {
return nil
@ -103,7 +103,7 @@ func (that *CacheDb) get(key string) interface{} {
}
data := Map{}
data.JsonToMap(cached.GetString("cvalue"))
data.JsonToMap(cached.GetString("value"))
return data.Get("data")
}
@ -113,9 +113,9 @@ func (that *CacheDb) set(key string, value interface{}, tim int64) {
bte, _ := json.Marshal(Map{"data": value})
num := that.Db.Update("cached", Map{"cvalue": string(bte), "time": time.Now().UnixNano(), "endtime": tim}, Map{"ckey": key})
num := that.Db.Update("cached", Map{"value": string(bte), "time": time.Now().UnixNano(), "endtime": tim}, Map{"key": key})
if num == int64(0) {
that.Db.Insert("cached", Map{"cvalue": string(bte), "time": time.Now().UnixNano(), "endtime": tim, "ckey": key})
that.Db.Insert("cached", Map{"value": string(bte), "time": time.Now().UnixNano(), "endtime": tim, "key": key})
}
//随机执行删除命令
@ -130,10 +130,10 @@ func (that *CacheDb) delete(key string) {
//如果通配删除
if del != -1 {
key = Substr(key, 0, del)
that.Db.Delete("cached", Map{"ckey": key + "%"})
that.Db.Delete("cached", Map{"key": key + "%"})
} else {
that.Db.Delete("cached", Map{"ckey": key})
that.Db.Delete("cached", Map{"key": key})
}
}

90
cache/cache_memory.go vendored
View File

@ -1,7 +1,7 @@
package cache
import (
. "../common"
. "code.hoteas.com/golang/hotime/common"
"strings"
"sync"
"time"
@ -17,47 +17,47 @@ type CacheMemory struct {
mutex *sync.RWMutex
}
func (this *CacheMemory) GetError() *Error {
func (that *CacheMemory) GetError() *Error {
return this.Error
return that.Error
}
func (this *CacheMemory) SetError(err *Error) {
this.Error = err
func (that *CacheMemory) SetError(err *Error) {
that.Error = err
}
//获取Cache键只能为string类型
func (this *CacheMemory) get(key string) interface{} {
this.Error.SetError(nil)
if this.Map == nil {
this.Map = Map{}
func (that *CacheMemory) get(key string) interface{} {
that.Error.SetError(nil)
if that.Map == nil {
that.Map = Map{}
}
if this.Map[key] == nil {
if that.Map[key] == nil {
return nil
}
data := this.Map.Get(key, this.Error).(cacheData)
if this.Error.GetError() != nil {
data := that.Map.Get(key, that.Error).(cacheData)
if that.Error.GetError() != nil {
return nil
}
if data.time < time.Now().Unix() {
delete(this.Map, key)
delete(that.Map, key)
return nil
}
return data.data
}
func (this *CacheMemory) refreshMap() {
func (that *CacheMemory) refreshMap() {
go func() {
this.mutex.Lock()
defer this.mutex.Unlock()
for key, v := range this.Map {
that.mutex.Lock()
defer that.mutex.Unlock()
for key, v := range that.Map {
data := v.(cacheData)
if data.time <= time.Now().Unix() {
delete(this.Map, key)
delete(that.Map, key)
}
}
@ -66,15 +66,15 @@ func (this *CacheMemory) refreshMap() {
}
//key value ,时间为时间戳
func (this *CacheMemory) set(key string, value interface{}, time int64) {
this.Error.SetError(nil)
func (that *CacheMemory) set(key string, value interface{}, time int64) {
that.Error.SetError(nil)
var data cacheData
if this.Map == nil {
this.Map = Map{}
if that.Map == nil {
that.Map = Map{}
}
dd := this.Map[key]
dd := that.Map[key]
if dd == nil {
data = cacheData{}
@ -85,74 +85,74 @@ func (this *CacheMemory) set(key string, value interface{}, time int64) {
data.time = time
data.data = value
this.Map.Put(key, data)
that.Map.Put(key, data)
}
func (this *CacheMemory) delete(key string) {
func (that *CacheMemory) delete(key string) {
del := strings.Index(key, "*")
//如果通配删除
if del != -1 {
key = Substr(key, 0, del)
for k, _ := range this.Map {
for k, _ := range that.Map {
if strings.Index(k, key) != -1 {
delete(this.Map, k)
delete(that.Map, k)
}
}
} else {
delete(this.Map, key)
delete(that.Map, key)
}
}
func (this *CacheMemory) Cache(key string, data ...interface{}) *Obj {
func (that *CacheMemory) Cache(key string, data ...interface{}) *Obj {
x := RandX(1, 100000)
if x > 99950 {
this.refreshMap()
that.refreshMap()
}
if this.mutex == nil {
this.mutex = &sync.RWMutex{}
if that.mutex == nil {
that.mutex = &sync.RWMutex{}
}
reData := &Obj{Data: nil}
if len(data) == 0 {
this.mutex.RLock()
reData.Data = this.get(key)
this.mutex.RUnlock()
that.mutex.RLock()
reData.Data = that.get(key)
that.mutex.RUnlock()
return reData
}
tim := time.Now().Unix()
if len(data) == 1 && data[0] == nil {
this.mutex.Lock()
this.delete(key)
this.mutex.Unlock()
that.mutex.Lock()
that.delete(key)
that.mutex.Unlock()
return reData
}
if len(data) == 1 {
tim = tim + this.TimeOut
tim = tim + that.TimeOut
}
if len(data) == 2 {
this.Error.SetError(nil)
tempt := ObjToInt64(data[1], this.Error)
that.Error.SetError(nil)
tempt := ObjToInt64(data[1], that.Error)
if tempt > tim {
tim = tempt
} else if this.Error.GetError() == nil {
} else if that.Error.GetError() == nil {
tim = tim + tempt
}
}
this.mutex.Lock()
this.set(key, data[0], tim)
this.mutex.Unlock()
that.mutex.Lock()
that.set(key, data[0], tim)
that.mutex.Unlock()
return reData
}

102
cache/cache_redis.go vendored
View File

@ -1,7 +1,7 @@
package cache
import (
. "../common"
. "code.hoteas.com/golang/hotime/common"
"github.com/garyburd/redigo/redis"
"strings"
"time"
@ -20,65 +20,65 @@ type CacheRedis struct {
*Error
}
func (this *CacheRedis) GetError() *Error {
func (that *CacheRedis) GetError() *Error {
return this.Error
return that.Error
}
func (this *CacheRedis) SetError(err *Error) {
this.Error = err
func (that *CacheRedis) SetError(err *Error) {
that.Error = err
}
//唯一标志
func (this *CacheRedis) GetTag() int64 {
func (that *CacheRedis) GetTag() int64 {
if this.tag == int64(0) {
this.tag = time.Now().UnixNano()
if that.tag == int64(0) {
that.tag = time.Now().UnixNano()
}
return this.tag
return that.tag
}
func (this *CacheRedis) reCon() bool {
func (that *CacheRedis) reCon() bool {
var err error
this.conn, err = redis.Dial("tcp", this.Host+":"+ObjToStr(this.Port))
that.conn, err = redis.Dial("tcp", that.Host+":"+ObjToStr(that.Port))
if err != nil {
this.conn = nil
this.Error.SetError(err)
that.conn = nil
that.Error.SetError(err)
return false
}
if this.Pwd != "" {
_, err = this.conn.Do("AUTH", this.Pwd)
if that.Pwd != "" {
_, err = that.conn.Do("AUTH", that.Pwd)
if err != nil {
this.conn = nil
this.Error.SetError(err)
that.conn = nil
that.Error.SetError(err)
return false
}
}
return true
}
func (this *CacheRedis) del(key string) {
func (that *CacheRedis) del(key string) {
del := strings.Index(key, "*")
if del != -1 {
val, err := redis.Strings(this.conn.Do("KEYS", key))
val, err := redis.Strings(that.conn.Do("KEYS", key))
if err != nil {
return
}
this.conn.Send("MULTI")
that.conn.Send("MULTI")
for i, _ := range val {
this.conn.Send("DEL", val[i])
that.conn.Send("DEL", val[i])
}
this.conn.Do("EXEC")
that.conn.Do("EXEC")
} else {
_, err := this.conn.Do("DEL", key)
_, err := that.conn.Do("DEL", key)
if err != nil {
this.Error.SetError(err)
_, err = this.conn.Do("PING")
that.Error.SetError(err)
_, err = that.conn.Do("PING")
if err != nil {
if this.reCon() {
_, err = this.conn.Do("DEL", key)
if that.reCon() {
_, err = that.conn.Do("DEL", key)
}
}
}
@ -86,32 +86,32 @@ func (this *CacheRedis) del(key string) {
}
//key value ,时间为时间戳
func (this *CacheRedis) set(key string, value string, time int64) {
_, err := this.conn.Do("SET", key, value, "EX", ObjToStr(time))
func (that *CacheRedis) set(key string, value string, time int64) {
_, err := that.conn.Do("SET", key, value, "EX", ObjToStr(time))
if err != nil {
this.Error.SetError(err)
_, err = this.conn.Do("PING")
that.Error.SetError(err)
_, err = that.conn.Do("PING")
if err != nil {
if this.reCon() {
_, err = this.conn.Do("SET", key, value, "EX", ObjToStr(time))
if that.reCon() {
_, err = that.conn.Do("SET", key, value, "EX", ObjToStr(time))
}
}
}
}
func (this *CacheRedis) get(key string) *Obj {
func (that *CacheRedis) get(key string) *Obj {
reData := &Obj{}
var err error
reData.Data, err = redis.String(this.conn.Do("GET", key))
reData.Data, err = redis.String(that.conn.Do("GET", key))
if err != nil {
reData.Data = nil
if !strings.Contains(err.Error(), "nil returned") {
this.Error.SetError(err)
_, err = this.conn.Do("PING")
that.Error.SetError(err)
_, err = that.conn.Do("PING")
if err != nil {
if this.reCon() {
reData.Data, err = redis.String(this.conn.Do("GET", key))
if that.reCon() {
reData.Data, err = redis.String(that.conn.Do("GET", key))
}
}
@ -121,10 +121,10 @@ func (this *CacheRedis) get(key string) *Obj {
return reData
}
func (this *CacheRedis) Cache(key string, data ...interface{}) *Obj {
func (that *CacheRedis) Cache(key string, data ...interface{}) *Obj {
reData := &Obj{}
if this.conn == nil {
re := this.reCon()
if that.conn == nil {
re := that.reCon()
if !re {
return reData
}
@ -132,38 +132,38 @@ func (this *CacheRedis) Cache(key string, data ...interface{}) *Obj {
//查询缓存
if len(data) == 0 {
reData = this.get(key)
reData = that.get(key)
return reData
}
tim := int64(0)
//删除缓存
if len(data) == 1 && data[0] == nil {
this.del(key)
that.del(key)
return reData
}
//添加缓存
if len(data) == 1 {
if this.TimeOut == 0 {
//this.Time = Config.GetInt64("cacheShortTime")
if that.TimeOut == 0 {
//that.Time = Config.GetInt64("cacheShortTime")
}
tim += this.TimeOut
tim += that.TimeOut
}
if len(data) == 2 {
this.Error.SetError(nil)
tempt := ObjToInt64(data[1], this.Error)
that.Error.SetError(nil)
tempt := ObjToInt64(data[1], that.Error)
if tempt > tim {
tim = tempt
} else if this.GetError() == nil {
} else if that.GetError() == nil {
tim = tim + tempt
}
}
this.set(key, ObjToStr(data[0]), tim)
that.set(key, ObjToStr(data[0]), tim)
return reData

2
cache/type.go vendored
View File

@ -1,7 +1,7 @@
package cache
import (
. "../common"
. "code.hoteas.com/golang/hotime/common"
)
type CacheIns interface {

977
code.go

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,24 @@
package code
import (
. "../common"
. "code.hoteas.com/golang/hotime/common"
)
var Config = Map{
"name": "HoTimeDashBoard",
"id": "2f92h3herh23rh2y8",
"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": "平台首页", "name": "HelloWorld", "icon": "el-icon-s-home"},
//{"label": "测试表格", "table": "table", "icon": "el-icon-suitcase"},
//{"label": "系统管理", "name": "setting", "icon": "el-icon-setting",
// "menus": []Map{
@ -40,6 +48,7 @@ var ColumnDataType = map[string]string{
"float": "number",
"double": "number",
"decimal": "number",
"integer": "number", //sqlite3
"char": "text",
"text": "text",
"blob": "text",
@ -50,54 +59,130 @@ 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 ColumnNameType = []ColumnShow{
//通用
{"idcard", false, true, true, false, "", false},
{"id", true, false, true, false, "", true},
{"parent_id", true, true, true, false, "", true},
//"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},
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"},
{"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": "parent_id", "add": true, "list": true, "edit": true, "info": true, "must": false, "true": false, "type": ""},
{"index", false, false, false, false, "index", false},
{"password", false, true, false, false, "password", false},
{"pwd", false, true, false, false, "password", false},
{"info", false, true, true, false, "", 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, "", false},
{"address", false, 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, true, "time", false},
{"level", false, false, true, false, "", false},
{"rule", true, true, true, false, "form", false},
{"name": "amount", "add": true, "list": true, "edit": true, "info": true, "must": false, "strict": true, "type": "money"},
{"name": "info", "add": true, "list": false, "edit": true, "info": true, "must": false, "strict": false, "type": "textArea"},
{"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"},
}
//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

@ -3,8 +3,8 @@ package code
var InitTpt = `package {{name}}
import (
. "../../../hotime"
. "../../../hotime/common"
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
)
var ID = "{{id}}"
@ -14,30 +14,32 @@ var Project = Proj{
//"user": UserCtr,
{{tablesCtr}}
"hotime":Ctr{
"login": func(this *Context) {
name := this.Req.FormValue("name")
password := this.Req.FormValue("password")
"login": func(that *Context) {
name := that.Req.FormValue("name")
password := that.Req.FormValue("password")
if name == "" || password == "" {
this.Display(3, "参数不足")
that.Display(3, "参数不足")
return
}
user := this.Db.Get("admin", "*", Map{"AND": Map{"OR":Map{"name": name,"phone":name}, "password": Md5(password)}})
user := that.Db.Get("admin", "*", Map{"AND": Map{"OR":Map{"name": name,"phone":name}, "password": Md5(password)}})
if user == nil {
this.Display(5, "登录失败")
that.Display(5, "登录失败")
return
}
this.Session("admin_id", user.GetCeilInt("id"))
this.Session("admin_name", name)
this.Display(0, this.SessionId)
that.Session("admin_id", user.GetCeilInt("id"))
that.Session("admin_name", name)
that.Display(0, that.SessionId)
},
"logout": func(this *Context) {
this.Session("admin_id", nil)
this.Session("admin_name", nil)
this.Display(0, "退出登录成功")
"logout": func(that *Context) {
that.Session("admin_id", nil)
that.Session("admin_name", nil)
that.Display(0, "退出登录成功")
},
"info": func(that *Context) {
hotimeName := that.RouterString[0]
data := that.Db.Get("admin", "*", Map{"id": that.Session("admin_id").ToCeilInt()})
str, inData := that.MakeCode.Info("admin", data, that.Db)
str, inData := that.MakeCodeRouter[hotimeName].Info("admin", data, that.Db)
where := Map{"id": that.Session("admin_id").ToCeilInt()}
if len(inData) ==1 {
inData["id"] =where["id"]
@ -52,7 +54,7 @@ var Project = Proj{
return
}
for k, v := range re {
column := that.MakeCode.TableColumns["admin"][k]
column := that.MakeCodeRouter[hotimeName].TableColumns["admin"][k]
if column == nil {
continue
}
@ -69,15 +71,16 @@ var Project = Proj{
var CtrTpt = `package {{name}}
import (
. "../../../hotime"
. "../../../hotime/common"
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"strings"
)
var {{table}}Ctr = Ctr{
"info": func(that *Context) {
hotimeName := that.RouterString[0]
data := that.Db.Get("admin", "*", Map{"id": that.Session("admin_id").ToCeilInt()})
str, inData := that.MakeCode.Info(that.RouterString[1], data, that.Db)
str, inData := that.MakeCodeRouter[hotimeName].Info(that.RouterString[1], data, that.Db)
where := Map{"id": that.RouterString[2]}
if len(inData) ==1 {
@ -96,7 +99,7 @@ var {{table}}Ctr = Ctr{
}
for k, v := range re {
column := that.MakeCode.TableColumns[that.RouterString[1]][k]
column := that.MakeCodeRouter[hotimeName].TableColumns[that.RouterString[1]][k]
if column == nil {
continue
}
@ -108,7 +111,8 @@ var {{table}}Ctr = Ctr{
that.Display(0, re)
},
"add": func(that *Context) {
inData := that.MakeCode.Add(that.RouterString[1], that.Req)
hotimeName := that.RouterString[0]
inData := that.MakeCodeRouter[hotimeName].Add(that.RouterString[1], that.Req)
if inData == nil {
that.Display(3, "请求参数不足")
return
@ -134,7 +138,8 @@ var {{table}}Ctr = Ctr{
that.Display(0, re)
},
"update": func(that *Context) {
inData := that.MakeCode.Edit(that.RouterString[1], that.Req)
hotimeName := that.RouterString[0]
inData := that.MakeCodeRouter[hotimeName].Edit(that.RouterString[1], that.Req)
if inData == nil {
that.Display(3, "没有找到要更新的数据")
return
@ -165,7 +170,8 @@ var {{table}}Ctr = Ctr{
that.Display(0, re)
},
"remove": func(that *Context) {
inData := that.MakeCode.Delete(that.RouterString[1], that.Req)
hotimeName := that.RouterString[0]
inData := that.MakeCodeRouter[hotimeName].Delete(that.RouterString[1], that.Req)
if inData == nil {
that.Display(3, "请求参数不足")
return
@ -186,10 +192,10 @@ var {{table}}Ctr = Ctr{
},
"search": func(that *Context) {
hotimeName := that.RouterString[0]
data := that.Db.Get("admin", "*", Map{"id": that.Session("admin_id").ToCeilInt()})
columnStr, leftJoin, where := that.MakeCode.Search(that.RouterString[1], data, that.Req, that.Db)
columnStr, leftJoin, where := that.MakeCodeRouter[hotimeName].Search(that.RouterString[1], data, that.Req, that.Db)
page := ObjToInt(that.Req.FormValue("page"))
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
@ -208,7 +214,7 @@ var {{table}}Ctr = Ctr{
for _, v := range reData {
for k, _ := range v {
column := that.MakeCode.TableColumns[that.RouterString[1]][k]
column := that.MakeCodeRouter[hotimeName].TableColumns[that.RouterString[1]][k]
if column == nil {
continue
}

View File

@ -9,10 +9,10 @@ type ContextBase struct {
}
//唯一标志
func (this *ContextBase) GetTag() string {
func (that *ContextBase) GetTag() string {
if this.tag == "" {
this.tag = ObjToStr(time.Now().Unix()) + ":" + ObjToStr(Random())
if that.tag == "" {
that.tag = ObjToStr(time.Now().Unix()) + ":" + ObjToStr(Random())
}
return this.tag
return that.tag
}

View File

@ -5,6 +5,7 @@ import (
"encoding/hex"
"math"
"strings"
"time"
)
//安全锁
@ -36,7 +37,43 @@ func StrFirstToUpper(str string) string {
return strings.ToUpper(first) + other
}
//相似度计算 ld compares two strings and returns the levenshtein distance between them.
// 时间转字符串第二个参数支持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 {
s = strings.ToLower(s)
@ -142,7 +179,7 @@ func Md5(req string) string {
return hex.EncodeToString(cipherStr)
}
//随机数
// Rand 随机数
func Rand(count int) int {
res := Random()
for i := 0; i < count; i++ {
@ -167,7 +204,7 @@ func Random() float64 {
}
//随机数范围
// RandX 随机数范围
func RandX(small int, max int) int {
res := 0
//随机对象
@ -219,7 +256,7 @@ func RandX(small int, max int) int {
// GetDb()
//}
//复制返回数组
// DeepCopyMap 复制返回数组
func DeepCopyMap(value interface{}) interface{} {
if valueMap, ok := value.(Map); ok {
newMap := make(Map)
@ -278,7 +315,7 @@ func DeepCopyMap(value interface{}) interface{} {
// }
//}
//浮点数四舍五入保留小数
// Round 浮点数四舍五入保留小数
func Round(f float64, n int) float64 {
pow10_n := math.Pow10(n)
return math.Trunc((f+0.5/pow10_n)*pow10_n) / pow10_n

View File

@ -4,114 +4,140 @@ import (
"encoding/json"
"errors"
"reflect"
"sort"
"time"
)
//hotime的常用map
type Map map[string]interface{}
//获取string
func (this Map) GetString(key string, err ...*Error) string {
func (that Map) GetString(key string, err ...*Error) string {
if len(err) != 0 {
err[0].SetError(nil)
}
return ObjToStr((this)[key])
return ObjToStr((that)[key])
}
func (this *Map) Pointer() *Map {
func (that *Map) Pointer() *Map {
return this
return that
}
//增加接口
func (this Map) Put(key string, value interface{}) {
//if this==nil{
// this=Map{}
func (that Map) Put(key string, value interface{}) {
//if that==nil{
// that=Map{}
//}
this[key] = value
that[key] = value
}
//删除接口
func (this Map) Delete(key string) {
delete(this, key)
func (that Map) Delete(key string) {
delete(that, key)
}
//获取Int
func (this Map) GetInt(key string, err ...*Error) int {
v := ObjToInt((this)[key], err...)
func (that Map) GetInt(key string, err ...*Error) int {
v := ObjToInt((that)[key], err...)
return v
}
//获取Int
func (this Map) GetInt64(key string, err ...*Error) int64 {
v := ObjToInt64((this)[key], err...)
func (that Map) GetInt64(key string, err ...*Error) int64 {
v := ObjToInt64((that)[key], err...)
return v
}
//获取向上取整Int64
func (this Map) GetCeilInt64(key string, err ...*Error) int64 {
v := ObjToCeilInt64((this)[key], err...)
func (that Map) GetCeilInt64(key string, err ...*Error) int64 {
v := ObjToCeilInt64((that)[key], err...)
return v
}
//获取向上取整Int
func (this Map) GetCeilInt(key string, err ...*Error) int {
v := ObjToCeilInt((this)[key], err...)
func (that Map) GetCeilInt(key string, err ...*Error) int {
v := ObjToCeilInt((that)[key], err...)
return v
}
//获取向上取整float64
func (this Map) GetCeilFloat64(key string, err ...*Error) float64 {
v := ObjToCeilFloat64((this)[key], err...)
func (that Map) GetCeilFloat64(key string, err ...*Error) float64 {
v := ObjToCeilFloat64((that)[key], err...)
return v
}
//获取Float64
func (this Map) GetFloat64(key string, err ...*Error) float64 {
func (that Map) GetFloat64(key string, err ...*Error) float64 {
v := ObjToFloat64((this)[key], err...)
v := ObjToFloat64((that)[key], err...)
return v
}
func (this Map) GetSlice(key string, err ...*Error) Slice {
func (that Map) GetSlice(key string, err ...*Error) Slice {
//var v Slice
v := ObjToSlice((this)[key], err...)
v := ObjToSlice((that)[key], err...)
return v
}
func (this Map) GetBool(key string, err ...*Error) bool {
func (that Map) GetBool(key string, err ...*Error) bool {
//var v Slice
v := ObjToBool((this)[key], err...)
v := ObjToBool((that)[key], err...)
return v
}
func (this Map) GetMap(key string, err ...*Error) Map {
func (that Map) GetTime(key string, err ...*Error) time.Time {
v := ObjToTime((that)[key], err...)
return v
}
func (that Map) RangeSort(callback func(k string, v interface{}) (isEnd bool)) {
testQu := []string{}
//testQuData:= qu[0].(Map)
for key, _ := range that {
//fmt.Println(key, ":", value)
testQu = append(testQu, key)
}
sort.Strings(testQu)
for _, k := range testQu {
re := callback(k, that[k])
if re {
return
}
}
}
func (that Map) GetMap(key string, err ...*Error) Map {
//var data Slice
v := ObjToMap((this)[key], err...)
v := ObjToMap((that)[key], err...)
return v
}
func (this Map) Get(key string, err ...*Error) interface{} {
func (that Map) Get(key string, err ...*Error) interface{} {
if v, ok := (this)[key]; ok {
if v, ok := (that)[key]; ok {
return v
}
e := errors.New("没有存储key及对应的数据")
@ -124,10 +150,10 @@ func (this Map) Get(key string, err ...*Error) interface{} {
}
//请传递指针过来
func (this Map) ToStruct(stct interface{}) {
func (that Map) ToStruct(stct interface{}) {
data := reflect.ValueOf(stct).Elem()
for k, v := range this {
for k, v := range that {
ks := StrFirstToUpper(k)
dkey := data.FieldByName(ks)
if !dkey.IsValid() {
@ -135,13 +161,13 @@ func (this Map) ToStruct(stct interface{}) {
}
switch dkey.Type().String() {
case "int":
dkey.SetInt(this.GetInt64(k))
dkey.SetInt(that.GetInt64(k))
case "int64":
dkey.Set(reflect.ValueOf(this.GetInt64(k)))
dkey.Set(reflect.ValueOf(that.GetInt64(k)))
case "float64":
dkey.Set(reflect.ValueOf(this.GetFloat64(k)))
dkey.Set(reflect.ValueOf(that.GetFloat64(k)))
case "string":
dkey.Set(reflect.ValueOf(this.GetString(k)))
dkey.Set(reflect.ValueOf(that.GetString(k)))
case "interface{}":
dkey.Set(reflect.ValueOf(v))
}
@ -149,13 +175,13 @@ func (this Map) ToStruct(stct interface{}) {
}
func (this Map) ToJsonString() string {
return ObjToStr(this)
func (that Map) ToJsonString() string {
return ObjToStr(that)
}
func (this Map) JsonToMap(jsonStr string, err ...*Error) {
e := json.Unmarshal([]byte(jsonStr), &this)
func (that Map) JsonToMap(jsonStr string, err ...*Error) {
e := json.Unmarshal([]byte(jsonStr), &that)
if e != nil && len(err) != 0 {
err[0].SetError(e)
}

View File

@ -1,5 +1,7 @@
package common
import "time"
//对象封装方便取用
type Obj struct {
Data interface{}
@ -18,6 +20,13 @@ func (that *Obj) ToInt(err ...Error) int {
return ObjToInt(that.Data, &that.Error)
}
func (that *Obj) ToTime(err ...Error) time.Time {
if len(err) != 0 {
that.Error = err[0]
}
return ObjToTime(that.Data, &that.Error)
}
func (that *Obj) ToInt64(err ...Error) int64 {
if len(err) != 0 {
that.Error = err[0]

View File

@ -5,6 +5,7 @@ import (
"errors"
"math"
"strconv"
"time"
)
//仅限于hotime.Slice
@ -96,6 +97,68 @@ func ObjToSlice(obj interface{}, e ...*Error) Slice {
return v
}
func ObjToTime(obj interface{}, e ...*Error) time.Time {
tInt := ObjToInt64(obj)
//字符串类型只支持标准mysql datetime格式
if tInt == 0 {
tStr := ObjToStr(obj)
if len(tStr) > 18 {
t, e := time.Parse("2006-01-02 15:04:05", tStr)
if e == nil {
return t
}
} else if len(tStr) > 15 {
t, e := time.Parse("2006-01-02 15:04", tStr)
if e == nil {
return t
}
} else if len(tStr) > 12 {
t, e := time.Parse("2006-01-02 15", tStr)
if e == nil {
return t
}
} else if len(tStr) > 9 {
t, e := time.Parse("2006-01-02", tStr)
if e == nil {
return t
}
} else if len(tStr) > 6 {
t, e := time.Parse("2006-01", tStr)
if e == nil {
return t
}
}
}
//纳秒级别
if len(ObjToStr(tInt)) > 16 {
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))
return t
//毫秒级别
} else if len(ObjToStr(tInt)) > 10 {
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))
return t
} else if len(ObjToStr(tInt)) > 3 {
t, e := time.Parse("2006", ObjToStr(tInt))
if e == nil {
return t
}
}
return time.Time{}
}
func ObjToFloat64(obj interface{}, e ...*Error) float64 {
var err error
v := float64(0)

View File

@ -2,6 +2,7 @@ package common
import (
"errors"
"time"
)
type Slice []interface{}
@ -14,6 +15,13 @@ func (that Slice) GetString(key int, err ...*Error) string {
return ObjToStr((that)[key])
}
func (that Slice) GetTime(key int, err ...*Error) time.Time {
v := ObjToTime((that)[key], err...)
return v
}
// GetInt 获取Int
func (that Slice) GetInt(key int, err ...*Error) int {
v := ObjToInt((that)[key], err...)

View File

@ -1,22 +1,25 @@
package hotime
import (
. "./cache"
. "./common"
. "./db"
. "code.hoteas.com/golang/hotime/common"
. "code.hoteas.com/golang/hotime/db"
"encoding/json"
"net/http"
"strings"
"time"
)
type Context struct {
*Application
Resp http.ResponseWriter
Req *http.Request
Log Map //日志有则创建
RouterString []string
Config Map
Db *HoTimeDB
RespData Map
CacheIns
RespFunc func()
//CacheIns
SessionIns
DataSize int
HandlerStr string //复写请求url
@ -57,12 +60,41 @@ func (that *Context) Display(statu int, data interface{}) {
}
func (that *Context) View() {
if that.RespFunc != nil {
that.RespFunc()
}
if that.RespData == nil {
return
}
//创建日志
if that.Log != nil {
that.Log["time"] = time.Now().Format("2006-01-02 15:04")
if that.Session("admin_id").Data != nil {
that.Log["admin_id"] = that.Session("admin_id").ToCeilInt()
}
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)
}
d, err := json.Marshal(that.RespData)
if err != nil {
that.Display(1, err.Error())
that.View()
return
}
that.DataSize = len(d)

View File

@ -1,15 +1,17 @@
package db
import (
"../cache"
. "../common"
"code.hoteas.com/golang/hotime/cache"
. "code.hoteas.com/golang/hotime/common"
"database/sql"
"encoding/json"
"errors"
_ "github.com/go-sql-driver/mysql"
_ "github.com/mattn/go-sqlite3"
"github.com/sirupsen/logrus"
"os"
"reflect"
"sort"
"strings"
)
@ -18,6 +20,7 @@ type HoTimeDB struct {
ContextBase
DBName string
*cache.HoTimeCache
Log *logrus.Logger
Type string
Prefix string
LastQuery string
@ -27,6 +30,231 @@ type HoTimeDB struct {
limit Slice
*sql.Tx //事务对象
SlaveDB *sql.DB
Mode int //mode为0生产模式,1、为测试模式、2为开发模式
}
type HotimeDBBuilder struct {
HoTimeDB *HoTimeDB
table string
selects []interface{}
join Slice
where Map
lastWhere Map
page int
pageRow int
}
func (that *HoTimeDB) Table(table string) *HotimeDBBuilder {
return &HotimeDBBuilder{HoTimeDB: that, table: table, where: Map{}}
}
func (that *HotimeDBBuilder) Get(qu ...interface{}) Map {
return that.HoTimeDB.Get(that.table, that.join, qu, that.where)
}
func (that *HotimeDBBuilder) Count() int {
return that.HoTimeDB.Count(that.table, that.join, that.where)
}
func (that *HotimeDBBuilder) Page(page, pageRow int) *HotimeDBBuilder {
that.page = page
that.pageRow = pageRow
return that
}
func (that *HotimeDBBuilder) Select(qu ...interface{}) []Map {
if that.page != 0 {
return that.HoTimeDB.Page(that.page, that.pageRow).PageSelect(that.table, that.join, qu, that.where)
}
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++
}
}
return that.HoTimeDB.Update(that.table, data, that.where)
}
func (that *HotimeDBBuilder) Delete() int64 {
return that.HoTimeDB.Delete(that.table, that.where)
}
func (that *HotimeDBBuilder) LeftJoin(table, joinStr string) *HotimeDBBuilder {
that.Join(Map{"[>]" + table: joinStr})
return that
}
func (that *HotimeDBBuilder) RightJoin(table, joinStr string) *HotimeDBBuilder {
that.Join(Map{"[<]" + table: joinStr})
return that
}
func (that *HotimeDBBuilder) InnerJoin(table, joinStr string) *HotimeDBBuilder {
that.Join(Map{"[><]" + table: joinStr})
return that
}
func (that *HotimeDBBuilder) FullJoin(table, joinStr string) *HotimeDBBuilder {
that.Join(Map{"[<>]" + table: joinStr})
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++
}
}
if that.join == nil {
that.join = Slice{}
}
if data == nil {
return that
}
that.join = append(that.join, data)
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++
}
}
if where == nil {
return that
}
if that.lastWhere != nil {
that.lastWhere["AND"] = where
that.lastWhere = where
return that
}
that.lastWhere = where
that.where = Map{"AND": where}
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++
}
}
if where == nil {
return that
}
if that.lastWhere != nil {
that.lastWhere["OR"] = where
that.lastWhere = where
return that
}
that.lastWhere = where
that.where = Map{"Or": where}
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++
}
}
if where == nil {
return that
}
if that.lastWhere != nil {
that.lastWhere["AND"] = where
that.lastWhere = where
return that
}
that.lastWhere = where
that.where = Map{"AND": that.lastWhere}
return that
}
func (that *HotimeDBBuilder) From(table string) *HotimeDBBuilder {
that.table = table
return that
}
func (that *HotimeDBBuilder) Order(qu ...interface{}) *HotimeDBBuilder {
that.where["ORDER"] = ObjToSlice(qu)
return that
}
func (that *HotimeDBBuilder) Limit(qu ...interface{}) *HotimeDBBuilder {
that.where["LIMIT"] = ObjToSlice(qu)
return that
}
func (that *HotimeDBBuilder) Group(qu ...interface{}) *HotimeDBBuilder {
that.where["GROUP"] = ObjToSlice(qu)
return that
}
// SetConnect 设置数据库配置连接
@ -42,32 +270,36 @@ func (that *HoTimeDB) GetType() string {
}
// Action 事务如果action返回true则执行成功false则回滚
func (that *HoTimeDB) Action(action func(db HoTimeDB) bool) bool {
db := HoTimeDB{DB: that.DB, HoTimeCache: that.HoTimeCache, Prefix: that.Prefix}
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.Begin()
if err != nil {
that.LastErr.SetError(err)
return false
return isSuccess
}
db.Tx = tx
result := action(db)
isSuccess = action(db)
if !result {
if !isSuccess {
err = db.Tx.Rollback()
if err != nil {
that.LastErr.SetError(err)
return false
return isSuccess
}
return result
return isSuccess
}
err = db.Tx.Commit()
if err != nil {
that.LastErr.SetError(err)
return false
}
return result
return true
}
func (that *HoTimeDB) InitDb(err ...*Error) *Error {
@ -86,7 +318,7 @@ func (that *HoTimeDB) InitDb(err ...*Error) *Error {
e := that.SlaveDB.Ping()
that.LastErr.SetError(e)
}
//that.DB.SetConnMaxLifetime(time.Second)
return that.LastErr
}
@ -165,7 +397,7 @@ func (that *HoTimeDB) Row(resl *sql.Rows) []Map {
//
////code=0,1,2 0 backup all,1 backup data,2 backup ddl
//func (this *HoTimeDB) Backup(path string, code int) {
//func (that *HoTimeDB) Backup(path string, code int) {
// var cmd *exec.Cmd
// switch code {
// case 0:cmd= exec.Command("mysqldump","-h"+ObjToStr(Config["dbHost"]), "-P"+ObjToStr(Config["dbPort"]),"-u"+ObjToStr(Config["dbUser"]), "-p"+ObjToStr(Config["dbPwd"]),ObjToStr(Config["dbName"]))
@ -197,7 +429,7 @@ func (that *HoTimeDB) Row(resl *sql.Rows) []Map {
// //db := ``
// //fmt.Println(db)
// //
// //tables := this.Query("show tables")
// //tables := that.Query("show tables")
// //lth := len(tables)
// //if lth == 0 {
// // return
@ -212,7 +444,7 @@ func (that *HoTimeDB) Row(resl *sql.Rows) []Map {
// //
// //for i := 0; i < lth; i++ {
// // tt := tables[i]["Tables_in_"+db].(string)
// // this.backupSave(path, tt, code)
// // that.backupSave(path, tt, code)
// // debug.FreeOSMemory()
// //}
//
@ -259,7 +491,7 @@ func (that *HoTimeDB) backupCol(tt string) string {
for k := range data[0] {
if tempLthData == lthCol-1 {
str += "`" + k + "`)"
str += "`" + k + "`) "
} else {
str += "`" + k + "`,"
}
@ -283,7 +515,7 @@ func (that *HoTimeDB) backupCol(tt string) string {
}
if m == lthCol-1 {
str += v + ")"
str += v + ") "
} else {
str += v + ","
@ -305,7 +537,11 @@ func (that *HoTimeDB) md5(query string, args ...interface{}) string {
}
func (that *HoTimeDB) Query(query string, args ...interface{}) []Map {
defer func() {
if that.Mode != 0 {
that.Log.Info("SQL:"+that.LastQuery, " DATA:", that.LastData, " ERROR:", that.LastErr.GetError())
}
}()
//fmt.Println(query)
var err error
var resl *sql.Rows
@ -330,16 +566,18 @@ 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 {
that.LastErr.SetError(err)
_ = that.InitDb()
if that.LastErr.GetError() != nil {
return nil
}
if err = db.Ping(); err == nil {
return that.Query(query, args...)
}
that.LastErr.SetError(err)
return nil
}
@ -347,7 +585,11 @@ 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 {
that.Log.Info("SQL: "+that.LastQuery, " DATA: ", that.LastData, " ERROR: ", that.LastErr.GetError())
}
}()
that.LastQuery = query
that.LastData = args
var e error
@ -365,25 +607,25 @@ func (that *HoTimeDB) Exec(query string, args ...interface{}) (sql.Result, *Erro
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 {
that.LastErr.SetError(e)
_ = that.InitDb()
if that.LastErr.GetError() != nil {
return resl, that.LastErr
}
if e = that.DB.Ping(); e == nil {
return that.Exec(query, args...)
}
that.LastErr.SetError(e)
return resl, that.LastErr
}
return resl, that.LastErr
}
//func (this *HoTimeDB)copy(data []Map)[]Map{
//func (that *HoTimeDB)copy(data []Map)[]Map{
// if data==nil{
// return nil
// }
@ -420,17 +662,20 @@ func (that *HoTimeDB) Select(table string, qu ...interface{}) []Map {
if reflect.ValueOf(qu[intQs]).Type().String() == "string" {
query += " " + qu[intQs].(string)
} else {
for i := 0; i < len(qu[intQs].(Slice)); i++ {
k := qu[intQs].(Slice)[i].(string)
if strings.Contains(k, " AS ") {
data := ObjToSlice(qu[intQs])
for i := 0; i < len(data); i++ {
k := data.GetString(i)
if strings.Contains(k, " AS ") ||
strings.Contains(k, ".") {
query += " " + k + " "
} else {
query += " `" + k + "` "
}
if i+1 != len(qu[intQs].(Slice)) {
if i+1 != len(data) {
query = query + ", "
}
@ -441,24 +686,75 @@ func (that *HoTimeDB) Select(table string, qu ...interface{}) []Map {
query += " *"
}
if !strings.Contains(table, ".") && !strings.Contains(table, " AS ") {
query += " FROM `" + that.Prefix + table + "`"
query += " FROM `" + that.Prefix + table + "` "
} else {
query += " FROM " + that.Prefix + table
query += " FROM " + that.Prefix + table + " "
}
if join {
for k, v := range qu[0].(Map) {
var testQu = []string{}
testQuData := Map{}
if reflect.ValueOf(qu[0]).Type().String() == "common.Map" {
testQuData = qu[0].(Map)
for key, _ := range testQuData {
//fmt.Println(key, ":", value)
testQu = append(testQu, key)
}
}
if reflect.ValueOf(qu[0]).Type().String() == "common.Slice" {
qu0 := ObjToSlice(qu[0])
for key, _ := range qu0 {
v := qu0.GetMap(key)
for k1, v1 := range v {
testQu = append(testQu, k1)
testQuData[k1] = v1
}
}
}
sort.Strings(testQu)
for _, k := range testQu {
v := testQuData[k]
switch Substr(k, 0, 3) {
case "[>]":
query += " LEFT JOIN " + Substr(k, 3, len(k)-3) + " ON " + v.(string)
func() {
table := Substr(k, 3, len(k)-3)
if !strings.Contains(table, " ") {
table = "`" + table + "`"
}
query += " LEFT JOIN " + table + " ON " + v.(string) + " "
}()
case "[<]":
query += " RIGHT JOIN " + Substr(k, 3, len(k)-3) + " ON " + v.(string)
func() {
table := Substr(k, 3, len(k)-3)
if !strings.Contains(table, " ") {
table = "`" + table + "`"
}
query += " RIGHT JOIN " + table + " ON " + v.(string) + " "
}()
}
switch Substr(k, 0, 4) {
case "[<>]":
query += " FULL JOIN " + Substr(k, 4, len(k)-4) + " ON " + v.(string)
func() {
table := Substr(k, 4, len(k)-4)
if !strings.Contains(table, " ") {
table = "`" + table + "`"
}
query += " FULL JOIN " + table + " ON " + v.(string) + " "
}()
case "[><]":
query += " INNER JOIN " + Substr(k, 4, len(k)-4) + " ON " + v.(string)
func() {
table := Substr(k, 4, len(k)-4)
if !strings.Contains(table, " ") {
table = "`" + table + "`"
}
query += " INNER JOIN " + table + " ON " + v.(string) + " "
}()
}
}
}
@ -469,7 +765,7 @@ func (that *HoTimeDB) Select(table string, qu ...interface{}) []Map {
temp, resWhere := that.where(where)
query += temp
query += temp + ";"
qs = append(qs, resWhere...)
md5 := that.md5(query, qs...)
@ -560,7 +856,15 @@ func (that *HoTimeDB) where(data Map) (string, []interface{}) {
res := make([]interface{}, 0)
//AND OR判断
for k, v := range data {
testQu := []string{}
//testQuData:= qu[0].(Map)
for key, _ := range data {
//fmt.Println(key, ":", value)
testQu = append(testQu, key)
}
sort.Strings(testQu)
for _, k := range testQu {
v := data[k]
x := 0
for i := 0; i < len(condition); i++ {
@ -588,8 +892,7 @@ func (that *HoTimeDB) where(data Map) (string, []interface{}) {
if v != nil && reflect.ValueOf(v).Type().String() == "common.Slice" && len(v.(Slice)) == 0 {
continue
}
if v != nil && reflect.ValueOf(v).Type().String() == "[]interface {}" && len(v.([]interface{})) == 0 {
if v != nil && strings.Contains(reflect.ValueOf(v).Type().String(), "[]") && len(ObjToSlice(v)) == 0 {
continue
}
@ -602,39 +905,56 @@ func (that *HoTimeDB) where(data Map) (string, []interface{}) {
}
if len(where) != 0 {
where = " WHERE " + where
hasWhere := true
for _, v := range vcond {
if strings.Index(where, v) == 0 {
hasWhere = false
}
}
if hasWhere {
where = " WHERE " + where + " "
}
}
//特殊字符
for j := 0; j < len(vcond); j++ {
for k, v := range data {
testQu := []string{}
//testQuData:= qu[0].(Map)
for key, _ := range data {
//fmt.Println(key, ":", value)
testQu = append(testQu, key)
}
sort.Strings(testQu)
for _, k := range testQu {
v := data[k]
if vcond[j] == k {
if k == "ORDER" {
where += " " + k + " BY "
where += k + " BY "
//fmt.Println(reflect.ValueOf(v).Type())
//break
} else if k == "GROUP" {
where += " " + k + " BY "
where += k + " BY "
} else {
where += " " + k
where += k
}
if reflect.ValueOf(v).Type().String() == "common.Slice" {
for i := 0; i < len(v.(Slice)); i++ {
where += " " + ObjToStr(v.(Slice)[i])
where += " " + ObjToStr(v.(Slice)[i]) + " "
if len(v.(Slice)) != i+1 {
where += ","
where += ", "
}
}
} else {
//fmt.Println(v)
where += " " + ObjToStr(v)
where += " " + ObjToStr(v) + " "
}
break
@ -662,45 +982,48 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
case "[>]":
k = strings.Replace(k, "[>]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where += k + ">? "
res = append(res, v)
case "[<]":
k = strings.Replace(k, "[<]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where += k + "<? "
res = append(res, v)
case "[!]":
k = strings.Replace(k, "[!]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where, res = that.notIn(k, v, where, res)
case "[#]":
k = strings.Replace(k, "[#]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where += " " + k + "=" + ObjToStr(v)
where += " " + k + "=" + ObjToStr(v) + " "
case "[##]": //直接添加value到sql需要考虑防注入value比如"a>b"
where += " " + ObjToStr(v)
case "[#!]":
k = strings.Replace(k, "[#!]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where += " " + k + "!=" + ObjToStr(v)
where += " " + k + "!=" + ObjToStr(v) + " "
case "[!#]":
k = strings.Replace(k, "[!#]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where += " " + k + "!=" + ObjToStr(v)
where += " " + k + "!=" + ObjToStr(v) + " "
case "[~]":
k = strings.Replace(k, "[~]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where += k + " LIKE ? "
v = "%" + ObjToStr(v) + "%"
@ -708,15 +1031,15 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
case "[!~]": //左边任意
k = strings.Replace(k, "[~]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where += k + " LIKE ? "
v = "%" + ObjToStr(v)
v = "%" + ObjToStr(v) + ""
res = append(res, v)
case "[~!]": //右边任意
k = strings.Replace(k, "[~]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where += k + " LIKE ? "
v = ObjToStr(v) + "%"
@ -724,7 +1047,7 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
case "[~~]": //手动任意
k = strings.Replace(k, "[~]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where += k + " LIKE ? "
//v = ObjToStr(v)
@ -738,21 +1061,21 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
case "[>=]":
k = strings.Replace(k, "[>=]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where += k + ">=? "
res = append(res, v)
case "[<=]":
k = strings.Replace(k, "[<=]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where += k + "<=? "
res = append(res, v)
case "[><]":
k = strings.Replace(k, "[><]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where += k + " NOT BETWEEN ? AND ? "
res = append(res, v.(Slice)[0])
@ -760,29 +1083,31 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
case "[<>]":
k = strings.Replace(k, "[<>]", "", -1)
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
where += k + " BETWEEN ? AND ? "
res = append(res, v.(Slice)[0])
res = append(res, v.(Slice)[1])
default:
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
if reflect.ValueOf(v).Type().String() == "common.Slice" {
if reflect.ValueOf(v).Type().String() == "common.Slice" || strings.Contains(reflect.ValueOf(v).Type().String(), "[]") {
vs := ObjToSlice(v)
if len(vs) == 0 {
return where, res
}
where += k + " IN ("
res = append(res, v.(Slice)...)
if len(v.(Slice)) == 0 {
where += ") "
} else {
for i := 0; i < len(v.(Slice)); i++ {
if i+1 != len(v.(Slice)) {
where += "?,"
} else {
where += "?) "
}
//res=append(res,(v.(Slice))[i])
res = append(res, vs...)
for i := 0; i < len(vs); i++ {
if i+1 != len(vs) {
where += "?,"
} else {
where += "?) "
}
//res=append(res,(v.(Slice))[i])
}
} else {
@ -796,35 +1121,28 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
} else {
//fmt.Println(reflect.ValueOf(v).Type().String())
if !strings.Contains(k, ".") {
k = "`" + k + "`"
k = "`" + k + "` "
}
if v == nil {
where += k + " IS NULL"
} else if reflect.ValueOf(v).Type().String() == "common.Slice" {
where += k + " IS NULL "
} else if reflect.ValueOf(v).Type().String() == "common.Slice" || strings.Contains(reflect.ValueOf(v).Type().String(), "[]") {
vs := ObjToSlice(v)
//fmt.Println(v)
where += k + " IN ("
res = append(res, v.(Slice)...)
for i := 0; i < len(v.(Slice)); i++ {
if i+1 != len(v.(Slice)) {
where += "?,"
} else {
where += "?) "
}
//res=append(res,(v.(Slice))[i])
if len(vs) == 0 {
return where, res
}
} else if reflect.ValueOf(v).Type().String() == "[]interface {}" {
where += k + " IN ("
res = append(res, vs...)
where += k + " IN ("
res = append(res, v.([]interface{})...)
for i := 0; i < len(v.([]interface{})); i++ {
if i+1 != len(v.([]interface{})) {
for i := 0; i < len(vs); i++ {
if i+1 != len(vs) {
where += "?,"
} else {
where += "?) "
}
//res=append(res,(v.(Slice))[i])
}
} else {
where += k + "=? "
@ -836,7 +1154,7 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
return where, res
}
// this.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())
@ -844,28 +1162,23 @@ func (that *HoTimeDB) notIn(k string, v interface{}, where string, res []interfa
where += k + " IS NOT NULL "
} else if reflect.ValueOf(v).Type().String() == "common.Slice" {
} else if reflect.ValueOf(v).Type().String() == "common.Slice" || strings.Contains(reflect.ValueOf(v).Type().String(), "[]") {
vs := ObjToSlice(v)
if len(vs) == 0 {
return where, res
}
where += k + " NOT IN ("
res = append(res, v.(Slice)...)
for i := 0; i < len(v.(Slice)); i++ {
if i+1 != len(v.(Slice)) {
where += "?,"
} else {
where += "?) "
}
//res=append(res,(v.(Slice))[i])
}
} else if reflect.ValueOf(v).Type().String() == "[]interface {}" {
where += k + " NOT IN ("
res = append(res, v.([]interface{})...)
for i := 0; i < len(v.([]interface{})); i++ {
if i+1 != len(v.([]interface{})) {
res = append(res, vs...)
for i := 0; i < len(vs); i++ {
if i+1 != len(vs) {
where += "?,"
} else {
where += "?) "
}
//res=append(res,(v.(Slice))[i])
}
} else {
where += k + " !=? "
@ -881,7 +1194,15 @@ func (that *HoTimeDB) cond(tag string, data Map) (string, []interface{}) {
res := make([]interface{}, 0)
lens := len(data)
//fmt.Println(lens)
for k, v := range data {
testQu := []string{}
//testQuData:= qu[0].(Map)
for key, _ := range data {
//fmt.Println(key, ":", value)
testQu = append(testQu, key)
}
sort.Strings(testQu)
for _, k := range testQu {
v := data[k]
x := 0
for i := 0; i < len(condition); i++ {
@ -904,7 +1225,10 @@ func (that *HoTimeDB) cond(tag string, data Map) (string, []interface{}) {
if x == len(condition) {
tv, vv := that.varCond(k, v)
if tv == "" {
lens--
continue
}
res = append(res, vv...)
if lens--; lens <= 0 {
where += tv + ""
@ -935,7 +1259,7 @@ func (that *HoTimeDB) Update(table string, data Map, where Map) int64 {
} else {
qs = append(qs, v)
}
query += "`" + k + "`=" + vstr + ""
query += "`" + k + "`=" + vstr + " "
if tp--; tp != 0 {
query += ", "
}
@ -944,7 +1268,7 @@ func (that *HoTimeDB) Update(table string, data Map, where Map) int64 {
temp, resWhere := that.where(where)
//fmt.Println(resWhere)
query += temp
query += temp + ";"
qs = append(qs, resWhere...)
res, err := that.Exec(query, qs...)
@ -969,7 +1293,7 @@ func (that *HoTimeDB) Delete(table string, data map[string]interface{}) int64 {
query := "DELETE FROM " + that.Prefix + table + " "
temp, resWhere := that.where(data)
query += temp
query += temp + ";"
res, err := that.Exec(query, resWhere...)
rows := int64(0)
@ -999,13 +1323,29 @@ func (that *HoTimeDB) Insert(table string, data map[string]interface{}) int64 {
tempLen := 0
for k, v := range data {
tempLen++
values = append(values, v)
if tempLen < lens {
queryString += "`" + k + "`,"
valueString += "?,"
vstr := "?"
if Substr(k, len(k)-3, 3) == "[#]" {
k = strings.Replace(k, "[#]", "", -1)
vstr = ObjToStr(v)
if tempLen < lens {
queryString += "`" + k + "`,"
valueString += vstr + ","
} else {
queryString += "`" + k + "`) "
valueString += vstr + ");"
}
} else {
queryString += "`" + k + "`) "
valueString += "?);"
values = append(values, v)
if tempLen < lens {
queryString += "`" + k + "`,"
valueString += "?,"
} else {
queryString += "`" + k + "`) "
valueString += "?);"
}
}
}

View File

@ -1,53 +1,55 @@
package aliyun
import (
. "../../common"
. "code.hoteas.com/golang/hotime/common"
"fmt"
"io/ioutil"
"net/http"
//"fmt"
)
type Company struct {
type company struct {
ApiCode string
Url string
}
func (this *Company) Init(apiCode string) {
var Company = company{}
func (that *company) Init(apiCode string) {
//"06c6a07e89dd45c88de040ee1489eef7"
this.ApiCode = apiCode
this.Url = "http://api.81api.com"
that.ApiCode = apiCode
that.Url = "http://api.81api.com"
}
// GetCompanyBaseInfo 获取企业基础信息
func (this *Company) GetCompanyOtherAll(name string) Map {
// GetCompanyOtherAll 获取企业基础信息
func (that *company) GetCompanyOtherAll(name string) Map {
res := Map{}
data, e := this.GetCompanyPatentsInfo(name) //获取专利信息
data, e := that.GetCompanyPatentsInfo(name) //获取专利信息
if e != nil {
fmt.Println(e)
} else {
res["PatentsInfo"] = data.GetMap("data")
}
data, e = this.GetCompanyOtherCopyrightsInfo(name) //获取其他专利
data, e = that.GetCompanyOtherCopyrightsInfo(name) //获取其他专利
if e != nil {
fmt.Println(e)
} else {
res["OtherCopyrightsInfo"] = data.GetMap("data")
}
data, e = this.GetCompanyTrademarksInfo(name) //获取商标
data, e = that.GetCompanyTrademarksInfo(name) //获取商标
if e != nil {
fmt.Println(e)
} else {
res["TrademarksInfo"] = data.GetMap("data")
}
data, e = this.GetCompanySoftwareCopyrightsInfo(name) //获取软著
data, e = that.GetCompanySoftwareCopyrightsInfo(name) //获取软著
if e != nil {
fmt.Println(e)
} else {
res["SoftwareCopyrightsInfo"] = data.GetMap("data")
}
data, e = this.GetCompanyProfileTags(name) //获取大数据标签
data, e = that.GetCompanyProfileTags(name) //获取大数据标签
if e != nil {
fmt.Println(e)
} else {
@ -57,63 +59,71 @@ func (this *Company) GetCompanyOtherAll(name string) Map {
}
// GetCompanyBaseInfo 获取企业基础信息
func (this *Company) GetCompanyBaseInfo(name string) (Map, error) {
func (that *company) GetCompanyList(name string) (Map, error) {
url := "/fuzzyQueryCompanyInfo/"
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
// GetCompanyBaseInfo 获取企业基础信息
func (that *company) GetCompanyBaseInfo(name string) (Map, error) {
url := "/getCompanyBaseInfo/"
body, err := this.basePost(url, name)
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
// GetCompanyPatentsInfo 获取专利信息
func (this *Company) GetCompanyPatentsInfo(name string) (Map, error) {
func (that *company) GetCompanyPatentsInfo(name string) (Map, error) {
url := "/getCompanyPatentsInfo/"
body, err := this.basePost(url, name)
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
// 获取商标信息
func (this *Company) GetCompanyTrademarksInfo(name string) (Map, error) {
// GetCompanyTrademarksInfo 获取商标信息
func (that *company) GetCompanyTrademarksInfo(name string) (Map, error) {
url := "/getCompanyTrademarksInfo/"
body, err := this.basePost(url, name)
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
// 获取软著信息
func (this *Company) GetCompanySoftwareCopyrightsInfo(name string) (Map, error) {
// GetCompanySoftwareCopyrightsInfo 获取软著信息
func (that *company) GetCompanySoftwareCopyrightsInfo(name string) (Map, error) {
url := "/getCompanySoftwareCopyrightsInfo/"
body, err := this.basePost(url, name)
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
// 获取其他著作信息
func (this *Company) GetCompanyOtherCopyrightsInfo(name string) (Map, error) {
// GetCompanyOtherCopyrightsInfo 获取其他著作信息
func (that *company) GetCompanyOtherCopyrightsInfo(name string) (Map, error) {
url := "/getCompanyOtherCopyrightsInfo/"
body, err := this.basePost(url, name)
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
// 获取大数据标签
func (this *Company) GetCompanyProfileTags(name string) (Map, error) {
// GetCompanyProfileTags 获取大数据标签
func (that *company) GetCompanyProfileTags(name string) (Map, error) {
url := "/getCompanyProfileTags/"
body, err := this.basePost(url, name)
body, err := that.basePost(url, name)
return ObjToMap(body), err
}
func (this *Company) basePost(url string, name string) (string, error) {
func (that *company) basePost(url string, name string) (string, error) {
client := &http.Client{}
reqest, err := http.NewRequest("GET", this.Url+url+name+"/?isRaiseErrorCode=1", nil)
reqest, err := http.NewRequest("GET", that.Url+url+name+"/?isRaiseErrorCode=1", nil)
if err != nil {
fmt.Println("Fatal error ", err.Error())
return "", err
}
reqest.Header.Add("Authorization", "APPCODE "+this.ApiCode)
reqest.Header.Add("Authorization", "APPCODE "+that.ApiCode)
response, err := client.Do(reqest)
defer response.Body.Close()
@ -130,9 +140,3 @@ func (this *Company) basePost(url string, name string) (string, error) {
fmt.Println(res)
return res, err
}
var DefaultCompany Company
func init() {
DefaultCompany = Company{}
}

View File

@ -7,26 +7,28 @@ import (
"net/url"
)
type BaiduMap struct {
type baiduMap struct {
Ak string
Url string
}
func (this *BaiduMap) Init(Ak string) {
var BaiDuMap = baiduMap{}
func (that *baiduMap) Init(Ak string) {
//"ak=ZeT902EZvVgIoGVWEFK3osUm"
this.Ak = Ak
this.Url = "https://api.map.baidu.com/place/v2/suggestion?output=json" + "&ak=" + Ak
that.Ak = Ak
that.Url = "https://api.map.baidu.com/place/v2/suggestion?output=json" + "&ak=" + Ak
//query
}
// GetPosition 获取定位列表
func (this *BaiduMap) GetPosition(name string, region string) (string, error) {
func (that *baiduMap) GetPosition(name string, region string) (string, error) {
client := &http.Client{}
if region == "" {
region = "全国"
}
reqest, err := http.NewRequest("GET", this.Url+"&query="+url.PathEscape(name)+"&region="+url.PathEscape(region), nil)
reqest, err := http.NewRequest("GET", that.Url+"&query="+url.PathEscape(name)+"&region="+url.PathEscape(region), nil)
if err != nil {
fmt.Println("Fatal error ", err.Error())
@ -50,9 +52,3 @@ func (this *BaiduMap) GetPosition(name string, region string) (string, error) {
return string(body), err
}
var DefaultBaiDuMap BaiduMap
func init() {
DefaultBaiDuMap = BaiduMap{}
}

View File

@ -10,29 +10,31 @@ import (
//"fmt"
)
type DDY struct {
type dingdongyun struct {
ApiKey string
YzmUrl string
TzUrl string
}
func (this *DDY) Init(apikey string) {
this.ApiKey = apikey
this.YzmUrl = "https://api.dingdongcloud.com/v2/sms/captcha/send.json"
this.TzUrl = "https://api.dingdongcloud.com/v2/sms/notice/send.json"
var DDY = dingdongyun{}
func (that *dingdongyun) Init(apikey string) {
that.ApiKey = apikey
that.YzmUrl = "https://api.dingdongcloud.com/v2/sms/captcha/send.json"
that.TzUrl = "https://api.dingdongcloud.com/v2/sms/notice/send.json"
}
//发送短信验证码 code验证码如123456 返回true表示发送成功flase表示发送失败
func (this *DDY) SendYZM(umoblie string, tpt string, data map[string]string) (bool, error) {
// SendYZM 发送短信验证码 code验证码如123456 返回true表示发送成功flase表示发送失败
func (that *dingdongyun) SendYZM(umoblie string, tpt string, data map[string]string) (bool, error) {
for k, v := range data {
tpt = strings.Replace(tpt, "{"+k+"}", v, -1)
}
return this.send(this.YzmUrl, umoblie, tpt)
return that.send(that.YzmUrl, umoblie, tpt)
}
//发送通知
func (this *DDY) SendTz(umoblie []string, tpt string, data map[string]string) (bool, error) {
// SendTz 发送通知
func (that *dingdongyun) SendTz(umoblie []string, tpt string, data map[string]string) (bool, error) {
for k, v := range data {
tpt = strings.Replace(tpt, "{"+k+"}", v, -1)
}
@ -44,14 +46,14 @@ func (this *DDY) SendTz(umoblie []string, tpt string, data map[string]string) (b
}
umobleStr += "," + v
}
return this.send(this.TzUrl, umobleStr, tpt)
return that.send(that.TzUrl, umobleStr, tpt)
}
//发送短信
func (this *DDY) send(mUrl string, umoblie string, content string) (bool, error) {
func (that *dingdongyun) send(mUrl string, umoblie string, content string) (bool, error) {
data_send_sms_yzm := url.Values{"apikey": {this.ApiKey}, "mobile": {umoblie}, "content": {content}}
res, err := this.httpsPostForm(mUrl, data_send_sms_yzm)
data_send_sms_yzm := url.Values{"apikey": {that.ApiKey}, "mobile": {umoblie}, "content": {content}}
res, err := that.httpsPostForm(mUrl, data_send_sms_yzm)
if err != nil && res == "" {
return false, errors.New("连接错误")
}
@ -73,7 +75,7 @@ func (this *DDY) send(mUrl string, umoblie string, content string) (bool, error)
}
//调用url发送短信的连接
func (this *DDY) httpsPostForm(url string, data url.Values) (string, error) {
func (that *dingdongyun) httpsPostForm(url string, data url.Values) (string, error) {
resp, err := http.PostForm(url, data)
if err != nil {
@ -89,9 +91,3 @@ func (this *DDY) httpsPostForm(url string, data url.Values) (string, error) {
return string(body), nil
}
var DefaultDDY DDY
func init() {
DefaultDDY = DDY{}
}

View File

@ -1,15 +1,15 @@
package download
import (
. "../../common"
"bytes"
. "code.hoteas.com/golang/hotime/common"
"io"
"io/ioutil"
"net/http"
"os"
)
//下载文件
// Down 下载文件
func Down(url, path, name string, e ...*Error) bool {
os.MkdirAll(path, os.ModeDir)
@ -18,13 +18,13 @@ func Down(url, path, name string, e ...*Error) bool {
}
out, err := os.Create(path + name)
if err != nil && e[0] != nil {
if err != nil && len(e) != 0 {
e[0].SetError(err)
return false
}
defer out.Close()
resp, err := http.Get(url)
if err != nil && e[0] != nil {
if err != nil && len(e) != 0 {
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 && e[0] != nil {
if err != nil && len(e) != 0 {
e[0].SetError(err)
return false
}

149
dri/mongodb/mongodb.go Normal file
View File

@ -0,0 +1,149 @@
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
}

View File

@ -23,7 +23,7 @@ func FileGet(path string) []byte {
return buf
}
//RSA加密
// RSA_Encrypt RSA加密
// plainText 要加密的数据
// path 公钥匙文件地址
func RSA_Encrypt(plainText []byte, buf []byte) []byte {
@ -46,7 +46,7 @@ func RSA_Encrypt(plainText []byte, buf []byte) []byte {
return cipherText
}
//RSA解密
// RSA_Decrypt RSA解密
// cipherText 需要解密的byte数据
// path 私钥文件路径
func RSA_Decrypt(cipherText []byte, buf []byte) []byte {
@ -97,7 +97,7 @@ func Demo() {
fmt.Println(string(decrypt))
}
//生成RSA私钥和公钥保存到文件中
// GenerateRSAKey 生成RSA私钥和公钥保存到文件中
// bits 证书大小
func GenerateRSAKey(bits int, path string) {
//GenerateKey函数使用随机数据生成器random生成一对具有指定字位数的RSA密钥

View File

@ -1,7 +1,7 @@
package tencent
import (
. "../../common"
. "code.hoteas.com/golang/hotime/common"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
@ -15,24 +15,40 @@ import (
"time"
)
func calcAuthorization(source string, secretId string, secretKey string) (auth string, datetime string, err error) {
type company struct {
secretId string
secretKey string
}
var Company = company{}
func (that *company) Init(secretId, secretKey string) {
// 云市场分配的密钥Id
//secretId := "xxxx"
//// 云市场分配的密钥Key
//secretKey := "xxxx"
that.secretId = secretId
that.secretKey = secretKey
}
func (that *company) calcAuthorization(source string) (auth string, datetime string, err error) {
timeLocation, _ := time.LoadLocation("Etc/GMT")
datetime = time.Now().In(timeLocation).Format("Mon, 02 Jan 2006 15:04:05 GMT")
signStr := fmt.Sprintf("x-date: %s\nx-source: %s", datetime, source)
// hmac-sha1
mac := hmac.New(sha1.New, []byte(secretKey))
mac := hmac.New(sha1.New, []byte(that.secretKey))
mac.Write([]byte(signStr))
sign := base64.StdEncoding.EncodeToString(mac.Sum(nil))
auth = fmt.Sprintf("hmac id=\"%s\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"%s\"",
secretId, sign)
that.secretId, sign)
return auth, datetime, nil
}
func urlencode(params map[string]string) string {
func (that *company) urlencode(params map[string]string) string {
var p = gourl.Values{}
for k, v := range params {
p.Add(k, v)
@ -40,7 +56,7 @@ func urlencode(params map[string]string) string {
return p.Encode()
}
func GetCompany(secretId, secretKey, name string) Map {
func (that *company) GetCompany(name string) Map {
// 云市场分配的密钥Id
//secretId := "xxxx"
//// 云市场分配的密钥Key
@ -48,7 +64,7 @@ func GetCompany(secretId, secretKey, name string) Map {
source := "market"
// 签名
auth, datetime, _ := calcAuthorization(source, secretId, secretKey)
auth, datetime, _ := that.calcAuthorization(source)
// 请求方法
method := "GET"
@ -64,13 +80,13 @@ func GetCompany(secretId, secretKey, name string) Map {
// url参数拼接
url := "https://service-3jnh3ku8-1256140209.gz.apigw.tencentcs.com/release/business4/geet"
if len(queryParams) > 0 {
url = fmt.Sprintf("%s?%s", url, urlencode(queryParams))
url = fmt.Sprintf("%s?%s", url, that.urlencode(queryParams))
}
bodyMethods := map[string]bool{"POST": true, "PUT": true, "PATCH": true}
var body io.Reader = nil
if bodyMethods[method] {
body = strings.NewReader(urlencode(bodyParams))
body = strings.NewReader(that.urlencode(bodyParams))
headers["Content-Type"] = "application/x-www-form-urlencoded"
}

View File

@ -8,16 +8,32 @@ import (
ocr "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ocr/v20181119"
)
var credential = common.NewCredential(
"AKIDOgT8cKCQksnY7yKATaYO7j9ORJzSYohP",
"GNXgjdN4czA9ya0FNMApVJzTmsmU0KSN",
)
type tencent struct {
secretId string
secretKey string
credential *common.Credential
}
func OCRCOMPANY(base64Str string) string {
var Tencent = tencent{}
func (that *tencent) Init(secretId, secretKey string) {
// 云市场分配的密钥Id
//secretId := "xxxx"
//// 云市场分配的密钥Key
//secretKey := "xxxx"
that.secretId = secretId
that.secretKey = secretKey
that.credential = common.NewCredential(
that.secretId,
that.secretKey,
)
}
func (that *tencent) OCRCOMPANY(base64Str string) string {
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "ocr.tencentcloudapi.com"
client, _ := ocr.NewClient(credential, "ap-guangzhou", cpf)
client, _ := ocr.NewClient(that.credential, "ap-guangzhou", cpf)
request := ocr.NewBizLicenseOCRRequest()
@ -38,11 +54,11 @@ func OCRCOMPANY(base64Str string) string {
return response.ToJsonString()
}
func OCR(base64Str string) string {
func (that *tencent) OCR(base64Str string) string {
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "ocr.tencentcloudapi.com"
client, _ := ocr.NewClient(credential, "ap-guangzhou", cpf)
client, _ := ocr.NewClient(that.credential, "ap-guangzhou", cpf)
request := ocr.NewGeneralAccurateOCRRequest()
@ -63,11 +79,11 @@ func OCR(base64Str string) string {
return response.ToJsonString()
}
func Qrcode(base64Str string) string {
func (that *tencent) Qrcode(base64Str string) string {
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "ocr.tencentcloudapi.com"
client, _ := ocr.NewClient(credential, "ap-guangzhou", cpf)
client, _ := ocr.NewClient(that.credential, "ap-guangzhou", cpf)
request := ocr.NewQrcodeOCRRequest()

View File

@ -1,7 +1,7 @@
package upload
import (
. "../../common"
. "code.hoteas.com/golang/hotime/common"
"errors"
"io"
"mime/multipart"
@ -15,7 +15,7 @@ type Upload struct {
Path string
}
func (this *Upload) UpFile(Request *http.Request, fieldName, savefilepath, savePath string) (string, error) {
func (that *Upload) UpFile(Request *http.Request, fieldName, savefilepath, savePath string) (string, error) {
Request.ParseMultipartForm(32 << 20)
var filePath string
files := Request.MultipartForm.File
@ -36,7 +36,7 @@ func (this *Upload) UpFile(Request *http.Request, fieldName, savefilepath, saveP
data := time.Unix(int64(t), 0).Format("2006-01")
path := ""
if strings.EqualFold(savefilepath, "") {
path = this.Path + data
path = that.Path + data
} else {
path = savefilepath + data
}
@ -51,7 +51,7 @@ func (this *Upload) UpFile(Request *http.Request, fieldName, savefilepath, saveP
}
}
filename := time.Unix(int64(t), 0).Format("2006-01-02-15-22-25") + ObjToStr(Rand(6))
filePath = path + "/" + filename + this.Path
filePath = path + "/" + filename + that.Path
} else {
filePath = savePath
}

79
dri/wechat/h5program.go Normal file
View File

@ -0,0 +1,79 @@
package wechat
import (
"github.com/silenceper/wechat/v2"
"github.com/silenceper/wechat/v2/cache"
"github.com/silenceper/wechat/v2/officialaccount"
h5config "github.com/silenceper/wechat/v2/officialaccount/config"
"github.com/silenceper/wechat/v2/officialaccount/js"
"github.com/silenceper/wechat/v2/officialaccount/oauth"
)
//基于此文档开发
//https://github.com/silenceper/wechat/blob/v2/doc/api/officialaccount.md
type h5Program struct {
Memory *cache.Memory
Config *h5config.Config
*officialaccount.OfficialAccount
weixin *wechat.Wechat //微信登录实例
}
var H5Program = h5Program{}
// Init 初始化
func (that *h5Program) Init(appid string, appsecret string) {
that.weixin = wechat.NewWechat()
that.Memory = cache.NewMemory()
that.Config = &h5config.Config{
AppID: appid,
AppSecret: appsecret,
//Token: "xxx",
//EncodingAESKey: "xxxx",
Cache: that.Memory,
}
that.OfficialAccount = that.weixin.GetOfficialAccount(that.Config)
}
// GetUserInfo 获取用户信息
func (that *h5Program) GetUserInfo(code string) (appid string, resToken oauth.ResAccessToken, userInfo oauth.UserInfo, err error) {
auth := that.GetOauth()
//weixin.GetOpenPlatform()
resToken, err = auth.GetUserAccessToken(code)
if err != nil {
return auth.AppID, resToken, userInfo, err
}
//getUserInfo
userInfo, err = auth.GetUserInfo(resToken.AccessToken, resToken.OpenID, "")
if err != nil {
return auth.AppID, resToken, userInfo, err
}
return auth.AppID, resToken, userInfo, err
}
// GetSignUrl js url签名
func (that *h5Program) GetSignUrl(signUrl string) (*js.Config, error) {
js := that.OfficialAccount.GetJs()
cfg1, e := js.GetConfig(signUrl)
if e != nil {
return nil, e
}
return cfg1, nil
}
// GetSignUrl js url签名
//func (that *h5Program) GetJsPay(signUrl string) (*js.Config, error) {
// //
// //js := that.OfficialAccount().GetJs()
// //
// //cfg1, e := js.GetConfig(signUrl)
// //if e != nil {
// // return nil, e
// //}
//
// return cfg1, nil
//}

66
dri/wechat/miniprogram.go Normal file
View File

@ -0,0 +1,66 @@
package wechat
import (
"errors"
"github.com/silenceper/wechat/v2"
"github.com/silenceper/wechat/v2/cache"
"github.com/silenceper/wechat/v2/miniprogram"
"github.com/silenceper/wechat/v2/miniprogram/auth"
"github.com/silenceper/wechat/v2/miniprogram/config"
"github.com/silenceper/wechat/v2/miniprogram/encryptor"
)
type miniProgram struct {
Memory *cache.Memory
Config *config.Config
weixin *wechat.Wechat //微信登录实例
*miniprogram.MiniProgram
}
var MiniProgram = miniProgram{}
// Init 初始化
func (that *miniProgram) Init(appid string, appsecret string) {
that.weixin = wechat.NewWechat()
that.Memory = cache.NewMemory()
that.Config = &config.Config{
AppID: appid,
AppSecret: appsecret,
//Token: "xxx",
//EncodingAESKey: "xxxx",
Cache: that.Memory,
}
that.MiniProgram = that.weixin.GetMiniProgram(that.Config)
}
func (that *miniProgram) GetBaseUserInfo(code string) (appid string, re auth.ResCode2Session, err error) {
appid = that.Config.AppID
a := that.GetAuth()
re, err = a.Code2Session(code)
if err != nil {
return appid, re, err
}
return appid, re, err
}
func (that *miniProgram) GetPhoneNumber(sessionkey, encryptedData, iv string) (appid string, re *encryptor.PlainData, err error) {
appid = that.Config.AppID
if sessionkey == "" || encryptedData == "" || iv == "" {
return appid, re, errors.New("参数不足")
}
eny := that.GetEncryptor()
re, err = eny.Decrypt(sessionkey, encryptedData, iv)
if err != nil {
return appid, re, err
}
return appid, re, err
}

142
dri/wechat/pay.go Normal file
View File

@ -0,0 +1,142 @@
package wechat
import (
"context"
"fmt"
"github.com/go-pay/gopay"
"github.com/go-pay/gopay/wechat/v3"
"net/http"
"time"
)
//基于此文档开发
//https://github.com/silenceper/wechat/blob/v2/doc/api/officialaccount.md
type wxpay struct {
client *wechat.ClientV3
ctx context.Context
apiV3Key string
MchId string
}
var WxPay = wxpay{}
// Init 初始化
func (that *wxpay) Init(MchId, SerialNo, APIv3Key, PrivateKey string) {
client, err := wechat.NewClientV3(MchId, SerialNo, APIv3Key, PrivateKey)
if err != nil {
//xlog.Error(err)
fmt.Println(err)
return
}
that.client = client
that.apiV3Key = APIv3Key
that.MchId = MchId
// 设置微信平台API证书和序列号如开启自动验签请忽略此步骤
//client.SetPlatformCert([]byte(""), "")
that.ctx = context.Background()
// 启用自动同步返回验签并定时更新微信平台API证书开启自动验签时无需单独设置微信平台API证书和序列号
err = client.AutoVerifySign()
if err != nil {
//xlog.Error(err)
fmt.Println(err)
return
}
// 打开Debug开关输出日志默认是关闭的
client.DebugSwitch = gopay.DebugOn
}
// GetUserInfo 获取用户信息
func (that *wxpay) GetJsOrder(money int64, appid, openid, name, tradeNo, notifyUrl string) (jsApiParams *wechat.JSAPIPayParams, err error) {
fmt.Println("dasdas", money, appid, name, tradeNo, notifyUrl)
PrepayId, err := that.getPrepayId(money, appid, that.MchId, openid, name, tradeNo, notifyUrl)
if err != nil {
return nil, err
}
//小程序
jsapi, err := that.client.PaySignOfJSAPI(appid, PrepayId)
return jsapi, err
}
func (that *wxpay) CallbackJsOrder(req *http.Request) (*wechat.V3DecryptResult, error) {
notifyReq, err := wechat.V3ParseNotify(req)
if err != nil {
//xlog.Error(err)
return nil, err
}
// wxPublicKey 通过 client.WxPublicKey() 获取
err = notifyReq.VerifySignByPK(that.client.WxPublicKey())
if err != nil {
//xlog.Error(err)
return nil, err
}
// ========异步通知敏感信息解密========
// 普通支付通知解密
result, err := notifyReq.DecryptCipherText(that.apiV3Key)
//that.client.V3TransactionQueryOrder(that.ctx,result.BankType,result.OR)
return result, err
// 合单支付通知解密
//result, err := notifyReq.DecryptCombineCipherText(apiV3Key)
//// 退款通知解密
//result, err := notifyReq.DecryptRefundCipherText(apiV3Key)
// ========异步通知应答========
// 退款通知http应答码为200且返回状态码为SUCCESS才会当做商户接收成功否则会重试。
// 注意:重试过多会导致微信支付端积压过多通知而堵塞,影响其他正常通知。
// 此写法是 gin 框架返回微信的写法
//c.JSON(http.StatusOK, &wechat.V3NotifyRsp{Code: gopay.SUCCESS, Message: "成功"})
//
//// 此写法是 echo 框架返回微信的写法
//return c.JSON(http.StatusOK, &wechat.V3NotifyRsp{Code: gopay.SUCCESS, Message: "成功"})
}
// GetUserInfo 获取用户信息
//func (that *wxpay) GetMiniOrder(money int64,appid,name,tradeNo,notifyUrl string) (jsApiParams *wechat.AppletParams,err error){
//
// PrepayId,err:=that.getPrepayId(money,name,tradeNo,notifyUrl)
// if err!=nil{
// return nil,err
// }
//
// //小程序
// applet, err := that.client.PaySignOfApplet(appid,PrepayId)
//
// return applet,err
//}
func (that *wxpay) getPrepayId(money int64, appid, mchid, openid, name, tradeNo, notifyUrl string) (prepayid string, err error) {
expire := time.Now().Add(10 * time.Minute).Format(time.RFC3339)
// 初始化 BodyMap
bm := make(gopay.BodyMap)
bm.Set("appid", appid).
Set("mchid", mchid).
//Set("sub_mchid", "sub_mchid").
Set("description", name).
Set("out_trade_no", tradeNo).
Set("time_expire", expire).
Set("notify_url", notifyUrl).
SetBodyMap("amount", func(bm gopay.BodyMap) {
bm.Set("total", money).
Set("currency", "CNY")
}).
SetBodyMap("payer", func(bm gopay.BodyMap) {
bm.Set("openid", openid)
})
//ctx:=context.Context()
wxRsp, err := that.client.V3TransactionJsapi(that.ctx, bm)
fmt.Println("获取PrepayId", wxRsp, err)
if err != nil {
//xlog.Error(err)
return "", err
}
return wxRsp.Response.PrepayId, nil
}

419
example/config/admin.json Normal file
View File

@ -0,0 +1,419 @@
{
"flow": {
"admin": {
"sql": {
"org_id": "org_id",
"parent_ids[~]": "%,id,%",
"role_id": "role_id",
"zone_id": "zone_id"
},
"stop": true,
"table": "admin"
},
"channel": {
"sql": {
"admin_id": "id",
"org_id": "org_id",
"zone_id": "zone_id"
},
"stop": false,
"table": "channel"
},
"company": {
"sql": {
"admin_id": "id",
"org_id": "org_id",
"zone_id": "zone_id"
},
"stop": false,
"table": "company"
},
"logs": {
"sql": {
"admin_id": "id"
},
"stop": false,
"table": "logs"
},
"org": {
"sql": {
"admin_id": "id",
"parent_ids[~]": "%,org_id,%",
"zone_id": "zone_id"
},
"stop": true,
"table": "org"
},
"proj": {
"sql": {
"admin_id": "id",
"org_id": "org_id",
"sc_admin_id": "sc_admin_id",
"xm_admin_id": "xm_admin_id",
"zone_id": "zone_id"
},
"stop": false,
"table": "proj"
},
"role": {
"sql": {
"id": "role_id"
},
"stop": true,
"table": "role"
},
"sea": {
"sql": {
"admin_id": "id"
},
"stop": false,
"table": "sea"
},
"task": {
"sql": {
"admin_id": "id",
"zone_id": "zone_id"
},
"stop": false,
"table": "task"
},
"task_admin": {
"sql": {
"admin_id": "id",
"zone_id": "zone_id"
},
"stop": false,
"table": "task_admin"
},
"user": {
"sql": {
"admin_id": "id",
"zone_id": "zone_id"
},
"stop": false,
"table": "user"
},
"wechat": {
"sql": {
"admin_id": "id",
"org_id": "org_id"
},
"stop": false,
"table": "wechat"
},
"zone": {
"sql": {
"parent_ids[~]": "%,zone_id,%"
},
"stop": true,
"table": "zone"
}
},
"id": "023d5002b1e2c64ed744a12ac442c00e",
"label": "HoTime管理平台",
"labelConfig": {
"add": "添加",
"delete": "删除",
"download": "下载清单",
"edit": "编辑",
"info": "查看详情",
"show": "开启"
},
"menus": [
{
"auth": [
"show"
],
"icon": "Setting",
"label": "系统管理",
"menus": [
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "角色管理",
"table": "role"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "联络人管理",
"table": "user"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "项目分类",
"table": "category"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "标签管理",
"table": "out_tag"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "考勤管理",
"table": "time_tag"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "车辆管理",
"table": "car"
},
{
"auth": [
"show",
"download"
],
"label": "日志管理",
"table": "logs"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "系统设置",
"table": "system"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "标签管理",
"table": "visit_tag"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "城市管理",
"table": "city"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "项目管理",
"table": "proj"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "客户管理",
"table": "company"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "项目归口",
"table": "department"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "部门管理",
"table": "org"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "用章管理",
"table": "seal_tag"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "微信信息",
"table": "wechat"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "联盟公司",
"table": "zone"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "人员管理",
"table": "admin"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "供应商管理",
"table": "channel"
}
],
"name": "sys"
},
{
"auth": [
"show"
],
"icon": "Setting",
"label": "任务执行",
"menus": [
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "任务执行",
"table": "task_admin"
},
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "任务管理",
"table": "task"
}
],
"name": "sys:task"
},
{
"auth": [
"show"
],
"icon": "Setting",
"label": "跟进管理",
"menus": [
{
"auth": [
"show",
"add",
"delete",
"edit",
"info",
"download"
],
"label": "跟进管理",
"table": "sea"
}
],
"name": "sys:sea"
}
],
"name": "admin",
"stop": [
"role",
"org"
]
}

6567
example/config/adminDB.json Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,9 @@
{
"avatarPath": "avatar/2006/01/02/",
"cache": {
"db": {
"db": false,
"session": true
"session": true,
"timeout": 7200
},
"memory": {
"db": true,
@ -11,24 +11,22 @@
"timeout": 7200
}
},
"codeConfig": {
"admin": "config/app.json"
},
"codeConfig1": {
"admin": {
"config": "config/app.json",
"package": "admin",
"rule": "config/rule.json"
"codeConfig": [
{
"config": "config/admin.json",
"configDB": "config/adminDB.json",
"mode": 0,
"name": "",
"rule": "config/rule.json",
"table": "admin"
}
},
"crossDomain": "auto",
],
"db": {
"mysql": {
"host": "192.168.6.253",
"name": "iedc_dev",
"name": "rfcb",
"password": "dasda8454456",
"port": "3306",
"prefix": "",
"user": "root"
}
},
@ -43,14 +41,8 @@
"4": "数据处理异常",
"5": "数据结果异常"
},
"imgPath": "img/2006/01/02/",
"mode": 3,
"mode": 2,
"port": "8081",
"sessionName": "HOTIME",
"smsKey": "b0eb4bf0198b9983cffcb85b69fdf4fa",
"smsLogin": "【政企超链接】您的验证码为:{code}请在5分钟内使用切勿将验证码泄露于他人如非本人操作请忽略。",
"tpt": "tpt",
"wechatAppID": "wx2edb802f5c3ae1ae",
"wechatAppSecret": "4ff97e523c3de6bad47051b568522386",
"wxFilePath": "wxfile/2006/01/02/"
"tpt": "tpt"
}

View File

@ -20,10 +20,17 @@
},
"注释": "可配置memorydbredis默认启用memory默认优先级为memory\u003eredis\u003edb,memory与数据库缓存设置项一致缓存数据填充会自动反方向反哺加入memory缓存过期将自动从redis更新但memory永远不会更新redis如果是集群建议不要开启memory配置即启用"
},
"codeConfig": {
"packageName": "默认无必须包名称以及应用名生成代码的配置文件地址比如config/app.json数据库有更新时自动更新配置文件以及对应的生成文件",
"注释": "配置即启用,非必须,默认无"
},
"codeConfig": [
"注释:配置即启用,非必须,默认无",
{
"config": "默认config/app.json必须接口描述配置文件",
"configDB": "默认无,非必须,有则每次将数据库数据生成到此目录用于配置读写,无则不生成",
"mode": "默认0非必须0为内嵌代码模式1为生成代码模式",
"name": "默认无非必须有则生成代码到此目录无则采用缺省模式使用表名如设置为admin将在admin目录生成包名为admin的代码",
"rule": "默认config/rule.json非必须有则按改规则生成接口无则按系统内嵌方式生成",
"table": "默认admin必须根据数据库内当前表名做为用户生成数据"
}
],
"crossDomain": "默认空 非必须空字符串为不开启如果需要跨域设置auto为智能开启所有网站允许跨域http://www.baidu.com为指定域允许跨域",
"db": {
"mysql": {

Binary file not shown.

Binary file not shown.

422
example/config/rule.json Normal file
View File

@ -0,0 +1,422 @@
[
{
"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": false,
"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

@ -1,15 +1,17 @@
package main
import (
"../../hotime"
//"../dri/aliyun"
"fmt"
"time"
. "code.hoteas.com/golang/hotime"
)
func main() {
date, _ := time.Parse("2006-01-02 15:04", time.Now().Format("2006-01-02")+" 14:00")
fmt.Println(date, date.Unix())
//fmt.Println("0123456"[1:7])
appIns := hotime.Init("config/config.json")
appIns := Init("config/config.json")
appIns.SetConnectListener(func(that *Context) (isFinished bool) {
return isFinished
})
appIns.Run(Router{})
}

17
go.mod Normal file
View File

@ -0,0 +1,17 @@
module code.hoteas.com/golang/hotime
go 1.16
require (
github.com/360EntSecGroup-Skylar/excelize v1.4.1
github.com/garyburd/redigo v1.6.3
github.com/go-pay/gopay v1.5.78
github.com/go-sql-driver/mysql v1.6.0
github.com/mattn/go-sqlite3 v1.14.12
github.com/silenceper/wechat/v2 v2.1.2
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
)

107
go.sum Normal file
View File

@ -0,0 +1,107 @@
github.com/360EntSecGroup-Skylar/excelize v1.4.1 h1:l55mJb6rkkaUzOpSsgEeKYtS6/0gHwBYyfo5Jcjv/Ks=
github.com/360EntSecGroup-Skylar/excelize v1.4.1/go.mod h1:vnax29X2usfl7HHkBrX5EvSCJcmH3dT9luvxzu8iGAE=
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b h1:L/QXpzIa3pOvUGt1D1lA5KjYhPBAN/3iWdP7xeFS9F0=
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
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/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/garyburd/redigo v1.6.3 h1:HCeeRluvAgMusMomi1+6Y5dmFOdYV/JzoRrrbFlkGIc=
github.com/garyburd/redigo v1.6.3/go.mod h1:rTb6epsqigu3kYKBnaF028A7Tf/Aw5s0cqA47doKKqw=
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=
github.com/mattn/go-sqlite3 v1.14.12 h1:TJ1bhYJPV44phC+IMu1u2K/i5RriLTPe+yc68XDJ1Z0=
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=
github.com/silenceper/wechat/v2 v2.1.2/go.mod h1:0OprxYCCp2CZAKw06BBlnaczInTk2KxOLsKeiopshGg=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
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=
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
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

@ -82,10 +82,29 @@ func findCaller(skip int) string {
for i := 0; i < 10; i++ {
file, line = getCaller(skip + i)
if !strings.HasPrefix(file, "logrus") {
if file == "common/error.go" {
file, line = getCaller(skip + i + 1)
j := 0
for true {
j++
if file == "common/error.go" {
file, line = getCaller(skip + i + j)
}
if file == "db/hotimedb.go" {
file, line = getCaller(skip + i + j)
}
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)
}
if j == 5 {
break
}
}
break
}
}

View File

@ -44,17 +44,17 @@ func Run() {
appIns.Run(hotime.Router{
"app": hotime.Proj{
"index": hotime.Ctr{
"test": func(this *hotime.Context) {
fmt.Println(this.Db.GetTag())
//x := this.Db.Action(func(db hotime.HoTimeDB) bool {
"test": func(that *hotime.Context) {
fmt.Println(that.Db.GetTag())
//x := that.Db.Action(func(db hotime.HoTimeDB) bool {
//
// db.Insert("user", hotime.Map{"unickname": "dasdas"})
//
// return true
//})
this.Display(0, 1)
that.Display(0, 1)
},
"websocket": func(this *hotime.Context) {
"websocket": func(that *hotime.Context) {
hdler := websocket.Handler(func(ws *websocket.Conn) {
for true {
msg := make([]byte, 5120)
@ -73,7 +73,7 @@ func Run() {
fmt.Printf("Send: %s\n", msg[:m])
}
})
hdler.ServeHTTP(this.Resp, this.Req)
hdler.ServeHTTP(that.Resp, that.Req)
},
},
},

View File

@ -1,8 +1,8 @@
package hotime
import (
. "./cache"
. "./common"
. "code.hoteas.com/golang/hotime/cache"
. "code.hoteas.com/golang/hotime/common"
)
//session对象

View File

@ -5,4 +5,4 @@ type Ctr map[string]Method
type Proj map[string]Ctr
type Router map[string]Proj
type MethodRouter map[string]Method //直接字符串关联函数
type Method func(this *Context)
type Method func(that *Context)

46
var.go
View File

@ -1,7 +1,7 @@
package hotime
import (
. "./common"
. "code.hoteas.com/golang/hotime/common"
)
var IsRun = false //当前状态
@ -10,15 +10,17 @@ var App = map[string]*Application{} //整个项目
//var Db = HoTimeDB{} //数据库实例
var Config = Map{
"mode": 3, //模式 0生产模式1测试模式2开发模式,3内嵌代码模式
"codeConfig": Map{
"admin": "config/app.json",
},
"codeConfig1": Map{
"admin": Map{ //默认无,必须,接口类别名称
"package": "admin", //默认admin非必须有则生成代码到此目录无则采用缺省模式不生成代码只生成接口
"config": "config/app.json", //默认config/app.json必须接口描述配置文件
"rule": "config/rule.json", //默认config/rule.json非必须有则按改规则生成接口无则按系统内嵌方式生成
"mode": 2, //模式 0生产模式1测试模式2开发模式
//"codeConfig": Map{
// "admin": "config/app.json",
//},
"codeConfig": Slice{
Map{
"table": "admin", //默认admin必须有则根据数据库内当前表名做为用户生成数据
"name": "", //默认admin非必须有则生成代码到此目录无则采用缺省模式使用表名
"config": "config/app.json", //默认config/app.json必须接口描述配置文件无则自动生成
"rule": "config/rule.json", //默认config/rule.json非必须有则按改规则生成接口无则按系统内嵌方式生成
"mode": 0, //默认0非必须0为内嵌代码模式1为生成代码模式
},
},
"db": Map{
@ -52,12 +54,24 @@ var ConfigNote = Map{
"webConnectLogShow": "默认true非必须访问日志如果需要web访问链接、访问ip、访问时间打印false为关闭true开启此功能",
"webConnectLogFile": "无默认非必须webConnectLogShow开启之后才能使用如果需要存储日志文件时使用保存格式为:a/b/c/20060102150405.txt,将生成a/b/c/年月日时分秒.txt按需设置",
"mode": "默认0,非必须0生产模式1测试模式2开发模式3内嵌代码模式在开发模式下会显示更多的数据用于开发测试并能够辅助研发自动生成配置文件、代码等功能,web无缓存数据库不启用缓存", //debug 0关闭1开启
"codeConfig": Map{
"注释": "配置即启用,非必须,默认无",
//"package":"默认admin必须mode模式为2时会自动生成包文件夹和代码文件",
//"path":""
"packageName": "默认无必须包名称以及应用名生成代码的配置文件地址比如config/app.json数据库有更新时自动更新配置文件以及对应的生成文件",
//"codeConfig": Map{
// "注释": "配置即启用,非必须,默认无",
// //"package":"默认admin必须mode模式为2时会自动生成包文件夹和代码文件",
// //"path":""
//
// "packageName": "默认无必须包名称以及应用名生成代码的配置文件地址比如config/app.json数据库有更新时自动更新配置文件以及对应的生成文件",
//},
"codeConfig": Slice{
"注释:配置即启用,非必须,默认无",
Map{ //默认无,必须,接口类别名称
//"注释": "", //
"table": "默认admin必须根据数据库内当前表名做为用户生成数据",
"name": "默认无非必须有则生成代码到此目录无则采用缺省模式使用表名如设置为admin将在admin目录生成包名为admin的代码",
"config": "默认config/app.json必须接口描述配置文件", //
"configDB": "默认无,非必须,有则每次将数据库数据生成到此目录用于配置读写,无则不生成", //
"rule": "默认config/rule.json非必须有则按改规则生成接口无则按系统内嵌方式生成",
"mode": "默认0非必须0为内嵌代码模式1为生成代码模式",
},
},
"db": Map{
"注释": "配置即启用非必须默认使用sqlite数据库",

View File

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

View File

@ -0,0 +1,26 @@
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

@ -0,0 +1,46 @@
# 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

@ -0,0 +1,464 @@
<!-- 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

@ -0,0 +1,384 @@
<!-- 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

@ -0,0 +1,29 @@
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

@ -0,0 +1,45 @@
# 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

@ -0,0 +1,179 @@
<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

@ -0,0 +1,179 @@
<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

@ -0,0 +1,599 @@
// 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)
}

1291
vendor/github.com/360EntSecGroup-Skylar/excelize/chart.go generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

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

376
vendor/github.com/360EntSecGroup-Skylar/excelize/col.go generated vendored Normal file
View File

@ -0,0 +1,376 @@
// 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

@ -0,0 +1,273 @@
// 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

@ -0,0 +1,233 @@
// 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

@ -0,0 +1,151 @@
// 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

@ -0,0 +1,456 @@
// 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.

After

Width:  |  Height:  |  Size: 62 KiB

View File

@ -0,0 +1,106 @@
// 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

@ -0,0 +1,8 @@
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

@ -0,0 +1,8 @@
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=

139
vendor/github.com/360EntSecGroup-Skylar/excelize/hsl.go generated vendored Normal file
View File

@ -0,0 +1,139 @@
// 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
}

229
vendor/github.com/360EntSecGroup-Skylar/excelize/lib.go generated vendored Normal file
View File

@ -0,0 +1,229 @@
// 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.

After

Width:  |  Height:  |  Size: 6.9 KiB

View File

@ -0,0 +1,533 @@
// 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

@ -0,0 +1,510 @@
// 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

@ -0,0 +1,428 @@
// 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

@ -0,0 +1,792 @@
// 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

@ -0,0 +1,168 @@
// 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

@ -0,0 +1,171 @@
// 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

@ -0,0 +1,461 @@
// 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

@ -0,0 +1,144 @@
// 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

@ -0,0 +1,623 @@
// 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

@ -0,0 +1,72 @@
// 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"`
}

View File

@ -0,0 +1,35 @@
// 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"
// xlsxTypes directly maps the types element of content types for relationship
// parts, it takes a Multipurpose Internet Mail Extension (MIME) media type as a
// value.
type xlsxTypes struct {
XMLName xml.Name `xml:"http://schemas.openxmlformats.org/package/2006/content-types Types"`
Overrides []xlsxOverride `xml:"Override"`
Defaults []xlsxDefault `xml:"Default"`
}
// xlsxOverride directly maps the override element in the namespace
// http://schemas.openxmlformats.org/package/2006/content-types
type xlsxOverride struct {
PartName string `xml:",attr"`
ContentType string `xml:",attr"`
}
// xlsxDefault directly maps the default element in the namespace
// http://schemas.openxmlformats.org/package/2006/content-types
type xlsxDefault struct {
Extension string `xml:",attr"`
ContentType string `xml:",attr"`
}

View File

@ -0,0 +1,196 @@
// 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"
// decodeCellAnchor directly maps the oneCellAnchor (One Cell Anchor Shape Size)
// and twoCellAnchor (Two Cell Anchor Shape Size). This element specifies a two
// cell anchor placeholder for a group, a shape, or a drawing element. It moves
// with cells and its extents are in EMU units.
type decodeCellAnchor struct {
EditAs string `xml:"editAs,attr,omitempty"`
Content string `xml:",innerxml"`
}
// decodeWsDr directly maps the root element for a part of this content type
// shall wsDr. In order to solve the problem that the label structure is changed
// after serialization and deserialization, two different structures are
// defined. decodeWsDr just for deserialization.
type decodeWsDr struct {
A string `xml:"xmlns a,attr"`
Xdr string `xml:"xmlns xdr,attr"`
R string `xml:"xmlns r,attr"`
OneCellAnchor []*decodeCellAnchor `xml:"oneCellAnchor,omitempty"`
TwoCellAnchor []*decodeCellAnchor `xml:"twoCellAnchor,omitempty"`
XMLName xml.Name `xml:"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing wsDr,omitempty"`
}
// decodeTwoCellAnchor directly maps the oneCellAnchor (One Cell Anchor Shape
// Size) and twoCellAnchor (Two Cell Anchor Shape Size). This element specifies
// a two cell anchor placeholder for a group, a shape, or a drawing element. It
// moves with cells and its extents are in EMU units.
type decodeTwoCellAnchor struct {
From *decodeFrom `xml:"from"`
To *decodeTo `xml:"to"`
Pic *decodePic `xml:"pic,omitempty"`
ClientData *decodeClientData `xml:"clientData"`
}
// decodeCNvPr directly maps the cNvPr (Non-Visual Drawing Properties). This
// element specifies non-visual canvas properties. This allows for additional
// information that does not affect the appearance of the picture to be stored.
type decodeCNvPr struct {
ID int `xml:"id,attr"`
Name string `xml:"name,attr"`
Descr string `xml:"descr,attr"`
Title string `xml:"title,attr,omitempty"`
}
// decodePicLocks directly maps the picLocks (Picture Locks). This element
// specifies all locking properties for a graphic frame. These properties inform
// the generating application about specific properties that have been
// previously locked and thus should not be changed.
type decodePicLocks struct {
NoAdjustHandles bool `xml:"noAdjustHandles,attr,omitempty"`
NoChangeArrowheads bool `xml:"noChangeArrowheads,attr,omitempty"`
NoChangeAspect bool `xml:"noChangeAspect,attr"`
NoChangeShapeType bool `xml:"noChangeShapeType,attr,omitempty"`
NoCrop bool `xml:"noCrop,attr,omitempty"`
NoEditPoints bool `xml:"noEditPoints,attr,omitempty"`
NoGrp bool `xml:"noGrp,attr,omitempty"`
NoMove bool `xml:"noMove,attr,omitempty"`
NoResize bool `xml:"noResize,attr,omitempty"`
NoRot bool `xml:"noRot,attr,omitempty"`
NoSelect bool `xml:"noSelect,attr,omitempty"`
}
// decodeBlip directly maps the blip element in the namespace
// http://purl.oclc.org/ooxml/officeDoc ument/relationships - This element
// specifies the existence of an image (binary large image or picture) and
// contains a reference to the image data.
type decodeBlip struct {
Embed string `xml:"embed,attr"`
Cstate string `xml:"cstate,attr,omitempty"`
R string `xml:"r,attr"`
}
// decodeStretch directly maps the stretch element. This element specifies that
// a BLIP should be stretched to fill the target rectangle. The other option is
// a tile where a BLIP is tiled to fill the available area.
type decodeStretch struct {
FillRect string `xml:"fillRect"`
}
// decodeOff directly maps the colOff and rowOff element. This element is used
// to specify the column offset within a cell.
type decodeOff struct {
X int `xml:"x,attr"`
Y int `xml:"y,attr"`
}
// decodeExt directly maps the ext element.
type decodeExt struct {
Cx int `xml:"cx,attr"`
Cy int `xml:"cy,attr"`
}
// decodePrstGeom directly maps the prstGeom (Preset geometry). This element
// specifies when a preset geometric shape should be used instead of a custom
// geometric shape. The generating application should be able to render all
// preset geometries enumerated in the ST_ShapeType list.
type decodePrstGeom struct {
Prst string `xml:"prst,attr"`
}
// decodeXfrm directly maps the xfrm (2D Transform for Graphic Frame). This
// element specifies the transform to be applied to the corresponding graphic
// frame. This transformation is applied to the graphic frame just as it would
// be for a shape or group shape.
type decodeXfrm struct {
Off decodeOff `xml:"off"`
Ext decodeExt `xml:"ext"`
}
// decodeCNvPicPr directly maps the cNvPicPr (Non-Visual Picture Drawing
// Properties). This element specifies the non-visual properties for the picture
// canvas. These properties are to be used by the generating application to
// determine how certain properties are to be changed for the picture object in
// question.
type decodeCNvPicPr struct {
PicLocks decodePicLocks `xml:"picLocks"`
}
// directly maps the nvPicPr (Non-Visual Properties for a Picture). This element
// specifies all non-visual properties for a picture. This element is a
// container for the non-visual identification properties, shape properties and
// application properties that are to be associated with a picture. This allows
// for additional information that does not affect the appearance of the picture
// to be stored.
type decodeNvPicPr struct {
CNvPr decodeCNvPr `xml:"cNvPr"`
CNvPicPr decodeCNvPicPr `xml:"cNvPicPr"`
}
// decodeBlipFill directly maps the blipFill (Picture Fill). This element
// specifies the kind of picture fill that the picture object has. Because a
// picture has a picture fill already by default, it is possible to have two
// fills specified for a picture object.
type decodeBlipFill struct {
Blip decodeBlip `xml:"blip"`
Stretch decodeStretch `xml:"stretch"`
}
// decodeSpPr directly maps the spPr (Shape Properties). This element specifies
// the visual shape properties that can be applied to a picture. These are the
// same properties that are allowed to describe the visual properties of a shape
// but are used here to describe the visual appearance of a picture within a
// document.
type decodeSpPr struct {
Xfrm decodeXfrm `xml:"a:xfrm"`
PrstGeom decodePrstGeom `xml:"a:prstGeom"`
}
// decodePic elements encompass the definition of pictures within the DrawingML
// framework. While pictures are in many ways very similar to shapes they have
// specific properties that are unique in order to optimize for picture-
// specific scenarios.
type decodePic struct {
NvPicPr decodeNvPicPr `xml:"nvPicPr"`
BlipFill decodeBlipFill `xml:"blipFill"`
SpPr decodeSpPr `xml:"spPr"`
}
// decodeFrom specifies the starting anchor.
type decodeFrom struct {
Col int `xml:"col"`
ColOff int `xml:"colOff"`
Row int `xml:"row"`
RowOff int `xml:"rowOff"`
}
// decodeTo directly specifies the ending anchor.
type decodeTo struct {
Col int `xml:"col"`
ColOff int `xml:"colOff"`
Row int `xml:"row"`
RowOff int `xml:"rowOff"`
}
// decodeClientData directly maps the clientData element. An empty element which
// specifies (via attributes) certain properties related to printing and
// selection of the drawing object. The fLocksWithSheet attribute (either true
// or false) determines whether to disable selection when the sheet is
// protected, and fPrintsWithSheet attribute (either true or false) determines
// whether the object is printed when the sheet is printed.
type decodeClientData struct {
FLocksWithSheet bool `xml:"fLocksWithSheet,attr"`
FPrintsWithSheet bool `xml:"fPrintsWithSheet,attr"`
}

View File

@ -0,0 +1,402 @@
// 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"
// Source relationship and namespace.
const (
SourceRelationship = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
SourceRelationshipChart = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart"
SourceRelationshipComments = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"
SourceRelationshipImage = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"
SourceRelationshipTable = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/table"
SourceRelationshipDrawingML = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing"
SourceRelationshipDrawingVML = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing"
SourceRelationshipHyperLink = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"
SourceRelationshipWorkSheet = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"
SourceRelationshipChart201506 = "http://schemas.microsoft.com/office/drawing/2015/06/chart"
SourceRelationshipChart20070802 = "http://schemas.microsoft.com/office/drawing/2007/8/2/chart"
SourceRelationshipChart2014 = "http://schemas.microsoft.com/office/drawing/2014/chart"
SourceRelationshipCompatibility = "http://schemas.openxmlformats.org/markup-compatibility/2006"
NameSpaceDrawingML = "http://schemas.openxmlformats.org/drawingml/2006/main"
NameSpaceDrawingMLChart = "http://schemas.openxmlformats.org/drawingml/2006/chart"
NameSpaceDrawingMLSpreadSheet = "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"
NameSpaceSpreadSheet = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
NameSpaceXML = "http://www.w3.org/XML/1998/namespace"
StrictSourceRelationship = "http://purl.oclc.org/ooxml/officeDocument/relationships"
StrictSourceRelationshipChart = "http://purl.oclc.org/ooxml/officeDocument/relationships/chart"
StrictSourceRelationshipComments = "http://purl.oclc.org/ooxml/officeDocument/relationships/comments"
StrictSourceRelationshipImage = "http://purl.oclc.org/ooxml/officeDocument/relationships/image"
StrictNameSpaceSpreadSheet = "http://purl.oclc.org/ooxml/spreadsheetml/main"
)
var supportImageTypes = map[string]string{".gif": ".gif", ".jpg": ".jpeg", ".jpeg": ".jpeg", ".png": ".png"}
// xlsxCNvPr directly maps the cNvPr (Non-Visual Drawing Properties). This
// element specifies non-visual canvas properties. This allows for additional
// information that does not affect the appearance of the picture to be stored.
type xlsxCNvPr struct {
ID int `xml:"id,attr"`
Name string `xml:"name,attr"`
Descr string `xml:"descr,attr"`
Title string `xml:"title,attr,omitempty"`
HlinkClick *xlsxHlinkClick `xml:"a:hlinkClick"`
}
// xlsxHlinkClick (Click Hyperlink) Specifies the on-click hyperlink
// information to be applied to a run of text. When the hyperlink text is
// clicked the link is fetched.
type xlsxHlinkClick struct {
R string `xml:"xmlns:r,attr,omitempty"`
RID string `xml:"r:id,attr,omitempty"`
InvalidURL string `xml:"invalidUrl,attr,omitempty"`
Action string `xml:"action,attr,omitempty"`
TgtFrame string `xml:"tgtFrame,attr,omitempty"`
Tooltip string `xml:"tooltip,attr,omitempty"`
History bool `xml:"history,attr,omitempty"`
HighlightClick bool `xml:"highlightClick,attr,omitempty"`
EndSnd bool `xml:"endSnd,attr,omitempty"`
}
// xlsxPicLocks directly maps the picLocks (Picture Locks). This element
// specifies all locking properties for a graphic frame. These properties inform
// the generating application about specific properties that have been
// previously locked and thus should not be changed.
type xlsxPicLocks struct {
NoAdjustHandles bool `xml:"noAdjustHandles,attr,omitempty"`
NoChangeArrowheads bool `xml:"noChangeArrowheads,attr,omitempty"`
NoChangeAspect bool `xml:"noChangeAspect,attr"`
NoChangeShapeType bool `xml:"noChangeShapeType,attr,omitempty"`
NoCrop bool `xml:"noCrop,attr,omitempty"`
NoEditPoints bool `xml:"noEditPoints,attr,omitempty"`
NoGrp bool `xml:"noGrp,attr,omitempty"`
NoMove bool `xml:"noMove,attr,omitempty"`
NoResize bool `xml:"noResize,attr,omitempty"`
NoRot bool `xml:"noRot,attr,omitempty"`
NoSelect bool `xml:"noSelect,attr,omitempty"`
}
// xlsxBlip directly maps the blip element in the namespace
// http://purl.oclc.org/ooxml/officeDoc ument/relationships - This element
// specifies the existence of an image (binary large image or picture) and
// contains a reference to the image data.
type xlsxBlip struct {
Embed string `xml:"r:embed,attr"`
Cstate string `xml:"cstate,attr,omitempty"`
R string `xml:"xmlns:r,attr"`
}
// xlsxStretch directly maps the stretch element. This element specifies that a
// BLIP should be stretched to fill the target rectangle. The other option is a
// tile where a BLIP is tiled to fill the available area.
type xlsxStretch struct {
FillRect string `xml:"a:fillRect"`
}
// xlsxOff directly maps the colOff and rowOff element. This element is used to
// specify the column offset within a cell.
type xlsxOff struct {
X int `xml:"x,attr"`
Y int `xml:"y,attr"`
}
// xlsxExt directly maps the ext element.
type xlsxExt struct {
Cx int `xml:"cx,attr"`
Cy int `xml:"cy,attr"`
}
// xlsxPrstGeom directly maps the prstGeom (Preset geometry). This element
// specifies when a preset geometric shape should be used instead of a custom
// geometric shape. The generating application should be able to render all
// preset geometries enumerated in the ST_ShapeType list.
type xlsxPrstGeom struct {
Prst string `xml:"prst,attr"`
}
// xlsxXfrm directly maps the xfrm (2D Transform for Graphic Frame). This
// element specifies the transform to be applied to the corresponding graphic
// frame. This transformation is applied to the graphic frame just as it would
// be for a shape or group shape.
type xlsxXfrm struct {
Off xlsxOff `xml:"a:off"`
Ext xlsxExt `xml:"a:ext"`
}
// xlsxCNvPicPr directly maps the cNvPicPr (Non-Visual Picture Drawing
// Properties). This element specifies the non-visual properties for the picture
// canvas. These properties are to be used by the generating application to
// determine how certain properties are to be changed for the picture object in
// question.
type xlsxCNvPicPr struct {
PicLocks xlsxPicLocks `xml:"a:picLocks"`
}
// directly maps the nvPicPr (Non-Visual Properties for a Picture). This element
// specifies all non-visual properties for a picture. This element is a
// container for the non-visual identification properties, shape properties and
// application properties that are to be associated with a picture. This allows
// for additional information that does not affect the appearance of the picture
// to be stored.
type xlsxNvPicPr struct {
CNvPr xlsxCNvPr `xml:"xdr:cNvPr"`
CNvPicPr xlsxCNvPicPr `xml:"xdr:cNvPicPr"`
}
// xlsxBlipFill directly maps the blipFill (Picture Fill). This element
// specifies the kind of picture fill that the picture object has. Because a
// picture has a picture fill already by default, it is possible to have two
// fills specified for a picture object.
type xlsxBlipFill struct {
Blip xlsxBlip `xml:"a:blip"`
Stretch xlsxStretch `xml:"a:stretch"`
}
// xlsxSpPr directly maps the spPr (Shape Properties). This element specifies
// the visual shape properties that can be applied to a picture. These are the
// same properties that are allowed to describe the visual properties of a shape
// but are used here to describe the visual appearance of a picture within a
// document.
type xlsxSpPr struct {
Xfrm xlsxXfrm `xml:"a:xfrm"`
PrstGeom xlsxPrstGeom `xml:"a:prstGeom"`
}
// xlsxPic elements encompass the definition of pictures within the DrawingML
// framework. While pictures are in many ways very similar to shapes they have
// specific properties that are unique in order to optimize for picture-
// specific scenarios.
type xlsxPic struct {
NvPicPr xlsxNvPicPr `xml:"xdr:nvPicPr"`
BlipFill xlsxBlipFill `xml:"xdr:blipFill"`
SpPr xlsxSpPr `xml:"xdr:spPr"`
}
// xlsxFrom specifies the starting anchor.
type xlsxFrom struct {
Col int `xml:"xdr:col"`
ColOff int `xml:"xdr:colOff"`
Row int `xml:"xdr:row"`
RowOff int `xml:"xdr:rowOff"`
}
// xlsxTo directly specifies the ending anchor.
type xlsxTo struct {
Col int `xml:"xdr:col"`
ColOff int `xml:"xdr:colOff"`
Row int `xml:"xdr:row"`
RowOff int `xml:"xdr:rowOff"`
}
// xdrClientData directly maps the clientData element. An empty element which
// specifies (via attributes) certain properties related to printing and
// selection of the drawing object. The fLocksWithSheet attribute (either true
// or false) determines whether to disable selection when the sheet is
// protected, and fPrintsWithSheet attribute (either true or false) determines
// whether the object is printed when the sheet is printed.
type xdrClientData struct {
FLocksWithSheet bool `xml:"fLocksWithSheet,attr"`
FPrintsWithSheet bool `xml:"fPrintsWithSheet,attr"`
}
// xdrCellAnchor directly maps the oneCellAnchor (One Cell Anchor Shape Size)
// and twoCellAnchor (Two Cell Anchor Shape Size). This element specifies a two
// cell anchor placeholder for a group, a shape, or a drawing element. It moves
// with cells and its extents are in EMU units.
type xdrCellAnchor struct {
EditAs string `xml:"editAs,attr,omitempty"`
From *xlsxFrom `xml:"xdr:from"`
To *xlsxTo `xml:"xdr:to"`
Ext *xlsxExt `xml:"xdr:ext"`
Sp *xdrSp `xml:"xdr:sp"`
Pic *xlsxPic `xml:"xdr:pic,omitempty"`
GraphicFrame string `xml:",innerxml"`
ClientData *xdrClientData `xml:"xdr:clientData"`
}
// xlsxWsDr directly maps the root element for a part of this content type shall
// wsDr.
type xlsxWsDr struct {
XMLName xml.Name `xml:"xdr:wsDr"`
OneCellAnchor []*xdrCellAnchor `xml:"xdr:oneCellAnchor"`
TwoCellAnchor []*xdrCellAnchor `xml:"xdr:twoCellAnchor"`
A string `xml:"xmlns:a,attr,omitempty"`
Xdr string `xml:"xmlns:xdr,attr,omitempty"`
R string `xml:"xmlns:r,attr,omitempty"`
}
// xlsxGraphicFrame (Graphic Frame) directly maps the xdr:graphicFrame element.
// This element specifies the existence of a graphics frame. This frame contains
// a graphic that was generated by an external source and needs a container in
// which to be displayed on the slide surface.
type xlsxGraphicFrame struct {
XMLName xml.Name `xml:"xdr:graphicFrame"`
Macro string `xml:"macro,attr"`
NvGraphicFramePr xlsxNvGraphicFramePr `xml:"xdr:nvGraphicFramePr"`
Xfrm xlsxXfrm `xml:"xdr:xfrm"`
Graphic *xlsxGraphic `xml:"a:graphic"`
}
// xlsxNvGraphicFramePr (Non-Visual Properties for a Graphic Frame) directly
// maps the xdr:nvGraphicFramePr element. This element specifies all non-visual
// properties for a graphic frame. This element is a container for the non-
// visual identification properties, shape properties and application properties
// that are to be associated with a graphic frame. This allows for additional
// information that does not affect the appearance of the graphic frame to be
// stored.
type xlsxNvGraphicFramePr struct {
CNvPr *xlsxCNvPr `xml:"xdr:cNvPr"`
ChicNvGraphicFramePr string `xml:"xdr:cNvGraphicFramePr"`
}
// xlsxGraphic (Graphic Object) directly maps the a:graphic element. This
// element specifies the existence of a single graphic object. Document authors
// should refer to this element when they wish to persist a graphical object of
// some kind. The specification for this graphical object is provided entirely
// by the document author and referenced within the graphicData child element.
type xlsxGraphic struct {
GraphicData *xlsxGraphicData `xml:"a:graphicData"`
}
// xlsxGraphicData (Graphic Object Data) directly maps the a:graphicData
// element. This element specifies the reference to a graphic object within the
// document. This graphic object is provided entirely by the document authors
// who choose to persist this data within the document.
type xlsxGraphicData struct {
URI string `xml:"uri,attr"`
Chart *xlsxChart `xml:"c:chart,omitempty"`
}
// xlsxChart (Chart) directly maps the c:chart element.
type xlsxChart struct {
C string `xml:"xmlns:c,attr"`
RID string `xml:"r:id,attr"`
R string `xml:"xmlns:r,attr"`
}
// xdrSp (Shape) directly maps the xdr:sp element. This element specifies the
// existence of a single shape. A shape can either be a preset or a custom
// geometry, defined using the SpreadsheetDrawingML framework. In addition to a
// geometry each shape can have both visual and non-visual properties attached.
// Text and corresponding styling information can also be attached to a shape.
// This shape is specified along with all other shapes within either the shape
// tree or group shape elements.
type xdrSp struct {
Macro string `xml:"macro,attr"`
Textlink string `xml:"textlink,attr"`
NvSpPr *xdrNvSpPr `xml:"xdr:nvSpPr"`
SpPr *xlsxSpPr `xml:"xdr:spPr"`
Style *xdrStyle `xml:"xdr:style"`
TxBody *xdrTxBody `xml:"xdr:txBody"`
}
// xdrNvSpPr (Non-Visual Properties for a Shape) directly maps the xdr:nvSpPr
// element. This element specifies all non-visual properties for a shape. This
// element is a container for the non-visual identification properties, shape
// properties and application properties that are to be associated with a shape.
// This allows for additional information that does not affect the appearance of
// the shape to be stored.
type xdrNvSpPr struct {
CNvPr *xlsxCNvPr `xml:"xdr:cNvPr"`
CNvSpPr *xdrCNvSpPr `xml:"xdr:cNvSpPr"`
}
// xdrCNvSpPr (Connection Non-Visual Shape Properties) directly maps the
// xdr:cNvSpPr element. This element specifies the set of non-visual properties
// for a connection shape. These properties specify all data about the
// connection shape which do not affect its display within a spreadsheet.
type xdrCNvSpPr struct {
TxBox bool `xml:"txBox,attr"`
}
// xdrStyle (Shape Style) directly maps the xdr:style element. The element
// specifies the style that is applied to a shape and the corresponding
// references for each of the style components such as lines and fills.
type xdrStyle struct {
LnRef *aRef `xml:"a:lnRef"`
FillRef *aRef `xml:"a:fillRef"`
EffectRef *aRef `xml:"a:effectRef"`
FontRef *aFontRef `xml:"a:fontRef"`
}
// aRef directly maps the a:lnRef, a:fillRef and a:effectRef element.
type aRef struct {
Idx int `xml:"idx,attr"`
ScrgbClr *aScrgbClr `xml:"a:scrgbClr"`
SchemeClr *attrValString `xml:"a:schemeClr"`
SrgbClr *attrValString `xml:"a:srgbClr"`
}
// aScrgbClr (RGB Color Model - Percentage Variant) directly maps the a:scrgbClr
// element. This element specifies a color using the red, green, blue RGB color
// model. Each component, red, green, and blue is expressed as a percentage from
// 0% to 100%. A linear gamma of 1.0 is assumed.
type aScrgbClr struct {
R float64 `xml:"r,attr"`
G float64 `xml:"g,attr"`
B float64 `xml:"b,attr"`
}
// aFontRef (Font Reference) directly maps the a:fontRef element. This element
// represents a reference to a themed font. When used it specifies which themed
// font to use along with a choice of color.
type aFontRef struct {
Idx string `xml:"idx,attr"`
SchemeClr *attrValString `xml:"a:schemeClr"`
}
// xdrTxBody (Shape Text Body) directly maps the xdr:txBody element. This
// element specifies the existence of text to be contained within the
// corresponding shape. All visible text and visible text related properties are
// contained within this element. There can be multiple paragraphs and within
// paragraphs multiple runs of text.
type xdrTxBody struct {
BodyPr *aBodyPr `xml:"a:bodyPr"`
P []*aP `xml:"a:p"`
}
// formatPicture directly maps the format settings of the picture.
type formatPicture struct {
FPrintsWithSheet bool `json:"print_obj"`
FLocksWithSheet bool `json:"locked"`
NoChangeAspect bool `json:"lock_aspect_ratio"`
OffsetX int `json:"x_offset"`
OffsetY int `json:"y_offset"`
XScale float64 `json:"x_scale"`
YScale float64 `json:"y_scale"`
Hyperlink string `json:"hyperlink"`
HyperlinkType string `json:"hyperlink_type"`
Positioning string `json:"positioning"`
}
// formatShape directly maps the format settings of the shape.
type formatShape struct {
Type string `json:"type"`
Width int `json:"width"`
Height int `json:"height"`
Format formatPicture `json:"format"`
Color formatShapeColor `json:"color"`
Paragraph []formatShapeParagraph `json:"paragraph"`
}
// formatShapeParagraph directly maps the format settings of the paragraph in
// the shape.
type formatShapeParagraph struct {
Font formatFont `json:"font"`
Text string `json:"text"`
}
// formatShapeColor directly maps the color settings of the shape.
type formatShapeColor struct {
Line string `json:"line"`
Fill string `json:"fill"`
Effect string `json:"effect"`
}

View File

@ -0,0 +1,55 @@
// 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"
// xlsxSST directly maps the sst element from the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main. String values may
// be stored directly inside spreadsheet cell elements; however, storing the
// same value inside multiple cell elements can result in very large worksheet
// Parts, possibly resulting in performance degradation. The Shared String Table
// is an indexed list of string values, shared across the workbook, which allows
// implementations to store values only once.
type xlsxSST struct {
XMLName xml.Name `xml:"http://schemas.openxmlformats.org/spreadsheetml/2006/main sst"`
Count int `xml:"count,attr"`
UniqueCount int `xml:"uniqueCount,attr"`
SI []xlsxSI `xml:"si"`
}
// xlsxSI directly maps the si element from the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked this for completeness - it does as much as I need.
type xlsxSI struct {
T string `xml:"t"`
R []xlsxR `xml:"r"`
}
// xlsxR directly maps the r element from the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked this for completeness - it does as much as I need.
type xlsxR struct {
RPr *xlsxRPr `xml:"rPr"`
T string `xml:"t"`
}
// xlsxRPr (Run Properties) 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 xlsxRPr struct {
B string `xml:"b,omitempty"`
Sz *attrValFloat `xml:"sz"`
Color *xlsxColor `xml:"color"`
RFont *attrValString `xml:"rFont"`
Family *attrValInt `xml:"family"`
}

View File

@ -0,0 +1,365 @@
// 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"
// xlsxStyleSheet directly maps the stylesheet element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked it for completeness - it does as much as I need.
type xlsxStyleSheet struct {
XMLName xml.Name `xml:"http://schemas.openxmlformats.org/spreadsheetml/2006/main styleSheet"`
NumFmts *xlsxNumFmts `xml:"numFmts,omitempty"`
Fonts *xlsxFonts `xml:"fonts,omitempty"`
Fills *xlsxFills `xml:"fills,omitempty"`
Borders *xlsxBorders `xml:"borders,omitempty"`
CellStyleXfs *xlsxCellStyleXfs `xml:"cellStyleXfs,omitempty"`
CellXfs *xlsxCellXfs `xml:"cellXfs,omitempty"`
CellStyles *xlsxCellStyles `xml:"cellStyles,omitempty"`
Dxfs *xlsxDxfs `xml:"dxfs,omitempty"`
TableStyles *xlsxTableStyles `xml:"tableStyles,omitempty"`
Colors *xlsxStyleColors `xml:"colors,omitempty"`
ExtLst *xlsxExtLst `xml:"extLst"`
}
// xlsxAlignment formatting information pertaining to text alignment in cells.
// There are a variety of choices for how text is aligned both horizontally and
// vertically, as well as indentation settings, and so on.
type xlsxAlignment struct {
Horizontal string `xml:"horizontal,attr,omitempty"`
Indent int `xml:"indent,attr,omitempty"`
JustifyLastLine bool `xml:"justifyLastLine,attr,omitempty"`
ReadingOrder uint64 `xml:"readingOrder,attr,omitempty"`
RelativeIndent int `xml:"relativeIndent,attr,omitempty"`
ShrinkToFit bool `xml:"shrinkToFit,attr,omitempty"`
TextRotation int `xml:"textRotation,attr,omitempty"`
Vertical string `xml:"vertical,attr,omitempty"`
WrapText bool `xml:"wrapText,attr,omitempty"`
}
// xlsxProtection (Protection Properties) contains protection properties
// associated with the cell. Each cell has protection properties that can be
// set. The cell protection properties do not take effect unless the sheet has
// been protected.
type xlsxProtection struct {
Hidden bool `xml:"hidden,attr"`
Locked bool `xml:"locked,attr"`
}
// xlsxLine directly maps the line style element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked it for completeness - it does as much as I need.
type xlsxLine struct {
Style string `xml:"style,attr,omitempty"`
Color *xlsxColor `xml:"color,omitempty"`
}
// xlsxColor is a common mapping used for both the fgColor and bgColor elements.
// Foreground color of the cell fill pattern. Cell fill patterns operate with
// two colors: a background color and a foreground color. These combine together
// to make a patterned cell fill. Background color of the cell fill pattern.
// Cell fill patterns operate with two colors: a background color and a
// foreground color. These combine together to make a patterned cell fill.
type xlsxColor struct {
Auto bool `xml:"auto,attr,omitempty"`
RGB string `xml:"rgb,attr,omitempty"`
Indexed int `xml:"indexed,attr,omitempty"`
Theme *int `xml:"theme,attr"`
Tint float64 `xml:"tint,attr,omitempty"`
}
// xlsxFonts directly maps the font element. This element contains all font
// definitions for this workbook.
type xlsxFonts struct {
Count int `xml:"count,attr"`
Font []*xlsxFont `xml:"font"`
}
// font directly maps the font element.
type font struct {
Name *attrValString `xml:"name"`
Charset *attrValInt `xml:"charset"`
Family *attrValInt `xml:"family"`
B bool `xml:"b,omitempty"`
I bool `xml:"i,omitempty"`
Strike bool `xml:"strike,omitempty"`
Outline bool `xml:"outline,omitempty"`
Shadow bool `xml:"shadow,omitempty"`
Condense bool `xml:"condense,omitempty"`
Extend bool `xml:"extend,omitempty"`
Color *xlsxColor `xml:"color"`
Sz *attrValInt `xml:"sz"`
U *attrValString `xml:"u"`
Scheme *attrValString `xml:"scheme"`
}
// xlsxFont directly maps the font element. This element defines the properties
// for one of the fonts used in this workbook.
type xlsxFont struct {
Font string `xml:",innerxml"`
}
// xlsxFills directly maps the fills element. This element defines the cell
// fills portion of the Styles part, consisting of a sequence of fill records. A
// cell fill consists of a background color, foreground color, and pattern to be
// applied across the cell.
type xlsxFills struct {
Count int `xml:"count,attr"`
Fill []*xlsxFill `xml:"fill,omitempty"`
}
// xlsxFill directly maps the fill element. This element specifies fill
// formatting.
type xlsxFill struct {
PatternFill *xlsxPatternFill `xml:"patternFill,omitempty"`
GradientFill *xlsxGradientFill `xml:"gradientFill,omitempty"`
}
// xlsxPatternFill directly maps the patternFill element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked it for completeness - it does as much as I need. This element is
// used to specify cell fill information for pattern and solid color cell fills.
// For solid cell fills (no pattern), fgColor is used. For cell fills with
// patterns specified, then the cell fill color is specified by the bgColor
// element.
type xlsxPatternFill struct {
PatternType string `xml:"patternType,attr,omitempty"`
FgColor xlsxColor `xml:"fgColor,omitempty"`
BgColor xlsxColor `xml:"bgColor,omitempty"`
}
// xlsxGradientFill defines a gradient-style cell fill. Gradient cell fills can
// use one or two colors as the end points of color interpolation.
type xlsxGradientFill struct {
Bottom float64 `xml:"bottom,attr,omitempty"`
Degree float64 `xml:"degree,attr,omitempty"`
Left float64 `xml:"left,attr,omitempty"`
Right float64 `xml:"right,attr,omitempty"`
Top float64 `xml:"top,attr,omitempty"`
Type string `xml:"type,attr,omitempty"`
Stop []*xlsxGradientFillStop `xml:"stop,omitempty"`
}
// xlsxGradientFillStop directly maps the stop element.
type xlsxGradientFillStop struct {
Position float64 `xml:"position,attr"`
Color xlsxColor `xml:"color,omitempty"`
}
// xlsxBorders directly maps the borders element. This element contains borders
// formatting information, specifying all border definitions for all cells in
// the workbook.
type xlsxBorders struct {
Count int `xml:"count,attr"`
Border []*xlsxBorder `xml:"border,omitempty"`
}
// xlsxBorder directly maps the border element. Expresses a single set of cell
// border formats (left, right, top, bottom, diagonal). Color is optional. When
// missing, 'automatic' is implied.
type xlsxBorder struct {
DiagonalDown bool `xml:"diagonalDown,attr,omitempty"`
DiagonalUp bool `xml:"diagonalUp,attr,omitempty"`
Outline bool `xml:"outline,attr,omitempty"`
Left xlsxLine `xml:"left,omitempty"`
Right xlsxLine `xml:"right,omitempty"`
Top xlsxLine `xml:"top,omitempty"`
Bottom xlsxLine `xml:"bottom,omitempty"`
Diagonal xlsxLine `xml:"diagonal,omitempty"`
}
// xlsxCellStyles directly maps the cellStyles element. This element contains
// the named cell styles, consisting of a sequence of named style records. A
// named cell style is a collection of direct or themed formatting (e.g., cell
// border, cell fill, and font type/size/style) grouped together into a single
// named style, and can be applied to a cell.
type xlsxCellStyles struct {
XMLName xml.Name `xml:"cellStyles"`
Count int `xml:"count,attr"`
CellStyle []*xlsxCellStyle `xml:"cellStyle,omitempty"`
}
// xlsxCellStyle directly maps the cellStyle element. This element represents
// the name and related formatting records for a named cell style in this
// workbook.
type xlsxCellStyle struct {
XMLName xml.Name `xml:"cellStyle"`
BuiltInID *int `xml:"builtinId,attr,omitempty"`
CustomBuiltIn *bool `xml:"customBuiltin,attr,omitempty"`
Hidden *bool `xml:"hidden,attr,omitempty"`
ILevel *bool `xml:"iLevel,attr,omitempty"`
Name string `xml:"name,attr"`
XfID int `xml:"xfId,attr"`
}
// xlsxCellStyleXfs directly maps the cellStyleXfs element. This element
// contains the master formatting records (xf's) which define the formatting for
// all named cell styles in this workbook. Master formatting records reference
// individual elements of formatting (e.g., number format, font definitions,
// cell fills, etc) by specifying a zero-based index into those collections.
// Master formatting records also specify whether to apply or ignore particular
// aspects of formatting.
type xlsxCellStyleXfs struct {
Count int `xml:"count,attr"`
Xf []xlsxXf `xml:"xf,omitempty"`
}
// xlsxXf directly maps the xf element. A single xf element describes all of the
// formatting for a cell.
type xlsxXf struct {
ApplyAlignment bool `xml:"applyAlignment,attr"`
ApplyBorder bool `xml:"applyBorder,attr"`
ApplyFill bool `xml:"applyFill,attr"`
ApplyFont bool `xml:"applyFont,attr"`
ApplyNumberFormat bool `xml:"applyNumberFormat,attr"`
ApplyProtection bool `xml:"applyProtection,attr"`
BorderID int `xml:"borderId,attr"`
FillID int `xml:"fillId,attr"`
FontID int `xml:"fontId,attr"`
NumFmtID int `xml:"numFmtId,attr"`
PivotButton bool `xml:"pivotButton,attr,omitempty"`
QuotePrefix bool `xml:"quotePrefix,attr,omitempty"`
XfID *int `xml:"xfId,attr"`
Alignment *xlsxAlignment `xml:"alignment"`
Protection *xlsxProtection `xml:"protection"`
}
// xlsxCellXfs directly maps the cellXfs element. This element contains the
// master formatting records (xf) which define the formatting applied to cells
// in this workbook. These records are the starting point for determining the
// formatting for a cell. Cells in the Sheet Part reference the xf records by
// zero-based index.
type xlsxCellXfs struct {
Count int `xml:"count,attr"`
Xf []xlsxXf `xml:"xf,omitempty"`
}
// xlsxDxfs directly maps the dxfs element. This element contains the master
// differential formatting records (dxf's) which define formatting for all non-
// cell formatting in this workbook. Whereas xf records fully specify a
// particular aspect of formatting (e.g., cell borders) by referencing those
// formatting definitions elsewhere in the Styles part, dxf records specify
// incremental (or differential) aspects of formatting directly inline within
// the dxf element. The dxf formatting is to be applied on top of or in addition
// to any formatting already present on the object using the dxf record.
type xlsxDxfs struct {
Count int `xml:"count,attr"`
Dxfs []*xlsxDxf `xml:"dxf,omitempty"`
}
// xlsxDxf directly maps the dxf element. A single dxf record, expressing
// incremental formatting to be applied.
type xlsxDxf struct {
Dxf string `xml:",innerxml"`
}
// dxf directly maps the dxf element.
type dxf struct {
Font *font `xml:"font"`
NumFmt *xlsxNumFmt `xml:"numFmt"`
Fill *xlsxFill `xml:"fill"`
Alignment *xlsxAlignment `xml:"alignment"`
Border *xlsxBorder `xml:"border"`
Protection *xlsxProtection `xml:"protection"`
ExtLst *xlsxExt `xml:"extLst"`
}
// xlsxTableStyles directly maps the tableStyles element. This element
// represents a collection of Table style definitions for Table styles and
// PivotTable styles used in this workbook. It consists of a sequence of
// tableStyle records, each defining a single Table style.
type xlsxTableStyles struct {
Count int `xml:"count,attr"`
DefaultPivotStyle string `xml:"defaultPivotStyle,attr"`
DefaultTableStyle string `xml:"defaultTableStyle,attr"`
TableStyles []*xlsxTableStyle `xml:"tableStyle,omitempty"`
}
// xlsxTableStyle directly maps the tableStyle element. This element represents
// a single table style definition that indicates how a spreadsheet application
// should format and display a table.
type xlsxTableStyle struct {
Name string `xml:"name,attr,omitempty"`
Pivot int `xml:"pivot,attr"`
Count int `xml:"count,attr,omitempty"`
Table bool `xml:"table,attr,omitempty"`
TableStyleElement string `xml:",innerxml"`
}
// xlsxNumFmts directly maps the numFmts element. This element defines the
// number formats in this workbook, consisting of a sequence of numFmt records,
// where each numFmt record defines a particular number format, indicating how
// to format and render the numeric value of a cell.
type xlsxNumFmts struct {
Count int `xml:"count,attr"`
NumFmt []*xlsxNumFmt `xml:"numFmt,omitempty"`
}
// xlsxNumFmt directly maps the numFmt element. This element specifies number
// format properties which indicate how to format and render the numeric value
// of a cell.
type xlsxNumFmt struct {
NumFmtID int `xml:"numFmtId,attr,omitempty"`
FormatCode string `xml:"formatCode,attr,omitempty"`
}
// xlsxStyleColors directly maps the colors element. Color information
// associated with this stylesheet. This collection is written whenever the
// legacy color palette has been modified (backwards compatibility settings) or
// a custom color has been selected while using this workbook.
type xlsxStyleColors struct {
Color string `xml:",innerxml"`
}
// formatFont directly maps the styles settings of the fonts.
type formatFont struct {
Bold bool `json:"bold"`
Italic bool `json:"italic"`
Underline string `json:"underline"`
Family string `json:"family"`
Size int `json:"size"`
Color string `json:"color"`
}
// formatStyle directly maps the styles settings of the cells.
type formatStyle struct {
Border []struct {
Type string `json:"type"`
Color string `json:"color"`
Style int `json:"style"`
} `json:"border"`
Fill struct {
Type string `json:"type"`
Pattern int `json:"pattern"`
Color []string `json:"color"`
Shading int `json:"shading"`
} `json:"fill"`
Font *formatFont `json:"font"`
Alignment *struct {
Horizontal string `json:"horizontal"`
Indent int `json:"indent"`
JustifyLastLine bool `json:"justify_last_line"`
ReadingOrder uint64 `json:"reading_order"`
RelativeIndent int `json:"relative_indent"`
ShrinkToFit bool `json:"shrink_to_fit"`
TextRotation int `json:"text_rotation"`
Vertical string `json:"vertical"`
WrapText bool `json:"wrap_text"`
} `json:"alignment"`
Protection *struct {
Hidden bool `json:"hidden"`
Locked bool `json:"locked"`
} `json:"protection"`
NumFmt int `json:"number_format"`
DecimalPlaces int `json:"decimal_places"`
CustomNumFmt *string `json:"custom_number_format"`
Lang string `json:"lang"`
NegRed bool `json:"negred"`
}

View File

@ -0,0 +1,214 @@
// 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"
// xlsxTable directly maps the table element. A table helps organize and provide
// structure to lists of information in a worksheet. Tables have clearly labeled
// columns, rows, and data regions. Tables make it easier for users to sort,
// analyze, format, manage, add, and delete information. This element is the
// root element for a table that is not a single cell XML table.
type xlsxTable struct {
XMLName xml.Name `xml:"table"`
XMLNS string `xml:"xmlns,attr"`
DataCellStyle string `xml:"dataCellStyle,attr,omitempty"`
DataDxfID int `xml:"dataDxfId,attr,omitempty"`
DisplayName string `xml:"displayName,attr,omitempty"`
HeaderRowBorderDxfID int `xml:"headerRowBorderDxfId,attr,omitempty"`
HeaderRowCellStyle string `xml:"headerRowCellStyle,attr,omitempty"`
HeaderRowCount int `xml:"headerRowCount,attr,omitempty"`
HeaderRowDxfID int `xml:"headerRowDxfId,attr,omitempty"`
ID int `xml:"id,attr"`
InsertRow bool `xml:"insertRow,attr,omitempty"`
InsertRowShift bool `xml:"insertRowShift,attr,omitempty"`
Name string `xml:"name,attr"`
Published bool `xml:"published,attr,omitempty"`
Ref string `xml:"ref,attr"`
TotalsRowCount int `xml:"totalsRowCount,attr,omitempty"`
TotalsRowDxfID int `xml:"totalsRowDxfId,attr,omitempty"`
TotalsRowShown bool `xml:"totalsRowShown,attr"`
AutoFilter *xlsxAutoFilter `xml:"autoFilter"`
TableColumns *xlsxTableColumns `xml:"tableColumns"`
TableStyleInfo *xlsxTableStyleInfo `xml:"tableStyleInfo"`
}
// xlsxAutoFilter temporarily hides rows based on a filter criteria, which is
// applied column by column to a table of data in the worksheet. This collection
// expresses AutoFilter settings.
type xlsxAutoFilter struct {
Ref string `xml:"ref,attr"`
FilterColumn *xlsxFilterColumn `xml:"filterColumn"`
}
// xlsxFilterColumn directly maps the filterColumn element. The filterColumn
// collection identifies a particular column in the AutoFilter range and
// specifies filter information that has been applied to this column. If a
// column in the AutoFilter range has no criteria specified, then there is no
// corresponding filterColumn collection expressed for that column.
type xlsxFilterColumn struct {
ColID int `xml:"colId,attr"`
HiddenButton bool `xml:"hiddenButton,attr,omitempty"`
ShowButton bool `xml:"showButton,attr,omitempty"`
CustomFilters *xlsxCustomFilters `xml:"customFilters"`
Filters *xlsxFilters `xml:"filters"`
ColorFilter *xlsxColorFilter `xml:"colorFilter"`
DynamicFilter *xlsxDynamicFilter `xml:"dynamicFilter"`
IconFilter *xlsxIconFilter `xml:"iconFilter"`
Top10 *xlsxTop10 `xml:"top10"`
}
// xlsxCustomFilters directly maps the customFilters element. When there is more
// than one custom filter criteria to apply (an 'and' or 'or' joining two
// criteria), then this element groups the customFilter elements together.
type xlsxCustomFilters struct {
And bool `xml:"and,attr,omitempty"`
CustomFilter []*xlsxCustomFilter `xml:"customFilter"`
}
// xlsxCustomFilter directly maps the customFilter element. A custom AutoFilter
// specifies an operator and a value. There can be at most two customFilters
// specified, and in that case the parent element specifies whether the two
// conditions are joined by 'and' or 'or'. For any cells whose values do not
// meet the specified criteria, the corresponding rows shall be hidden from view
// when the filter is applied.
type xlsxCustomFilter struct {
Operator string `xml:"operator,attr,omitempty"`
Val string `xml:"val,attr,omitempty"`
}
// xlsxFilters directly maps the filters (Filter Criteria) element. When
// multiple values are chosen to filter by, or when a group of date values are
// chosen to filter by, this element groups those criteria together.
type xlsxFilters struct {
Blank bool `xml:"blank,attr,omitempty"`
CalendarType string `xml:"calendarType,attr,omitempty"`
Filter []*xlsxFilter `xml:"filter"`
DateGroupItem []*xlsxDateGroupItem `xml:"dateGroupItem"`
}
// xlsxFilter directly maps the filter element. This element expresses a filter
// criteria value.
type xlsxFilter struct {
Val string `xml:"val,attr,omitempty"`
}
// xlsxColorFilter directly maps the colorFilter element. This element specifies
// the color to filter by and whether to use the cell's fill or font color in
// the filter criteria. If the cell's font or fill color does not match the
// color specified in the criteria, the rows corresponding to those cells are
// hidden from view.
type xlsxColorFilter struct {
CellColor bool `xml:"cellColor,attr"`
DxfID int `xml:"dxfId,attr"`
}
// xlsxDynamicFilter directly maps the dynamicFilter element. This collection
// specifies dynamic filter criteria. These criteria are considered dynamic
// because they can change, either with the data itself (e.g., "above average")
// or with the current system date (e.g., show values for "today"). For any
// cells whose values do not meet the specified criteria, the corresponding rows
// shall be hidden from view when the filter is applied.
type xlsxDynamicFilter struct {
MaxValISO string `xml:"maxValIso,attr,omitempty"`
Type string `xml:"type,attr,omitempty"`
Val float64 `xml:"val,attr,omitempty"`
ValISO string `xml:"valIso,attr,omitempty"`
}
// xlsxIconFilter directly maps the iconFilter element. This element specifies
// the icon set and particular icon within that set to filter by. For any cells
// whose icon does not match the specified criteria, the corresponding rows
// shall be hidden from view when the filter is applied.
type xlsxIconFilter struct {
IconID int `xml:"iconId,attr"`
IconSet string `xml:"iconSet,attr,omitempty"`
}
// xlsxTop10 directly maps the top10 element. This element specifies the top N
// (percent or number of items) to filter by.
type xlsxTop10 struct {
FilterVal float64 `xml:"filterVal,attr,omitempty"`
Percent bool `xml:"percent,attr,omitempty"`
Top bool `xml:"top,attr"`
Val float64 `xml:"val,attr,omitempty"`
}
// xlsxDateGroupItem directly maps the dateGroupItem element. This collection is
// used to express a group of dates or times which are used in an AutoFilter
// criteria. [Note: See parent element for an example. end note] Values are
// always written in the calendar type of the first date encountered in the
// filter range, so that all subsequent dates, even when formatted or
// represented by other calendar types, can be correctly compared for the
// purposes of filtering.
type xlsxDateGroupItem struct {
DateTimeGrouping string `xml:"dateTimeGrouping,attr,omitempty"`
Day int `xml:"day,attr,omitempty"`
Hour int `xml:"hour,attr,omitempty"`
Minute int `xml:"minute,attr,omitempty"`
Month int `xml:"month,attr,omitempty"`
Second int `xml:"second,attr,omitempty"`
Year int `xml:"year,attr,omitempty"`
}
// xlsxTableColumns directly maps the element representing the collection of all
// table columns for this table.
type xlsxTableColumns struct {
Count int `xml:"count,attr"`
TableColumn []*xlsxTableColumn `xml:"tableColumn"`
}
// xlsxTableColumn directly maps the element representing a single column for
// this table.
type xlsxTableColumn struct {
DataCellStyle string `xml:"dataCellStyle,attr,omitempty"`
DataDxfID int `xml:"dataDxfId,attr,omitempty"`
HeaderRowCellStyle string `xml:"headerRowCellStyle,attr,omitempty"`
HeaderRowDxfID int `xml:"headerRowDxfId,attr,omitempty"`
ID int `xml:"id,attr"`
Name string `xml:"name,attr"`
QueryTableFieldID int `xml:"queryTableFieldId,attr,omitempty"`
TotalsRowCellStyle string `xml:"totalsRowCellStyle,attr,omitempty"`
TotalsRowDxfID int `xml:"totalsRowDxfId,attr,omitempty"`
TotalsRowFunction string `xml:"totalsRowFunction,attr,omitempty"`
TotalsRowLabel string `xml:"totalsRowLabel,attr,omitempty"`
UniqueName string `xml:"uniqueName,attr,omitempty"`
}
// xlsxTableStyleInfo directly maps the tableStyleInfo element. This element
// describes which style is used to display this table, and specifies which
// portions of the table have the style applied.
type xlsxTableStyleInfo struct {
Name string `xml:"name,attr,omitempty"`
ShowFirstColumn bool `xml:"showFirstColumn,attr"`
ShowLastColumn bool `xml:"showLastColumn,attr"`
ShowRowStripes bool `xml:"showRowStripes,attr"`
ShowColumnStripes bool `xml:"showColumnStripes,attr"`
}
// formatTable directly maps the format settings of the table.
type formatTable struct {
TableName string `json:"table_name"`
TableStyle string `json:"table_style"`
ShowFirstColumn bool `json:"show_first_column"`
ShowLastColumn bool `json:"show_last_column"`
ShowRowStripes bool `json:"show_row_stripes"`
ShowColumnStripes bool `json:"show_column_stripes"`
}
// formatAutoFilter directly maps the auto filter settings.
type formatAutoFilter struct {
Column string `json:"column"`
Expression string `json:"expression"`
FilterList []struct {
Column string `json:"column"`
Value []int `json:"value"`
} `json:"filter_list"`
}

View File

@ -0,0 +1,149 @@
// 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"
// xlsxTheme directly maps the theme element in the namespace
// http://schemas.openxmlformats.org/drawingml/2006/main
type xlsxTheme struct {
ThemeElements xlsxThemeElements `xml:"themeElements"`
ObjectDefaults xlsxObjectDefaults `xml:"objectDefaults"`
ExtraClrSchemeLst xlsxExtraClrSchemeLst `xml:"extraClrSchemeLst"`
ExtLst *xlsxExtLst `xml:"extLst"`
}
// objectDefaults element allows for the definition of default shape, line,
// and textbox formatting properties. An application can use this information
// to format a shape (or text) initially on insertion into a document.
type xlsxObjectDefaults struct {
ObjectDefaults string `xml:",innerxml"`
}
// xlsxExtraClrSchemeLst element is a container for the list of extra color
// schemes present in a document.
type xlsxExtraClrSchemeLst struct {
ExtraClrSchemeLst string `xml:",innerxml"`
}
// xlsxThemeElements directly maps the element defines the theme formatting
// options for the theme and is the workhorse of the theme. This is where the
// bulk of the shared theme information is contained and used by a document.
// This element contains the color scheme, font scheme, and format scheme
// elements which define the different formatting aspects of what a theme
// defines.
type xlsxThemeElements struct {
ClrScheme xlsxClrScheme `xml:"clrScheme"`
FontScheme xlsxFontScheme `xml:"fontScheme"`
FmtScheme xlsxFmtScheme `xml:"fmtScheme"`
}
// xlsxClrScheme element specifies the theme color, stored in the document's
// Theme part to which the value of this theme color shall be mapped. This
// mapping enables multiple theme colors to be chained together.
type xlsxClrScheme struct {
Name string `xml:"name,attr"`
Children []xlsxClrSchemeEl `xml:",any"`
}
// xlsxFontScheme element defines the font scheme within the theme. The font
// scheme consists of a pair of major and minor fonts for which to use in a
// document. The major font corresponds well with the heading areas of a
// document, and the minor font corresponds well with the normal text or
// paragraph areas.
type xlsxFontScheme struct {
Name string `xml:"name,attr"`
MajorFont xlsxMajorFont `xml:"majorFont"`
MinorFont xlsxMinorFont `xml:"minorFont"`
ExtLst *xlsxExtLst `xml:"extLst"`
}
// xlsxMajorFont element defines the set of major fonts which are to be used
// under different languages or locals.
type xlsxMajorFont struct {
Children []xlsxFontSchemeEl `xml:",any"`
}
// xlsxMinorFont element defines the set of minor fonts that are to be used
// under different languages or locals.
type xlsxMinorFont struct {
Children []xlsxFontSchemeEl `xml:",any"`
}
// xlsxFmtScheme element contains the background fill styles, effect styles,
// fill styles, and line styles which define the style matrix for a theme. The
// style matrix consists of subtle, moderate, and intense fills, lines, and
// effects. The background fills are not generally thought of to directly be
// associated with the matrix, but do play a role in the style of the overall
// document. Usually, a given object chooses a single line style, a single
// fill style, and a single effect style in order to define the overall final
// look of the object.
type xlsxFmtScheme struct {
Name string `xml:"name,attr"`
FillStyleLst xlsxFillStyleLst `xml:"fillStyleLst"`
LnStyleLst xlsxLnStyleLst `xml:"lnStyleLst"`
EffectStyleLst xlsxEffectStyleLst `xml:"effectStyleLst"`
BgFillStyleLst xlsxBgFillStyleLst `xml:"bgFillStyleLst"`
}
// xlsxFillStyleLst element defines a set of three fill styles that are used
// within a theme. The three fill styles are arranged in order from subtle to
// moderate to intense.
type xlsxFillStyleLst struct {
FillStyleLst string `xml:",innerxml"`
}
// xlsxLnStyleLst element defines a list of three line styles for use within a
// theme. The three line styles are arranged in order from subtle to moderate
// to intense versions of lines. This list makes up part of the style matrix.
type xlsxLnStyleLst struct {
LnStyleLst string `xml:",innerxml"`
}
// xlsxEffectStyleLst element defines a set of three effect styles that create
// the effect style list for a theme. The effect styles are arranged in order
// of subtle to moderate to intense.
type xlsxEffectStyleLst struct {
EffectStyleLst string `xml:",innerxml"`
}
// xlsxBgFillStyleLst element defines a list of background fills that are
// used within a theme. The background fills consist of three fills, arranged
// in order from subtle to moderate to intense.
type xlsxBgFillStyleLst struct {
BgFillStyleLst string `xml:",innerxml"`
}
// xlsxClrScheme maps to children of the clrScheme element in the namespace
// http://schemas.openxmlformats.org/drawingml/2006/main - currently I have
// not checked it for completeness - it does as much as I need.
type xlsxClrSchemeEl struct {
XMLName xml.Name
SysClr *xlsxSysClr `xml:"sysClr"`
SrgbClr *attrValString `xml:"srgbClr"`
}
// xlsxFontSchemeEl directly maps the major and minor font of the style's font
// scheme.
type xlsxFontSchemeEl struct {
XMLName xml.Name
Script string `xml:"script,attr,omitempty"`
Typeface string `xml:"typeface,attr"`
Panose string `xml:"panose,attr,omitempty"`
PitchFamily string `xml:"pitchFamily,attr,omitempty"`
Charset string `xml:"charset,attr,omitempty"`
}
// xlsxSysClr element specifies a color bound to predefined operating system
// elements.
type xlsxSysClr struct {
Val string `xml:"val,attr"`
LastClr string `xml:"lastClr,attr"`
}

View File

@ -0,0 +1,291 @@
// 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"
// xmlxWorkbookRels contains xmlxWorkbookRelations which maps sheet id and sheet XML.
type xlsxWorkbookRels struct {
XMLName xml.Name `xml:"http://schemas.openxmlformats.org/package/2006/relationships Relationships"`
Relationships []xlsxWorkbookRelation `xml:"Relationship"`
}
// xmlxWorkbookRelation maps sheet id and xl/worksheets/_rels/sheet%d.xml.rels
type xlsxWorkbookRelation struct {
ID string `xml:"Id,attr"`
Target string `xml:",attr"`
Type string `xml:",attr"`
TargetMode string `xml:",attr,omitempty"`
}
// xlsxWorkbook directly maps the workbook element from the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked it for completeness - it does as much as I need.
type xlsxWorkbook struct {
XMLName xml.Name `xml:"http://schemas.openxmlformats.org/spreadsheetml/2006/main workbook"`
FileVersion *xlsxFileVersion `xml:"fileVersion"`
WorkbookPr *xlsxWorkbookPr `xml:"workbookPr"`
WorkbookProtection *xlsxWorkbookProtection `xml:"workbookProtection"`
BookViews xlsxBookViews `xml:"bookViews"`
Sheets xlsxSheets `xml:"sheets"`
ExternalReferences *xlsxExternalReferences `xml:"externalReferences"`
DefinedNames *xlsxDefinedNames `xml:"definedNames"`
CalcPr *xlsxCalcPr `xml:"calcPr"`
CustomWorkbookViews *xlsxCustomWorkbookViews `xml:"customWorkbookViews"`
PivotCaches *xlsxPivotCaches `xml:"pivotCaches"`
ExtLst *xlsxExtLst `xml:"extLst"`
FileRecoveryPr *xlsxFileRecoveryPr `xml:"fileRecoveryPr"`
}
// xlsxFileRecoveryPr maps sheet recovery information. This element defines
// properties that track the state of the workbook file, such as whether the
// file was saved during a crash, or whether it should be opened in auto-recover
// mode.
type xlsxFileRecoveryPr struct {
AutoRecover bool `xml:"autoRecover,attr,omitempty"`
CrashSave bool `xml:"crashSave,attr,omitempty"`
DataExtractLoad bool `xml:"dataExtractLoad,attr,omitempty"`
RepairLoad bool `xml:"repairLoad,attr,omitempty"`
}
// xlsxWorkbookProtection directly maps the workbookProtection element. This
// element specifies options for protecting data in the workbook. Applications
// might use workbook protection to prevent anyone from accidentally changing,
// moving, or deleting important data. This protection can be ignored by
// applications which choose not to support this optional protection mechanism.
// When a password is to be hashed and stored in this element, it shall be
// hashed as defined below, starting from a UTF-16LE encoded string value. If
// there is a leading BOM character (U+FEFF) in the encoded password it is
// removed before hash calculation.
type xlsxWorkbookProtection struct {
LockRevision bool `xml:"lockRevision,attr,omitempty"`
LockStructure bool `xml:"lockStructure,attr,omitempty"`
LockWindows bool `xml:"lockWindows,attr,omitempty"`
RevisionsAlgorithmName string `xml:"revisionsAlgorithmName,attr,omitempty"`
RevisionsHashValue string `xml:"revisionsHashValue,attr,omitempty"`
RevisionsSaltValue string `xml:"revisionsSaltValue,attr,omitempty"`
RevisionsSpinCount int `xml:"revisionsSpinCount,attr,omitempty"`
WorkbookAlgorithmName string `xml:"workbookAlgorithmName,attr,omitempty"`
WorkbookHashValue string `xml:"workbookHashValue,attr,omitempty"`
WorkbookSaltValue string `xml:"workbookSaltValue,attr,omitempty"`
WorkbookSpinCount int `xml:"workbookSpinCount,attr,omitempty"`
}
// xlsxFileVersion directly maps the fileVersion element. This element defines
// properties that track which version of the application accessed the data and
// source code contained in the file.
type xlsxFileVersion struct {
AppName string `xml:"appName,attr,omitempty"`
CodeName string `xml:"codeName,attr,omitempty"`
LastEdited string `xml:"lastEdited,attr,omitempty"`
LowestEdited string `xml:"lowestEdited,attr,omitempty"`
RupBuild string `xml:"rupBuild,attr,omitempty"`
}
// xlsxWorkbookPr directly maps the workbookPr element from the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main This element
// defines a collection of workbook properties.
type xlsxWorkbookPr struct {
AllowRefreshQuery bool `xml:"allowRefreshQuery,attr,omitempty"`
AutoCompressPictures bool `xml:"autoCompressPictures,attr,omitempty"`
BackupFile bool `xml:"backupFile,attr,omitempty"`
CheckCompatibility bool `xml:"checkCompatibility,attr,omitempty"`
CodeName string `xml:"codeName,attr,omitempty"`
Date1904 bool `xml:"date1904,attr,omitempty"`
DefaultThemeVersion string `xml:"defaultThemeVersion,attr,omitempty"`
FilterPrivacy bool `xml:"filterPrivacy,attr,omitempty"`
HidePivotFieldList bool `xml:"hidePivotFieldList,attr,omitempty"`
PromptedSolutions bool `xml:"promptedSolutions,attr,omitempty"`
PublishItems bool `xml:"publishItems,attr,omitempty"`
RefreshAllConnections bool `xml:"refreshAllConnections,attr,omitempty"`
SaveExternalLinkValues bool `xml:"saveExternalLinkValues,attr,omitempty"`
ShowBorderUnselectedTables bool `xml:"showBorderUnselectedTables,attr,omitempty"`
ShowInkAnnotation bool `xml:"showInkAnnotation,attr,omitempty"`
ShowObjects string `xml:"showObjects,attr,omitempty"`
ShowPivotChartFilter bool `xml:"showPivotChartFilter,attr,omitempty"`
UpdateLinks string `xml:"updateLinks,attr,omitempty"`
}
// xlsxBookViews directly maps the bookViews element. This element specifies the
// collection of workbook views of the enclosing workbook. Each view can specify
// a window position, filter options, and other configurations. There is no
// limit on the number of workbook views that can be defined for a workbook.
type xlsxBookViews struct {
WorkBookView []xlsxWorkBookView `xml:"workbookView"`
}
// xlsxWorkBookView directly maps the workbookView element from the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main This element
// specifies a single Workbook view.
type xlsxWorkBookView struct {
ActiveTab int `xml:"activeTab,attr,omitempty"`
AutoFilterDateGrouping bool `xml:"autoFilterDateGrouping,attr,omitempty"`
FirstSheet int `xml:"firstSheet,attr,omitempty"`
Minimized bool `xml:"minimized,attr,omitempty"`
ShowHorizontalScroll bool `xml:"showHorizontalScroll,attr,omitempty"`
ShowSheetTabs bool `xml:"showSheetTabs,attr,omitempty"`
ShowVerticalScroll bool `xml:"showVerticalScroll,attr,omitempty"`
TabRatio int `xml:"tabRatio,attr,omitempty"`
Visibility string `xml:"visibility,attr,omitempty"`
WindowHeight int `xml:"windowHeight,attr,omitempty"`
WindowWidth int `xml:"windowWidth,attr,omitempty"`
XWindow string `xml:"xWindow,attr,omitempty"`
YWindow string `xml:"yWindow,attr,omitempty"`
}
// xlsxSheets directly maps the sheets element from the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main.
type xlsxSheets struct {
Sheet []xlsxSheet `xml:"sheet"`
}
// xlsxSheet directly maps the sheet element from the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked it for completeness - it does as much as I need.
type xlsxSheet struct {
Name string `xml:"name,attr,omitempty"`
SheetID int `xml:"sheetId,attr,omitempty"`
ID string `xml:"http://schemas.openxmlformats.org/officeDocument/2006/relationships id,attr,omitempty"`
State string `xml:"state,attr,omitempty"`
}
// xlsxExternalReferences directly maps the externalReferences element of the
// external workbook references part.
type xlsxExternalReferences struct {
ExternalReference []xlsxExternalReference `xml:"externalReference"`
}
// xlsxExternalReference directly maps the externalReference element of the
// external workbook references part.
type xlsxExternalReference struct {
RID string `xml:"http://schemas.openxmlformats.org/officeDocument/2006/relationships id,attr,omitempty"`
}
// xlsxPivotCaches element enumerates pivot cache definition parts used by pivot
// tables and formulas in this workbook.
type xlsxPivotCaches struct {
PivotCache []xlsxPivotCache `xml:"pivotCache"`
}
// xlsxPivotCache directly maps the pivotCache element.
type xlsxPivotCache struct {
CacheID int `xml:"cacheId,attr,omitempty"`
RID string `xml:"http://schemas.openxmlformats.org/officeDocument/2006/relationships id,attr,omitempty"`
}
// extLst element provides a convention for extending spreadsheetML in
// predefined locations. The locations shall be denoted with the extLst element,
// and are called extension lists. Extension list locations within the markup
// document are specified in the markup specification and can be used to store
// extensions to the markup specification, whether those are future version
// extensions of the markup specification or are private extensions implemented
// independently from the markup specification. Markup within an extension might
// not be understood by a consumer.
type xlsxExtLst struct {
Ext string `xml:",innerxml"`
}
// xlsxDefinedNames directly maps the definedNames element. This element defines
// the collection of defined names for this workbook. Defined names are
// descriptive names to represent cells, ranges of cells, formulas, or constant
// values. Defined names can be used to represent a range on any worksheet.
type xlsxDefinedNames struct {
DefinedName []xlsxDefinedName `xml:"definedName"`
}
// xlsxDefinedName directly maps the definedName element from the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main This element
// defines a defined name within this workbook. A defined name is descriptive
// text that is used to represents a cell, range of cells, formula, or constant
// value. For a descriptions of the attributes see https://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.definedname.aspx
type xlsxDefinedName struct {
Comment string `xml:"comment,attr,omitempty"`
CustomMenu string `xml:"customMenu,attr,omitempty"`
Description string `xml:"description,attr,omitempty"`
Function bool `xml:"function,attr,omitempty"`
FunctionGroupID int `xml:"functionGroupId,attr,omitempty"`
Help string `xml:"help,attr,omitempty"`
Hidden bool `xml:"hidden,attr,omitempty"`
LocalSheetID *int `xml:"localSheetId,attr"`
Name string `xml:"name,attr,omitempty"`
PublishToServer bool `xml:"publishToServer,attr,omitempty"`
ShortcutKey string `xml:"shortcutKey,attr,omitempty"`
StatusBar string `xml:"statusBar,attr,omitempty"`
VbProcedure bool `xml:"vbProcedure,attr,omitempty"`
WorkbookParameter bool `xml:"workbookParameter,attr,omitempty"`
Xlm bool `xml:"xml,attr,omitempty"`
Data string `xml:",chardata"`
}
// xlsxCalcPr directly maps the calcPr element. This element defines the
// collection of properties the application uses to record calculation status
// and details. Calculation is the process of computing formulas and then
// displaying the results as values in the cells that contain the formulas.
type xlsxCalcPr struct {
CalcCompleted bool `xml:"calcCompleted,attr,omitempty"`
CalcID string `xml:"calcId,attr,omitempty"`
CalcMode string `xml:"calcMode,attr,omitempty"`
CalcOnSave bool `xml:"calcOnSave,attr,omitempty"`
ConcurrentCalc *bool `xml:"concurrentCalc,attr"`
ConcurrentManualCount int `xml:"concurrentManualCount,attr,omitempty"`
ForceFullCalc bool `xml:"forceFullCalc,attr,omitempty"`
FullCalcOnLoad bool `xml:"fullCalcOnLoad,attr,omitempty"`
FullPrecision bool `xml:"fullPrecision,attr,omitempty"`
Iterate bool `xml:"iterate,attr,omitempty"`
IterateCount int `xml:"iterateCount,attr,omitempty"`
IterateDelta float64 `xml:"iterateDelta,attr,omitempty"`
RefMode string `xml:"refMode,attr,omitempty"`
}
// xlsxCustomWorkbookViews defines the collection of custom workbook views that
// are defined for this workbook. A customWorkbookView is similar in concept to
// a workbookView in that its attributes contain settings related to the way
// that the workbook should be displayed on a screen by a spreadsheet
// application.
type xlsxCustomWorkbookViews struct {
CustomWorkbookView []xlsxCustomWorkbookView `xml:"customWorkbookView"`
}
// xlsxCustomWorkbookView directly maps the customWorkbookView element. This
// element specifies a single custom workbook view. A custom workbook view
// consists of a set of display and print settings that you can name and apply
// to a workbook. You can create more than one custom workbook view of the same
// workbook. Custom Workbook Views are not required in order to construct a
// valid SpreadsheetML document, and are not necessary if the document is never
// displayed by a spreadsheet application, or if the spreadsheet application has
// a fixed display for workbooks. However, if a spreadsheet application chooses
// to implement configurable display modes, the customWorkbookView element
// should be used to persist the settings for those display modes.
type xlsxCustomWorkbookView struct {
ActiveSheetID *int `xml:"activeSheetId,attr"`
AutoUpdate *bool `xml:"autoUpdate,attr"`
ChangesSavedWin *bool `xml:"changesSavedWin,attr"`
GUID *string `xml:"guid,attr"`
IncludeHiddenRowCol *bool `xml:"includeHiddenRowCol,attr"`
IncludePrintSettings *bool `xml:"includePrintSettings,attr"`
Maximized *bool `xml:"maximized,attr"`
MergeInterval int `xml:"mergeInterval,attr"`
Minimized *bool `xml:"minimized,attr"`
Name *string `xml:"name,attr"`
OnlySync *bool `xml:"onlySync,attr"`
PersonalView *bool `xml:"personalView,attr"`
ShowComments *string `xml:"showComments,attr"`
ShowFormulaBar *bool `xml:"showFormulaBar,attr"`
ShowHorizontalScroll *bool `xml:"showHorizontalScroll,attr"`
ShowObjects *string `xml:"showObjects,attr"`
ShowSheetTabs *bool `xml:"showSheetTabs,attr"`
ShowStatusbar *bool `xml:"showStatusbar,attr"`
ShowVerticalScroll *bool `xml:"showVerticalScroll,attr"`
TabRatio *int `xml:"tabRatio,attr"`
WindowHeight *int `xml:"windowHeight,attr"`
WindowWidth *int `xml:"windowWidth,attr"`
XWindow *int `xml:"xWindow,attr"`
YWindow *int `xml:"yWindow,attr"`
}

View File

@ -0,0 +1,629 @@
// 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"
// xlsxWorksheet directly maps the worksheet element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked it for completeness - it does as much as I need.
type xlsxWorksheet struct {
XMLName xml.Name `xml:"http://schemas.openxmlformats.org/spreadsheetml/2006/main worksheet"`
SheetPr *xlsxSheetPr `xml:"sheetPr"`
Dimension xlsxDimension `xml:"dimension"`
SheetViews xlsxSheetViews `xml:"sheetViews,omitempty"`
SheetFormatPr *xlsxSheetFormatPr `xml:"sheetFormatPr"`
Cols *xlsxCols `xml:"cols,omitempty"`
SheetData xlsxSheetData `xml:"sheetData"`
SheetProtection *xlsxSheetProtection `xml:"sheetProtection"`
AutoFilter *xlsxAutoFilter `xml:"autoFilter"`
MergeCells *xlsxMergeCells `xml:"mergeCells"`
PhoneticPr *xlsxPhoneticPr `xml:"phoneticPr"`
ConditionalFormatting []*xlsxConditionalFormatting `xml:"conditionalFormatting"`
DataValidations *xlsxDataValidations `xml:"dataValidations,omitempty"`
Hyperlinks *xlsxHyperlinks `xml:"hyperlinks"`
PrintOptions *xlsxPrintOptions `xml:"printOptions"`
PageMargins *xlsxPageMargins `xml:"pageMargins"`
PageSetUp *xlsxPageSetUp `xml:"pageSetup"`
HeaderFooter *xlsxHeaderFooter `xml:"headerFooter"`
Drawing *xlsxDrawing `xml:"drawing"`
LegacyDrawing *xlsxLegacyDrawing `xml:"legacyDrawing"`
Picture *xlsxPicture `xml:"picture"`
TableParts *xlsxTableParts `xml:"tableParts"`
ExtLst *xlsxExtLst `xml:"extLst"`
}
// xlsxDrawing change r:id to rid in the namespace.
type xlsxDrawing struct {
RID string `xml:"http://schemas.openxmlformats.org/officeDocument/2006/relationships id,attr,omitempty"`
}
// xlsxHeaderFooter directly maps the headerFooter element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - When printed or
// viewed in page layout view (§18.18.69), each page of a worksheet can have a
// page header, a page footer, or both. The headers and footers on odd-numbered
// pages can differ from those on even-numbered pages, and the headers and
// footers on the first page can differ from those on odd- and even-numbered
// pages. In the latter case, the first page is not considered an odd page.
type xlsxHeaderFooter struct {
DifferentFirst bool `xml:"differentFirst,attr,omitempty"`
DifferentOddEven bool `xml:"differentOddEven,attr,omitempty"`
OddHeader []*xlsxOddHeader `xml:"oddHeader"`
OddFooter []*xlsxOddFooter `xml:"oddFooter"`
}
// xlsxOddHeader directly maps the oddHeader element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked it for completeness - it does as much as I need.
type xlsxOddHeader struct {
Content string `xml:",chardata"`
}
// xlsxOddFooter directly maps the oddFooter element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked it for completeness - it does as much as I need.
type xlsxOddFooter struct {
Content string `xml:",chardata"`
}
// xlsxPageSetUp directly maps the pageSetup element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - Page setup
// settings for the worksheet.
type xlsxPageSetUp struct {
BlackAndWhite bool `xml:"blackAndWhite,attr,omitempty"`
CellComments string `xml:"cellComments,attr,omitempty"`
Copies int `xml:"copies,attr,omitempty"`
Draft bool `xml:"draft,attr,omitempty"`
Errors string `xml:"errors,attr,omitempty"`
FirstPageNumber int `xml:"firstPageNumber,attr,omitempty"`
FitToHeight *int `xml:"fitToHeight,attr"`
FitToWidth int `xml:"fitToWidth,attr,omitempty"`
HorizontalDPI float32 `xml:"horizontalDpi,attr,omitempty"`
RID string `xml:"http://schemas.openxmlformats.org/officeDocument/2006/relationships id,attr,omitempty"`
Orientation string `xml:"orientation,attr,omitempty"`
PageOrder string `xml:"pageOrder,attr,omitempty"`
PaperHeight string `xml:"paperHeight,attr,omitempty"`
PaperSize string `xml:"paperSize,attr,omitempty"`
PaperWidth string `xml:"paperWidth,attr,omitempty"`
Scale int `xml:"scale,attr,omitempty"`
UseFirstPageNumber bool `xml:"useFirstPageNumber,attr,omitempty"`
UsePrinterDefaults bool `xml:"usePrinterDefaults,attr,omitempty"`
VerticalDPI float32 `xml:"verticalDpi,attr,omitempty"`
}
// xlsxPrintOptions directly maps the printOptions element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - Print options for
// the sheet. Printer-specific settings are stored separately in the Printer
// Settings part.
type xlsxPrintOptions struct {
GridLines bool `xml:"gridLines,attr,omitempty"`
GridLinesSet bool `xml:"gridLinesSet,attr,omitempty"`
Headings bool `xml:"headings,attr,omitempty"`
HorizontalCentered bool `xml:"horizontalCentered,attr,omitempty"`
VerticalCentered bool `xml:"verticalCentered,attr,omitempty"`
}
// xlsxPageMargins directly maps the pageMargins element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - Page margins for
// a sheet or a custom sheet view.
type xlsxPageMargins struct {
Bottom float64 `xml:"bottom,attr"`
Footer float64 `xml:"footer,attr"`
Header float64 `xml:"header,attr"`
Left float64 `xml:"left,attr"`
Right float64 `xml:"right,attr"`
Top float64 `xml:"top,attr"`
}
// xlsxSheetFormatPr directly maps the sheetFormatPr element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main. This element
// specifies the sheet formatting properties.
type xlsxSheetFormatPr struct {
BaseColWidth uint8 `xml:"baseColWidth,attr,omitempty"`
DefaultColWidth float64 `xml:"defaultColWidth,attr,omitempty"`
DefaultRowHeight float64 `xml:"defaultRowHeight,attr"`
CustomHeight bool `xml:"customHeight,attr,omitempty"`
ZeroHeight bool `xml:"zeroHeight,attr,omitempty"`
ThickTop bool `xml:"thickTop,attr,omitempty"`
ThickBottom bool `xml:"thickBottom,attr,omitempty"`
OutlineLevelRow uint8 `xml:"outlineLevelRow,attr,omitempty"`
OutlineLevelCol uint8 `xml:"outlineLevelCol,attr,omitempty"`
}
// xlsxSheetViews directly maps the sheetViews element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - Worksheet views
// collection.
type xlsxSheetViews struct {
SheetView []xlsxSheetView `xml:"sheetView"`
}
// xlsxSheetView directly maps the sheetView element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked it for completeness - it does as much as I need. A single sheet
// view definition. When more than one sheet view is defined in the file, it
// means that when opening the workbook, each sheet view corresponds to a
// separate window within the spreadsheet application, where each window is
// showing the particular sheet containing the same workbookViewId value, the
// last sheetView definition is loaded, and the others are discarded. When
// multiple windows are viewing the same sheet, multiple sheetView elements
// (with corresponding workbookView entries) are saved.
// See https://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.sheetview.aspx
type xlsxSheetView struct {
WindowProtection bool `xml:"windowProtection,attr,omitempty"`
ShowFormulas bool `xml:"showFormulas,attr,omitempty"`
ShowGridLines *bool `xml:"showGridLines,attr"`
ShowRowColHeaders *bool `xml:"showRowColHeaders,attr"`
ShowZeros bool `xml:"showZeros,attr,omitempty"`
RightToLeft bool `xml:"rightToLeft,attr,omitempty"`
TabSelected bool `xml:"tabSelected,attr,omitempty"`
ShowWhiteSpace *bool `xml:"showWhiteSpace,attr"`
ShowOutlineSymbols bool `xml:"showOutlineSymbols,attr,omitempty"`
DefaultGridColor *bool `xml:"defaultGridColor,attr"`
View string `xml:"view,attr,omitempty"`
TopLeftCell string `xml:"topLeftCell,attr,omitempty"`
ColorID int `xml:"colorId,attr,omitempty"`
ZoomScale float64 `xml:"zoomScale,attr,omitempty"`
ZoomScaleNormal float64 `xml:"zoomScaleNormal,attr,omitempty"`
ZoomScalePageLayoutView float64 `xml:"zoomScalePageLayoutView,attr,omitempty"`
ZoomScaleSheetLayoutView float64 `xml:"zoomScaleSheetLayoutView,attr,omitempty"`
WorkbookViewID int `xml:"workbookViewId,attr"`
Pane *xlsxPane `xml:"pane,omitempty"`
Selection []*xlsxSelection `xml:"selection"`
}
// xlsxSelection directly maps the selection element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - Worksheet view
// selection.
type xlsxSelection struct {
ActiveCell string `xml:"activeCell,attr,omitempty"`
ActiveCellID *int `xml:"activeCellId,attr"`
Pane string `xml:"pane,attr,omitempty"`
SQRef string `xml:"sqref,attr,omitempty"`
}
// xlsxSelection directly maps the selection element. Worksheet view pane.
type xlsxPane struct {
ActivePane string `xml:"activePane,attr,omitempty"`
State string `xml:"state,attr,omitempty"` // Either "split" or "frozen"
TopLeftCell string `xml:"topLeftCell,attr,omitempty"`
XSplit float64 `xml:"xSplit,attr,omitempty"`
YSplit float64 `xml:"ySplit,attr,omitempty"`
}
// xlsxSheetPr directly maps the sheetPr element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - Sheet-level
// properties.
type xlsxSheetPr struct {
XMLName xml.Name `xml:"sheetPr"`
CodeName string `xml:"codeName,attr,omitempty"`
EnableFormatConditionsCalculation *bool `xml:"enableFormatConditionsCalculation,attr"`
FilterMode bool `xml:"filterMode,attr,omitempty"`
Published *bool `xml:"published,attr"`
SyncHorizontal bool `xml:"syncHorizontal,attr,omitempty"`
SyncVertical bool `xml:"syncVertical,attr,omitempty"`
TransitionEntry bool `xml:"transitionEntry,attr,omitempty"`
TabColor *xlsxTabColor `xml:"tabColor,omitempty"`
PageSetUpPr *xlsxPageSetUpPr `xml:"pageSetUpPr,omitempty"`
OutlinePr *xlsxOutlinePr `xml:"outlinePr,omitempty"`
}
// xlsxOutlinePr maps to the outlinePr element
// SummaryBelow allows you to adjust the direction of grouper controls
type xlsxOutlinePr struct {
SummaryBelow bool `xml:"summaryBelow,attr"`
}
// xlsxPageSetUpPr directly maps the pageSetupPr element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - Page setup
// properties of the worksheet.
type xlsxPageSetUpPr struct {
AutoPageBreaks bool `xml:"autoPageBreaks,attr,omitempty"`
FitToPage bool `xml:"fitToPage,attr,omitempty"` // Flag indicating whether the Fit to Page print option is enabled.
}
// xlsxTabColor directly maps the tabColor element in the namespace currently I
// have not checked it for completeness - it does as much as I need.
type xlsxTabColor struct {
Theme int `xml:"theme,attr,omitempty"`
Tint float64 `xml:"tint,attr,omitempty"`
}
// xlsxCols directly maps the cols element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked it for completeness - it does as much as I need.
type xlsxCols struct {
Col []xlsxCol `xml:"col"`
}
// xlsxCol directly maps the col (Column Width & Formatting). Defines column
// width and column formatting for one or more columns of the worksheet.
type xlsxCol struct {
BestFit bool `xml:"bestFit,attr,omitempty"`
Collapsed bool `xml:"collapsed,attr"`
CustomWidth bool `xml:"customWidth,attr,omitempty"`
Hidden bool `xml:"hidden,attr"`
Max int `xml:"max,attr"`
Min int `xml:"min,attr"`
OutlineLevel uint8 `xml:"outlineLevel,attr,omitempty"`
Phonetic bool `xml:"phonetic,attr,omitempty"`
Style int `xml:"style,attr"`
Width float64 `xml:"width,attr"`
}
// xlsxDimension directly maps the dimension element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - This element
// specifies the used range of the worksheet. It specifies the row and column
// bounds of used cells in the worksheet. This is optional and is not required.
// Used cells include cells with formulas, text content, and cell formatting.
// When an entire column is formatted, only the first cell in that column is
// considered used.
type xlsxDimension struct {
Ref string `xml:"ref,attr"`
}
// xlsxSheetData directly maps the sheetData element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked it for completeness - it does as much as I need.
type xlsxSheetData struct {
XMLName xml.Name `xml:"sheetData"`
Row []xlsxRow `xml:"row"`
}
// xlsxRow directly maps the row element. The element expresses information
// about an entire row of a worksheet, and contains all cell definitions for a
// particular row in the worksheet.
type xlsxRow struct {
Collapsed bool `xml:"collapsed,attr,omitempty"`
CustomFormat bool `xml:"customFormat,attr,omitempty"`
CustomHeight bool `xml:"customHeight,attr,omitempty"`
Hidden bool `xml:"hidden,attr,omitempty"`
Ht float64 `xml:"ht,attr,omitempty"`
OutlineLevel uint8 `xml:"outlineLevel,attr,omitempty"`
Ph bool `xml:"ph,attr,omitempty"`
R int `xml:"r,attr,omitempty"`
S int `xml:"s,attr,omitempty"`
Spans string `xml:"spans,attr,omitempty"`
ThickBot bool `xml:"thickBot,attr,omitempty"`
ThickTop bool `xml:"thickTop,attr,omitempty"`
C []xlsxC `xml:"c"`
}
// xlsxMergeCell directly maps the mergeCell element. A single merged cell.
type xlsxMergeCell struct {
Ref string `xml:"ref,attr,omitempty"`
}
// xlsxMergeCells directly maps the mergeCells element. This collection
// expresses all the merged cells in the sheet.
type xlsxMergeCells struct {
Count int `xml:"count,attr,omitempty"`
Cells []*xlsxMergeCell `xml:"mergeCell,omitempty"`
}
// xlsxDataValidations expresses all data validation information for cells in a
// sheet which have data validation features applied.
type xlsxDataValidations struct {
Count int `xml:"count,attr,omitempty"`
DisablePrompts bool `xml:"disablePrompts,attr,omitempty"`
XWindow int `xml:"xWindow,attr,omitempty"`
YWindow int `xml:"yWindow,attr,omitempty"`
DataValidation []*DataValidation `xml:"dataValidation"`
}
// DataValidation directly maps the a single item of data validation defined
// on a range of the worksheet.
type DataValidation struct {
AllowBlank bool `xml:"allowBlank,attr"`
Error *string `xml:"error,attr"`
ErrorStyle *string `xml:"errorStyle,attr"`
ErrorTitle *string `xml:"errorTitle,attr"`
Operator string `xml:"operator,attr"`
Prompt *string `xml:"prompt,attr"`
PromptTitle *string `xml:"promptTitle"`
ShowDropDown bool `xml:"showDropDown,attr"`
ShowErrorMessage bool `xml:"showErrorMessage,attr"`
ShowInputMessage bool `xml:"showInputMessage,attr"`
Sqref string `xml:"sqref,attr"`
Type string `xml:"type,attr"`
Formula1 string `xml:"formula1"`
Formula2 string `xml:"formula2"`
}
// xlsxC directly maps the c element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked it for completeness - it does as much as I need.
//
// This simple type is restricted to the values listed in the following table:
//
// Enumeration Value | Description
// ---------------------------+---------------------------------
// b (Boolean) | Cell containing a boolean.
// d (Date) | Cell contains a date in the ISO 8601 format.
// e (Error) | Cell containing an error.
// inlineStr (Inline String) | Cell containing an (inline) rich string, i.e., one not in the shared string table. If this cell type is used, then the cell value is in the is element rather than the v element in the cell (c element).
// n (Number) | Cell containing a number.
// s (Shared String) | Cell containing a shared string.
// str (String) | Cell containing a formula string.
//
type xlsxC struct {
R string `xml:"r,attr"` // Cell ID, e.g. A1
S int `xml:"s,attr,omitempty"` // Style reference.
// Str string `xml:"str,attr,omitempty"` // Style reference.
T string `xml:"t,attr,omitempty"` // Type.
F *xlsxF `xml:"f,omitempty"` // Formula
V string `xml:"v,omitempty"` // Value
IS *xlsxIS `xml:"is"`
XMLSpace xml.Attr `xml:"space,attr,omitempty"`
}
// xlsxIS directly maps the t element. Cell containing an (inline) rich
// string, i.e., one not in the shared string table. If this cell type is
// used, then the cell value is in the is element rather than the v element in
// the cell (c element).
type xlsxIS struct {
T string `xml:"t"`
}
// xlsxF directly maps the f element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - currently I have
// not checked it for completeness - it does as much as I need.
type xlsxF struct {
Content string `xml:",chardata"`
T string `xml:"t,attr,omitempty"` // Formula type
Ref string `xml:"ref,attr,omitempty"` // Shared formula ref
Si string `xml:"si,attr,omitempty"` // Shared formula index
}
// xlsxSheetProtection collection expresses the sheet protection options to
// enforce when the sheet is protected.
type xlsxSheetProtection struct {
AlgorithmName string `xml:"algorithmName,attr,omitempty"`
AutoFilter bool `xml:"autoFilter,attr,omitempty"`
DeleteColumns bool `xml:"deleteColumns,attr,omitempty"`
DeleteRows bool `xml:"deleteRows,attr,omitempty"`
FormatCells bool `xml:"formatCells,attr,omitempty"`
FormatColumns bool `xml:"formatColumns,attr,omitempty"`
FormatRows bool `xml:"formatRows,attr,omitempty"`
HashValue string `xml:"hashValue,attr,omitempty"`
InsertColumns bool `xml:"insertColumns,attr,omitempty"`
InsertHyperlinks bool `xml:"insertHyperlinks,attr,omitempty"`
InsertRows bool `xml:"insertRows,attr,omitempty"`
Objects bool `xml:"objects,attr,omitempty"`
Password string `xml:"password,attr,omitempty"`
PivotTables bool `xml:"pivotTables,attr,omitempty"`
SaltValue string `xml:"saltValue,attr,omitempty"`
Scenarios bool `xml:"scenarios,attr,omitempty"`
SelectLockedCells bool `xml:"selectLockedCells,attr,omitempty"`
SelectUnlockedCells bool `xml:"selectUnlockedCells,attr,omitempty"`
Sheet bool `xml:"sheet,attr,omitempty"`
Sort bool `xml:"sort,attr,omitempty"`
SpinCount int `xml:"spinCount,attr,omitempty"`
}
// xlsxPhoneticPr (Phonetic Properties) represents a collection of phonetic
// properties that affect the display of phonetic text for this String Item
// (si). Phonetic text is used to give hints as to the pronunciation of an East
// Asian language, and the hints are displayed as text within the spreadsheet
// cells across the top portion of the cell. Since the phonetic hints are text,
// every phonetic hint is expressed as a phonetic run (rPh), and these
// properties specify how to display that phonetic run.
type xlsxPhoneticPr struct {
Alignment string `xml:"alignment,attr,omitempty"`
FontID *int `xml:"fontId,attr"`
Type string `xml:"type,attr,omitempty"`
}
// A Conditional Format is a format, such as cell shading or font color, that a
// spreadsheet application can automatically apply to cells if a specified
// condition is true. This collection expresses conditional formatting rules
// applied to a particular cell or range.
type xlsxConditionalFormatting struct {
SQRef string `xml:"sqref,attr,omitempty"`
CfRule []*xlsxCfRule `xml:"cfRule"`
}
// xlsxCfRule (Conditional Formatting Rule) represents a description of a
// conditional formatting rule.
type xlsxCfRule struct {
AboveAverage *bool `xml:"aboveAverage,attr"`
Bottom bool `xml:"bottom,attr,omitempty"`
DxfID *int `xml:"dxfId,attr"`
EqualAverage bool `xml:"equalAverage,attr,omitempty"`
Operator string `xml:"operator,attr,omitempty"`
Percent bool `xml:"percent,attr,omitempty"`
Priority int `xml:"priority,attr,omitempty"`
Rank int `xml:"rank,attr,omitempty"`
StdDev int `xml:"stdDev,attr,omitempty"`
StopIfTrue bool `xml:"stopIfTrue,attr,omitempty"`
Text string `xml:"text,attr,omitempty"`
TimePeriod string `xml:"timePeriod,attr,omitempty"`
Type string `xml:"type,attr,omitempty"`
Formula []string `xml:"formula,omitempty"`
ColorScale *xlsxColorScale `xml:"colorScale"`
DataBar *xlsxDataBar `xml:"dataBar"`
IconSet *xlsxIconSet `xml:"iconSet"`
ExtLst *xlsxExtLst `xml:"extLst"`
}
// xlsxColorScale (Color Scale) describes a gradated color scale in this
// conditional formatting rule.
type xlsxColorScale struct {
Cfvo []*xlsxCfvo `xml:"cfvo"`
Color []*xlsxColor `xml:"color"`
}
// dataBar (Data Bar) describes a data bar conditional formatting rule.
type xlsxDataBar struct {
MaxLength int `xml:"maxLength,attr,omitempty"`
MinLength int `xml:"minLength,attr,omitempty"`
ShowValue bool `xml:"showValue,attr,omitempty"`
Cfvo []*xlsxCfvo `xml:"cfvo"`
Color []*xlsxColor `xml:"color"`
}
// xlsxIconSet (Icon Set) describes an icon set conditional formatting rule.
type xlsxIconSet struct {
Cfvo []*xlsxCfvo `xml:"cfvo"`
IconSet string `xml:"iconSet,attr,omitempty"`
ShowValue bool `xml:"showValue,attr,omitempty"`
Percent bool `xml:"percent,attr,omitempty"`
Reverse bool `xml:"reverse,attr,omitempty"`
}
// cfvo (Conditional Format Value Object) describes the values of the
// interpolation points in a gradient scale.
type xlsxCfvo struct {
Gte bool `xml:"gte,attr,omitempty"`
Type string `xml:"type,attr,omitempty"`
Val string `xml:"val,attr"`
ExtLst *xlsxExtLst `xml:"extLst"`
}
// xlsxHyperlinks directly maps the hyperlinks element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - A hyperlink can
// be stored in a package as a relationship. Hyperlinks shall be identified by
// containing a target which specifies the destination of the given hyperlink.
type xlsxHyperlinks struct {
Hyperlink []xlsxHyperlink `xml:"hyperlink"`
}
// xlsxHyperlink directly maps the hyperlink element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main
type xlsxHyperlink struct {
Ref string `xml:"ref,attr"`
Location string `xml:"location,attr,omitempty"`
Display string `xml:"display,attr,omitempty"`
RID string `xml:"http://schemas.openxmlformats.org/officeDocument/2006/relationships id,attr,omitempty"`
}
// xlsxTableParts directly maps the tableParts element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - The table element
// has several attributes applied to identify the table and the data range it
// covers. The table id attribute needs to be unique across all table parts, the
// same goes for the name and displayName. The displayName has the further
// restriction that it must be unique across all defined names in the workbook.
// Later on we will see that you can define names for many elements, such as
// cells or formulas. The name value is used for the object model in Microsoft
// Office Excel. The displayName is used for references in formulas. The ref
// attribute is used to identify the cell range that the table covers. This
// includes not only the table data, but also the table header containing column
// names.
// To add columns to your table you add new tableColumn elements to the
// tableColumns container. Similar to the shared string table the collection
// keeps a count attribute identifying the number of columns. Besides the table
// definition in the table part there is also the need to identify which tables
// are displayed in the worksheet. The worksheet part has a separate element
// tableParts to store this information. Each table part is referenced through
// the relationship ID and again a count of the number of table parts is
// maintained. The following markup sample is taken from the documents
// accompanying this book. The sheet data element has been removed to reduce the
// size of the sample. To reference the table, just add the tableParts element,
// of course after having created and stored the table part. For example:
//
// <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
// ...
// <tableParts count="1">
// <tablePart r:id="rId1" />
// </tableParts>
// </worksheet>
//
type xlsxTableParts struct {
Count int `xml:"count,attr,omitempty"`
TableParts []*xlsxTablePart `xml:"tablePart"`
}
// xlsxTablePart directly maps the tablePart element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main
type xlsxTablePart struct {
RID string `xml:"http://schemas.openxmlformats.org/officeDocument/2006/relationships id,attr,omitempty"`
}
// xlsxPicture directly maps the picture element in the namespace
// http://schemas.openxmlformats.org/spreadsheetml/2006/main - Background sheet
// image. For example:
//
// <picture r:id="rId1"/>
//
type xlsxPicture struct {
RID string `xml:"http://schemas.openxmlformats.org/officeDocument/2006/relationships id,attr,omitempty"`
}
// xlsxLegacyDrawing directly maps the legacyDrawing element in 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 xlsxLegacyDrawing struct {
RID string `xml:"http://schemas.openxmlformats.org/officeDocument/2006/relationships id,attr,omitempty"`
}
// formatPanes directly maps the settings of the panes.
type formatPanes struct {
Freeze bool `json:"freeze"`
Split bool `json:"split"`
XSplit int `json:"x_split"`
YSplit int `json:"y_split"`
TopLeftCell string `json:"top_left_cell"`
ActivePane string `json:"active_pane"`
Panes []struct {
SQRef string `json:"sqref"`
ActiveCell string `json:"active_cell"`
Pane string `json:"pane"`
} `json:"panes"`
}
// formatConditional directly maps the conditional format settings of the cells.
type formatConditional struct {
Type string `json:"type"`
AboveAverage bool `json:"above_average"`
Percent bool `json:"percent"`
Format int `json:"format"`
Criteria string `json:"criteria"`
Value string `json:"value,omitempty"`
Minimum string `json:"minimum,omitempty"`
Maximum string `json:"maximum,omitempty"`
MinType string `json:"min_type,omitempty"`
MidType string `json:"mid_type,omitempty"`
MaxType string `json:"max_type,omitempty"`
MinValue string `json:"min_value,omitempty"`
MidValue string `json:"mid_value,omitempty"`
MaxValue string `json:"max_value,omitempty"`
MinColor string `json:"min_color,omitempty"`
MidColor string `json:"mid_color,omitempty"`
MaxColor string `json:"max_color,omitempty"`
MinLength string `json:"min_length,omitempty"`
MaxLength string `json:"max_length,omitempty"`
MultiRange string `json:"multi_range,omitempty"`
BarColor string `json:"bar_color,omitempty"`
}
// FormatSheetProtection directly maps the settings of worksheet protection.
type FormatSheetProtection struct {
AutoFilter bool
DeleteColumns bool
DeleteRows bool
EditObjects bool
EditScenarios bool
FormatCells bool
FormatColumns bool
FormatRows bool
InsertColumns bool
InsertHyperlinks bool
InsertRows bool
Password string
PivotTables bool
SelectLockedCells bool
SelectUnlockedCells bool
Sort bool
}

202
vendor/github.com/bradfitz/gomemcache/LICENSE generated vendored Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,718 @@
/*
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package memcache provides a client for the memcached cache server.
package memcache
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"sync"
"time"
)
// Similar to:
// https://godoc.org/google.golang.org/appengine/memcache
var (
// ErrCacheMiss means that a Get failed because the item wasn't present.
ErrCacheMiss = errors.New("memcache: cache miss")
// ErrCASConflict means that a CompareAndSwap call failed due to the
// cached value being modified between the Get and the CompareAndSwap.
// If the cached value was simply evicted rather than replaced,
// ErrNotStored will be returned instead.
ErrCASConflict = errors.New("memcache: compare-and-swap conflict")
// ErrNotStored means that a conditional write operation (i.e. Add or
// CompareAndSwap) failed because the condition was not satisfied.
ErrNotStored = errors.New("memcache: item not stored")
// ErrServer means that a server error occurred.
ErrServerError = errors.New("memcache: server error")
// ErrNoStats means that no statistics were available.
ErrNoStats = errors.New("memcache: no statistics available")
// ErrMalformedKey is returned when an invalid key is used.
// Keys must be at maximum 250 bytes long and not
// contain whitespace or control characters.
ErrMalformedKey = errors.New("malformed: key is too long or contains invalid characters")
// ErrNoServers is returned when no servers are configured or available.
ErrNoServers = errors.New("memcache: no servers configured or available")
)
const (
// DefaultTimeout is the default socket read/write timeout.
DefaultTimeout = 100 * time.Millisecond
// DefaultMaxIdleConns is the default maximum number of idle connections
// kept for any single address.
DefaultMaxIdleConns = 2
)
const buffered = 8 // arbitrary buffered channel size, for readability
// resumableError returns true if err is only a protocol-level cache error.
// This is used to determine whether or not a server connection should
// be re-used or not. If an error occurs, by default we don't reuse the
// connection, unless it was just a cache error.
func resumableError(err error) bool {
switch err {
case ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrMalformedKey:
return true
}
return false
}
func legalKey(key string) bool {
if len(key) > 250 {
return false
}
for i := 0; i < len(key); i++ {
if key[i] <= ' ' || key[i] == 0x7f {
return false
}
}
return true
}
var (
crlf = []byte("\r\n")
space = []byte(" ")
resultOK = []byte("OK\r\n")
resultStored = []byte("STORED\r\n")
resultNotStored = []byte("NOT_STORED\r\n")
resultExists = []byte("EXISTS\r\n")
resultNotFound = []byte("NOT_FOUND\r\n")
resultDeleted = []byte("DELETED\r\n")
resultEnd = []byte("END\r\n")
resultOk = []byte("OK\r\n")
resultTouched = []byte("TOUCHED\r\n")
resultClientErrorPrefix = []byte("CLIENT_ERROR ")
versionPrefix = []byte("VERSION")
)
// New returns a memcache client using the provided server(s)
// with equal weight. If a server is listed multiple times,
// it gets a proportional amount of weight.
func New(server ...string) *Client {
ss := new(ServerList)
ss.SetServers(server...)
return NewFromSelector(ss)
}
// NewFromSelector returns a new Client using the provided ServerSelector.
func NewFromSelector(ss ServerSelector) *Client {
return &Client{selector: ss}
}
// Client is a memcache client.
// It is safe for unlocked use by multiple concurrent goroutines.
type Client struct {
// Timeout specifies the socket read/write timeout.
// If zero, DefaultTimeout is used.
Timeout time.Duration
// MaxIdleConns specifies the maximum number of idle connections that will
// be maintained per address. If less than one, DefaultMaxIdleConns will be
// used.
//
// Consider your expected traffic rates and latency carefully. This should
// be set to a number higher than your peak parallel requests.
MaxIdleConns int
selector ServerSelector
lk sync.Mutex
freeconn map[string][]*conn
}
// Item is an item to be got or stored in a memcached server.
type Item struct {
// Key is the Item's key (250 bytes maximum).
Key string
// Value is the Item's value.
Value []byte
// Flags are server-opaque flags whose semantics are entirely
// up to the app.
Flags uint32
// Expiration is the cache expiration time, in seconds: either a relative
// time from now (up to 1 month), or an absolute Unix epoch time.
// Zero means the Item has no expiration time.
Expiration int32
// Compare and swap ID.
casid uint64
}
// conn is a connection to a server.
type conn struct {
nc net.Conn
rw *bufio.ReadWriter
addr net.Addr
c *Client
}
// release returns this connection back to the client's free pool
func (cn *conn) release() {
cn.c.putFreeConn(cn.addr, cn)
}
func (cn *conn) extendDeadline() {
cn.nc.SetDeadline(time.Now().Add(cn.c.netTimeout()))
}
// condRelease releases this connection if the error pointed to by err
// is nil (not an error) or is only a protocol level error (e.g. a
// cache miss). The purpose is to not recycle TCP connections that
// are bad.
func (cn *conn) condRelease(err *error) {
if *err == nil || resumableError(*err) {
cn.release()
} else {
cn.nc.Close()
}
}
func (c *Client) putFreeConn(addr net.Addr, cn *conn) {
c.lk.Lock()
defer c.lk.Unlock()
if c.freeconn == nil {
c.freeconn = make(map[string][]*conn)
}
freelist := c.freeconn[addr.String()]
if len(freelist) >= c.maxIdleConns() {
cn.nc.Close()
return
}
c.freeconn[addr.String()] = append(freelist, cn)
}
func (c *Client) getFreeConn(addr net.Addr) (cn *conn, ok bool) {
c.lk.Lock()
defer c.lk.Unlock()
if c.freeconn == nil {
return nil, false
}
freelist, ok := c.freeconn[addr.String()]
if !ok || len(freelist) == 0 {
return nil, false
}
cn = freelist[len(freelist)-1]
c.freeconn[addr.String()] = freelist[:len(freelist)-1]
return cn, true
}
func (c *Client) netTimeout() time.Duration {
if c.Timeout != 0 {
return c.Timeout
}
return DefaultTimeout
}
func (c *Client) maxIdleConns() int {
if c.MaxIdleConns > 0 {
return c.MaxIdleConns
}
return DefaultMaxIdleConns
}
// ConnectTimeoutError is the error type used when it takes
// too long to connect to the desired host. This level of
// detail can generally be ignored.
type ConnectTimeoutError struct {
Addr net.Addr
}
func (cte *ConnectTimeoutError) Error() string {
return "memcache: connect timeout to " + cte.Addr.String()
}
func (c *Client) dial(addr net.Addr) (net.Conn, error) {
type connError struct {
cn net.Conn
err error
}
nc, err := net.DialTimeout(addr.Network(), addr.String(), c.netTimeout())
if err == nil {
return nc, nil
}
if ne, ok := err.(net.Error); ok && ne.Timeout() {
return nil, &ConnectTimeoutError{addr}
}
return nil, err
}
func (c *Client) getConn(addr net.Addr) (*conn, error) {
cn, ok := c.getFreeConn(addr)
if ok {
cn.extendDeadline()
return cn, nil
}
nc, err := c.dial(addr)
if err != nil {
return nil, err
}
cn = &conn{
nc: nc,
addr: addr,
rw: bufio.NewReadWriter(bufio.NewReader(nc), bufio.NewWriter(nc)),
c: c,
}
cn.extendDeadline()
return cn, nil
}
func (c *Client) onItem(item *Item, fn func(*Client, *bufio.ReadWriter, *Item) error) error {
addr, err := c.selector.PickServer(item.Key)
if err != nil {
return err
}
cn, err := c.getConn(addr)
if err != nil {
return err
}
defer cn.condRelease(&err)
if err = fn(c, cn.rw, item); err != nil {
return err
}
return nil
}
func (c *Client) FlushAll() error {
return c.selector.Each(c.flushAllFromAddr)
}
// Get gets the item for the given key. ErrCacheMiss is returned for a
// memcache cache miss. The key must be at most 250 bytes in length.
func (c *Client) Get(key string) (item *Item, err error) {
err = c.withKeyAddr(key, func(addr net.Addr) error {
return c.getFromAddr(addr, []string{key}, func(it *Item) { item = it })
})
if err == nil && item == nil {
err = ErrCacheMiss
}
return
}
// Touch updates the expiry for the given key. The seconds parameter is either
// a Unix timestamp or, if seconds is less than 1 month, the number of seconds
// into the future at which time the item will expire. Zero means the item has
// no expiration time. ErrCacheMiss is returned if the key is not in the cache.
// The key must be at most 250 bytes in length.
func (c *Client) Touch(key string, seconds int32) (err error) {
return c.withKeyAddr(key, func(addr net.Addr) error {
return c.touchFromAddr(addr, []string{key}, seconds)
})
}
func (c *Client) withKeyAddr(key string, fn func(net.Addr) error) (err error) {
if !legalKey(key) {
return ErrMalformedKey
}
addr, err := c.selector.PickServer(key)
if err != nil {
return err
}
return fn(addr)
}
func (c *Client) withAddrRw(addr net.Addr, fn func(*bufio.ReadWriter) error) (err error) {
cn, err := c.getConn(addr)
if err != nil {
return err
}
defer cn.condRelease(&err)
return fn(cn.rw)
}
func (c *Client) withKeyRw(key string, fn func(*bufio.ReadWriter) error) error {
return c.withKeyAddr(key, func(addr net.Addr) error {
return c.withAddrRw(addr, fn)
})
}
func (c *Client) getFromAddr(addr net.Addr, keys []string, cb func(*Item)) error {
return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
if _, err := fmt.Fprintf(rw, "gets %s\r\n", strings.Join(keys, " ")); err != nil {
return err
}
if err := rw.Flush(); err != nil {
return err
}
if err := parseGetResponse(rw.Reader, cb); err != nil {
return err
}
return nil
})
}
// flushAllFromAddr send the flush_all command to the given addr
func (c *Client) flushAllFromAddr(addr net.Addr) error {
return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
if _, err := fmt.Fprintf(rw, "flush_all\r\n"); err != nil {
return err
}
if err := rw.Flush(); err != nil {
return err
}
line, err := rw.ReadSlice('\n')
if err != nil {
return err
}
switch {
case bytes.Equal(line, resultOk):
break
default:
return fmt.Errorf("memcache: unexpected response line from flush_all: %q", string(line))
}
return nil
})
}
// ping sends the version command to the given addr
func (c *Client) ping(addr net.Addr) error {
return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
if _, err := fmt.Fprintf(rw, "version\r\n"); err != nil {
return err
}
if err := rw.Flush(); err != nil {
return err
}
line, err := rw.ReadSlice('\n')
if err != nil {
return err
}
switch {
case bytes.HasPrefix(line, versionPrefix):
break
default:
return fmt.Errorf("memcache: unexpected response line from ping: %q", string(line))
}
return nil
})
}
func (c *Client) touchFromAddr(addr net.Addr, keys []string, expiration int32) error {
return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
for _, key := range keys {
if _, err := fmt.Fprintf(rw, "touch %s %d\r\n", key, expiration); err != nil {
return err
}
if err := rw.Flush(); err != nil {
return err
}
line, err := rw.ReadSlice('\n')
if err != nil {
return err
}
switch {
case bytes.Equal(line, resultTouched):
break
case bytes.Equal(line, resultNotFound):
return ErrCacheMiss
default:
return fmt.Errorf("memcache: unexpected response line from touch: %q", string(line))
}
}
return nil
})
}
// GetMulti is a batch version of Get. The returned map from keys to
// items may have fewer elements than the input slice, due to memcache
// cache misses. Each key must be at most 250 bytes in length.
// If no error is returned, the returned map will also be non-nil.
func (c *Client) GetMulti(keys []string) (map[string]*Item, error) {
var lk sync.Mutex
m := make(map[string]*Item)
addItemToMap := func(it *Item) {
lk.Lock()
defer lk.Unlock()
m[it.Key] = it
}
keyMap := make(map[net.Addr][]string)
for _, key := range keys {
if !legalKey(key) {
return nil, ErrMalformedKey
}
addr, err := c.selector.PickServer(key)
if err != nil {
return nil, err
}
keyMap[addr] = append(keyMap[addr], key)
}
ch := make(chan error, buffered)
for addr, keys := range keyMap {
go func(addr net.Addr, keys []string) {
ch <- c.getFromAddr(addr, keys, addItemToMap)
}(addr, keys)
}
var err error
for _ = range keyMap {
if ge := <-ch; ge != nil {
err = ge
}
}
return m, err
}
// parseGetResponse reads a GET response from r and calls cb for each
// read and allocated Item
func parseGetResponse(r *bufio.Reader, cb func(*Item)) error {
for {
line, err := r.ReadSlice('\n')
if err != nil {
return err
}
if bytes.Equal(line, resultEnd) {
return nil
}
it := new(Item)
size, err := scanGetResponseLine(line, it)
if err != nil {
return err
}
it.Value = make([]byte, size+2)
_, err = io.ReadFull(r, it.Value)
if err != nil {
it.Value = nil
return err
}
if !bytes.HasSuffix(it.Value, crlf) {
it.Value = nil
return fmt.Errorf("memcache: corrupt get result read")
}
it.Value = it.Value[:size]
cb(it)
}
}
// scanGetResponseLine populates it and returns the declared size of the item.
// It does not read the bytes of the item.
func scanGetResponseLine(line []byte, it *Item) (size int, err error) {
pattern := "VALUE %s %d %d %d\r\n"
dest := []interface{}{&it.Key, &it.Flags, &size, &it.casid}
if bytes.Count(line, space) == 3 {
pattern = "VALUE %s %d %d\r\n"
dest = dest[:3]
}
n, err := fmt.Sscanf(string(line), pattern, dest...)
if err != nil || n != len(dest) {
return -1, fmt.Errorf("memcache: unexpected line in get response: %q", line)
}
return size, nil
}
// Set writes the given item, unconditionally.
func (c *Client) Set(item *Item) error {
return c.onItem(item, (*Client).set)
}
func (c *Client) set(rw *bufio.ReadWriter, item *Item) error {
return c.populateOne(rw, "set", item)
}
// Add writes the given item, if no value already exists for its
// key. ErrNotStored is returned if that condition is not met.
func (c *Client) Add(item *Item) error {
return c.onItem(item, (*Client).add)
}
func (c *Client) add(rw *bufio.ReadWriter, item *Item) error {
return c.populateOne(rw, "add", item)
}
// Replace writes the given item, but only if the server *does*
// already hold data for this key
func (c *Client) Replace(item *Item) error {
return c.onItem(item, (*Client).replace)
}
func (c *Client) replace(rw *bufio.ReadWriter, item *Item) error {
return c.populateOne(rw, "replace", item)
}
// CompareAndSwap writes the given item that was previously returned
// by Get, if the value was neither modified or evicted between the
// Get and the CompareAndSwap calls. The item's Key should not change
// between calls but all other item fields may differ. ErrCASConflict
// is returned if the value was modified in between the
// calls. ErrNotStored is returned if the value was evicted in between
// the calls.
func (c *Client) CompareAndSwap(item *Item) error {
return c.onItem(item, (*Client).cas)
}
func (c *Client) cas(rw *bufio.ReadWriter, item *Item) error {
return c.populateOne(rw, "cas", item)
}
func (c *Client) populateOne(rw *bufio.ReadWriter, verb string, item *Item) error {
if !legalKey(item.Key) {
return ErrMalformedKey
}
var err error
if verb == "cas" {
_, err = fmt.Fprintf(rw, "%s %s %d %d %d %d\r\n",
verb, item.Key, item.Flags, item.Expiration, len(item.Value), item.casid)
} else {
_, err = fmt.Fprintf(rw, "%s %s %d %d %d\r\n",
verb, item.Key, item.Flags, item.Expiration, len(item.Value))
}
if err != nil {
return err
}
if _, err = rw.Write(item.Value); err != nil {
return err
}
if _, err := rw.Write(crlf); err != nil {
return err
}
if err := rw.Flush(); err != nil {
return err
}
line, err := rw.ReadSlice('\n')
if err != nil {
return err
}
switch {
case bytes.Equal(line, resultStored):
return nil
case bytes.Equal(line, resultNotStored):
return ErrNotStored
case bytes.Equal(line, resultExists):
return ErrCASConflict
case bytes.Equal(line, resultNotFound):
return ErrCacheMiss
}
return fmt.Errorf("memcache: unexpected response line from %q: %q", verb, string(line))
}
func writeReadLine(rw *bufio.ReadWriter, format string, args ...interface{}) ([]byte, error) {
_, err := fmt.Fprintf(rw, format, args...)
if err != nil {
return nil, err
}
if err := rw.Flush(); err != nil {
return nil, err
}
line, err := rw.ReadSlice('\n')
return line, err
}
func writeExpectf(rw *bufio.ReadWriter, expect []byte, format string, args ...interface{}) error {
line, err := writeReadLine(rw, format, args...)
if err != nil {
return err
}
switch {
case bytes.Equal(line, resultOK):
return nil
case bytes.Equal(line, expect):
return nil
case bytes.Equal(line, resultNotStored):
return ErrNotStored
case bytes.Equal(line, resultExists):
return ErrCASConflict
case bytes.Equal(line, resultNotFound):
return ErrCacheMiss
}
return fmt.Errorf("memcache: unexpected response line: %q", string(line))
}
// Delete deletes the item with the provided key. The error ErrCacheMiss is
// returned if the item didn't already exist in the cache.
func (c *Client) Delete(key string) error {
return c.withKeyRw(key, func(rw *bufio.ReadWriter) error {
return writeExpectf(rw, resultDeleted, "delete %s\r\n", key)
})
}
// DeleteAll deletes all items in the cache.
func (c *Client) DeleteAll() error {
return c.withKeyRw("", func(rw *bufio.ReadWriter) error {
return writeExpectf(rw, resultDeleted, "flush_all\r\n")
})
}
// Ping checks all instances if they are alive. Returns error if any
// of them is down.
func (c *Client) Ping() error {
return c.selector.Each(c.ping)
}
// Increment atomically increments key by delta. The return value is
// the new value after being incremented or an error. If the value
// didn't exist in memcached the error is ErrCacheMiss. The value in
// memcached must be an decimal number, or an error will be returned.
// On 64-bit overflow, the new value wraps around.
func (c *Client) Increment(key string, delta uint64) (newValue uint64, err error) {
return c.incrDecr("incr", key, delta)
}
// Decrement atomically decrements key by delta. The return value is
// the new value after being decremented or an error. If the value
// didn't exist in memcached the error is ErrCacheMiss. The value in
// memcached must be an decimal number, or an error will be returned.
// On underflow, the new value is capped at zero and does not wrap
// around.
func (c *Client) Decrement(key string, delta uint64) (newValue uint64, err error) {
return c.incrDecr("decr", key, delta)
}
func (c *Client) incrDecr(verb, key string, delta uint64) (uint64, error) {
var val uint64
err := c.withKeyRw(key, func(rw *bufio.ReadWriter) error {
line, err := writeReadLine(rw, "%s %s %d\r\n", verb, key, delta)
if err != nil {
return err
}
switch {
case bytes.Equal(line, resultNotFound):
return ErrCacheMiss
case bytes.HasPrefix(line, resultClientErrorPrefix):
errMsg := line[len(resultClientErrorPrefix) : len(line)-2]
return errors.New("memcache: client error: " + string(errMsg))
}
val, err = strconv.ParseUint(string(line[:len(line)-2]), 10, 64)
if err != nil {
return err
}
return nil
})
return val, err
}

View File

@ -0,0 +1,129 @@
/*
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package memcache
import (
"hash/crc32"
"net"
"strings"
"sync"
)
// ServerSelector is the interface that selects a memcache server
// as a function of the item's key.
//
// All ServerSelector implementations must be safe for concurrent use
// by multiple goroutines.
type ServerSelector interface {
// PickServer returns the server address that a given item
// should be shared onto.
PickServer(key string) (net.Addr, error)
Each(func(net.Addr) error) error
}
// ServerList is a simple ServerSelector. Its zero value is usable.
type ServerList struct {
mu sync.RWMutex
addrs []net.Addr
}
// staticAddr caches the Network() and String() values from any net.Addr.
type staticAddr struct {
ntw, str string
}
func newStaticAddr(a net.Addr) net.Addr {
return &staticAddr{
ntw: a.Network(),
str: a.String(),
}
}
func (s *staticAddr) Network() string { return s.ntw }
func (s *staticAddr) String() string { return s.str }
// SetServers changes a ServerList's set of servers at runtime and is
// safe for concurrent use by multiple goroutines.
//
// Each server is given equal weight. A server is given more weight
// if it's listed multiple times.
//
// SetServers returns an error if any of the server names fail to
// resolve. No attempt is made to connect to the server. If any error
// is returned, no changes are made to the ServerList.
func (ss *ServerList) SetServers(servers ...string) error {
naddr := make([]net.Addr, len(servers))
for i, server := range servers {
if strings.Contains(server, "/") {
addr, err := net.ResolveUnixAddr("unix", server)
if err != nil {
return err
}
naddr[i] = newStaticAddr(addr)
} else {
tcpaddr, err := net.ResolveTCPAddr("tcp", server)
if err != nil {
return err
}
naddr[i] = newStaticAddr(tcpaddr)
}
}
ss.mu.Lock()
defer ss.mu.Unlock()
ss.addrs = naddr
return nil
}
// Each iterates over each server calling the given function
func (ss *ServerList) Each(f func(net.Addr) error) error {
ss.mu.RLock()
defer ss.mu.RUnlock()
for _, a := range ss.addrs {
if err := f(a); nil != err {
return err
}
}
return nil
}
// keyBufPool returns []byte buffers for use by PickServer's call to
// crc32.ChecksumIEEE to avoid allocations. (but doesn't avoid the
// copies, which at least are bounded in size and small)
var keyBufPool = sync.Pool{
New: func() interface{} {
b := make([]byte, 256)
return &b
},
}
func (ss *ServerList) PickServer(key string) (net.Addr, error) {
ss.mu.RLock()
defer ss.mu.RUnlock()
if len(ss.addrs) == 0 {
return nil, ErrNoServers
}
if len(ss.addrs) == 1 {
return ss.addrs[0], nil
}
bufp := keyBufPool.Get().(*[]byte)
n := copy(*bufp, key)
cs := crc32.ChecksumIEEE((*bufp)[:n])
keyBufPool.Put(bufp)
return ss.addrs[cs%uint32(len(ss.addrs))], nil
}

23
vendor/github.com/fatih/structs/.gitignore generated vendored Normal file
View File

@ -0,0 +1,23 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test

13
vendor/github.com/fatih/structs/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,13 @@
language: go
go:
- 1.7.x
- 1.8.x
- 1.9.x
- tip
sudo: false
before_install:
- go get github.com/axw/gocov/gocov
- go get github.com/mattn/goveralls
- if ! go get github.com/golang/tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi
script:
- $HOME/gopath/bin/goveralls -service=travis-ci

21
vendor/github.com/fatih/structs/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Fatih Arslan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

163
vendor/github.com/fatih/structs/README.md generated vendored Normal file
View File

@ -0,0 +1,163 @@
# Structs [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/github.com/fatih/structs) [![Build Status](http://img.shields.io/travis/fatih/structs.svg?style=flat-square)](https://travis-ci.org/fatih/structs) [![Coverage Status](http://img.shields.io/coveralls/fatih/structs.svg?style=flat-square)](https://coveralls.io/r/fatih/structs)
Structs contains various utilities to work with Go (Golang) structs. It was
initially used by me to convert a struct into a `map[string]interface{}`. With
time I've added other utilities for structs. It's basically a high level
package based on primitives from the reflect package. Feel free to add new
functions or improve the existing code.
## Install
```bash
go get github.com/fatih/structs
```
## Usage and Examples
Just like the standard lib `strings`, `bytes` and co packages, `structs` has
many global functions to manipulate or organize your struct data. Lets define
and declare a struct:
```go
type Server struct {
Name string `json:"name,omitempty"`
ID int
Enabled bool
users []string // not exported
http.Server // embedded
}
server := &Server{
Name: "gopher",
ID: 123456,
Enabled: true,
}
```
```go
// Convert a struct to a map[string]interface{}
// => {"Name":"gopher", "ID":123456, "Enabled":true}
m := structs.Map(server)
// Convert the values of a struct to a []interface{}
// => ["gopher", 123456, true]
v := structs.Values(server)
// Convert the names of a struct to a []string
// (see "Names methods" for more info about fields)
n := structs.Names(server)
// Convert the values of a struct to a []*Field
// (see "Field methods" for more info about fields)
f := structs.Fields(server)
// Return the struct name => "Server"
n := structs.Name(server)
// Check if any field of a struct is initialized or not.
h := structs.HasZero(server)
// Check if all fields of a struct is initialized or not.
z := structs.IsZero(server)
// Check if server is a struct or a pointer to struct
i := structs.IsStruct(server)
```
### Struct methods
The structs functions can be also used as independent methods by creating a new
`*structs.Struct`. This is handy if you want to have more control over the
structs (such as retrieving a single Field).
```go
// Create a new struct type:
s := structs.New(server)
m := s.Map() // Get a map[string]interface{}
v := s.Values() // Get a []interface{}
f := s.Fields() // Get a []*Field
n := s.Names() // Get a []string
f := s.Field(name) // Get a *Field based on the given field name
f, ok := s.FieldOk(name) // Get a *Field based on the given field name
n := s.Name() // Get the struct name
h := s.HasZero() // Check if any field is uninitialized
z := s.IsZero() // Check if all fields are uninitialized
```
### Field methods
We can easily examine a single Field for more detail. Below you can see how we
get and interact with various field methods:
```go
s := structs.New(server)
// Get the Field struct for the "Name" field
name := s.Field("Name")
// Get the underlying value, value => "gopher"
value := name.Value().(string)
// Set the field's value
name.Set("another gopher")
// Get the field's kind, kind => "string"
name.Kind()
// Check if the field is exported or not
if name.IsExported() {
fmt.Println("Name field is exported")
}
// Check if the value is a zero value, such as "" for string, 0 for int
if !name.IsZero() {
fmt.Println("Name is initialized")
}
// Check if the field is an anonymous (embedded) field
if !name.IsEmbedded() {
fmt.Println("Name is not an embedded field")
}
// Get the Field's tag value for tag name "json", tag value => "name,omitempty"
tagValue := name.Tag("json")
```
Nested structs are supported too:
```go
addrField := s.Field("Server").Field("Addr")
// Get the value for addr
a := addrField.Value().(string)
// Or get all fields
httpServer := s.Field("Server").Fields()
```
We can also get a slice of Fields from the Struct type to iterate over all
fields. This is handy if you wish to examine all fields:
```go
s := structs.New(server)
for _, f := range s.Fields() {
fmt.Printf("field name: %+v\n", f.Name())
if f.IsExported() {
fmt.Printf("value : %+v\n", f.Value())
fmt.Printf("is zero : %+v\n", f.IsZero())
}
}
```
## Credits
* [Fatih Arslan](https://github.com/fatih)
* [Cihangir Savas](https://github.com/cihangir)
## License
The MIT License (MIT) - see LICENSE.md for more details

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