util-go/excel.go
2021-11-25 21:50:12 +08:00

104 lines
2.0 KiB
Go

package util
import (
"errors"
"math"
"regexp"
"strconv"
"strings"
"time"
)
var ExcelChar = []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
//数字转字母
func ExcelNumToChar(num int) string {
var cols string
v := num
for v > 0 {
k := v % 26
if k == 0 {
k = 26
}
cols = ExcelChar[k-1] + cols
v = (v - k) / 26
}
return cols
}
//字母转数字
func ExcelCharToNum(str string) int {
num := 0
for i:=0;i<len(str);i++{
item := str[i:i+1]
itemNum := 0
for index,charItem := range ExcelChar{
if charItem==item{
itemNum=index+1
break
}
}
num+=itemNum*int(math.Pow(26.0,float64(len(str)-i-1)))
}
return num
}
//表头比对
func ExcelCompare(target [][]string,compare [][]string)bool{
if len(compare)==0{
return true
}
if len(target)<len(compare) || len(target[0])<len(compare[0]){
return false
}
for index,row :=range compare{
for index2,item := range row{
if target[index][index2]!=item{
return false
}
}
}
return true
}
//字符串转日期
//30-12-21
//2021-01-01 2021-1-1
//2021/01/01 2021/1/1
//2021.01.01 2021.1.1
//20210101
//55555
func ExcelStringToDate(str string)(time.Time,error){
matched,_:=regexp.MatchString(`\d{2}-\d{2}-\d{2}`,str)
if matched{
return time.Parse("02-01-06",str)
}
items := []string{"-", "/", "."}
for _, item := range items {
if strings.Contains(str, item) {
arr := strings.Split(str, item)
if len(arr) == 3 {
if len(arr[1]) == 1 {
arr[1] = "0" + arr[1]
}
if len(arr[2]) == 1 {
arr[2] = "0" + arr[2]
}
str = arr[0] + arr[1] + arr[2]
return time.Parse("20060102", str)
} else {
return time.Time{}, errors.New("日期格式错误:" + str)
}
}
}
if len(str) == 8 {
return time.Parse("20060102", str)
}
if len(str) == 5 {
//日期戳
dayDuration, _ := strconv.ParseInt(str, 10, 64)
return time.Unix((dayDuration-25569)*24*3600, 0), nil
}
return time.Time{}, errors.New("日期格式错误:" + str)
}