fixes
This commit is contained in:
1 parent
c347d2418f
commit
1ad180a052
49 files changed
+6339
-89
No files matched your search
+463
@@ -0,0 +1,463 @@
|
||||
package commonxl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
"unicode/utf16"
|
||||
)
|
||||
|
||||
// CellType annotates the type of data extracted in the cell.
|
||||
type CellType uint16
|
||||
|
||||
// CellType annotations for various cell value types.
|
||||
const (
|
||||
BlankCell CellType = iota
|
||||
IntegerCell
|
||||
FloatCell
|
||||
StringCell
|
||||
BooleanCell
|
||||
DateCell
|
||||
|
||||
HyperlinkStringCell // internal type to separate URLs
|
||||
StaticCell // placeholder, internal use only
|
||||
)
|
||||
|
||||
// String returns a string description of the cell data type.
|
||||
func (c CellType) String() string {
|
||||
switch c {
|
||||
case BlankCell:
|
||||
return "blank"
|
||||
case IntegerCell:
|
||||
return "integer"
|
||||
case FloatCell:
|
||||
return "float"
|
||||
case BooleanCell:
|
||||
return "boolean"
|
||||
case DateCell:
|
||||
return "date"
|
||||
case HyperlinkStringCell:
|
||||
return "hyperlink"
|
||||
case StaticCell:
|
||||
return "static"
|
||||
default: // StringCell, StaticCell
|
||||
return "string"
|
||||
}
|
||||
}
|
||||
|
||||
// Cell represents a single cell value.
|
||||
type Cell []interface{}
|
||||
|
||||
// internally, it is a slice sized 2 or 3
|
||||
// [Value, CellType] or [Value, CellType, FormatNumber]
|
||||
// where FormatNumber is a uint16 if not 0
|
||||
|
||||
// Value returns the contents as a generic interface{}.
|
||||
func (c Cell) Value() interface{} {
|
||||
if len(c) == 0 {
|
||||
return ""
|
||||
}
|
||||
return c[0]
|
||||
}
|
||||
|
||||
// SetURL adds a URL hyperlink to the cell.
|
||||
func (c *Cell) SetURL(link string) {
|
||||
(*c)[1] = HyperlinkStringCell
|
||||
if len(*c) == 2 {
|
||||
*c = append(*c, uint16(0), link)
|
||||
} else { // len = 3 already
|
||||
*c = append(*c, link)
|
||||
}
|
||||
}
|
||||
|
||||
// URL returns the parsed URL when a cell contains a hyperlink.
|
||||
func (c Cell) URL() (*url.URL, bool) {
|
||||
if c.Type() == HyperlinkStringCell && len(c) >= 4 {
|
||||
u, err := url.Parse(c[3].(string))
|
||||
return u, err == nil
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Type returns the CellType of the value.
|
||||
func (c Cell) Type() CellType {
|
||||
if len(c) < 2 {
|
||||
return BlankCell
|
||||
}
|
||||
return c[1].(CellType)
|
||||
}
|
||||
|
||||
// FormatNo returns the NumberFormat used for display.
|
||||
func (c Cell) FormatNo() uint16 {
|
||||
if len(c) == 3 {
|
||||
return c[2].(uint16)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Clone returns the new copy of this Cell.
|
||||
func (c Cell) Clone() Cell {
|
||||
c2 := make([]interface{}, len(c))
|
||||
for i, x := range c {
|
||||
c2[i] = x
|
||||
}
|
||||
return c2
|
||||
}
|
||||
|
||||
///////
|
||||
|
||||
var boolStrings = map[string]bool{
|
||||
"yes": true, "true": true, "t": true, "y": true, "1": true, "on": true,
|
||||
"no": false, "false": false, "f": false, "n": false, "0": false, "off": false,
|
||||
"YES": true, "TRUE": true, "T": true, "Y": true, "1.0": true, "ON": true,
|
||||
"NO": false, "FALSE": false, "F": false, "N": false, "0.0": false, "OFF": false,
|
||||
}
|
||||
|
||||
// NewCellWithType creates a new cell value with the given type, coercing as necessary.
|
||||
func NewCellWithType(value interface{}, t CellType, f *Formatter) Cell {
|
||||
c := NewCell(value)
|
||||
if c[1] == t {
|
||||
// fast path if it was already typed correctly
|
||||
return c
|
||||
}
|
||||
|
||||
if c[1] == BooleanCell {
|
||||
if t == IntegerCell {
|
||||
if c[0].(bool) {
|
||||
c[0] = int64(1)
|
||||
} else {
|
||||
c[0] = int64(0)
|
||||
}
|
||||
c[1] = IntegerCell
|
||||
} else if t == FloatCell {
|
||||
if c[0].(bool) {
|
||||
c[0] = float64(1.0)
|
||||
} else {
|
||||
c[0] = float64(0.0)
|
||||
}
|
||||
c[1] = FloatCell
|
||||
} else if t == StringCell {
|
||||
if c[0].(bool) {
|
||||
c[0] = "TRUE"
|
||||
} else {
|
||||
c[0] = "FALSE"
|
||||
}
|
||||
c[1] = FloatCell
|
||||
}
|
||||
}
|
||||
|
||||
if c[1] == FloatCell {
|
||||
if t == IntegerCell {
|
||||
c[0] = int64(c[0].(float64))
|
||||
c[1] = IntegerCell
|
||||
} else if t == BooleanCell {
|
||||
c[0] = c[0].(float64) != 0.0
|
||||
c[1] = BooleanCell
|
||||
}
|
||||
}
|
||||
if c[1] == IntegerCell {
|
||||
if t == FloatCell {
|
||||
c[0] = float64(c[0].(int64))
|
||||
c[1] = FloatCell
|
||||
} else if t == BooleanCell {
|
||||
c[0] = c[0].(int64) != 0
|
||||
c[1] = BooleanCell
|
||||
}
|
||||
}
|
||||
if c[1] == StringCell {
|
||||
if t == IntegerCell {
|
||||
x, _ := strconv.ParseInt(c[0].(string), 10, 64)
|
||||
c[0] = x
|
||||
c[1] = IntegerCell
|
||||
} else if t == FloatCell {
|
||||
x, _ := strconv.ParseFloat(c[0].(string), 64)
|
||||
c[0] = x
|
||||
c[1] = FloatCell
|
||||
} else if t == BooleanCell {
|
||||
c[0] = boolStrings[c[0].(string)]
|
||||
c[1] = BooleanCell
|
||||
}
|
||||
}
|
||||
if t == StringCell {
|
||||
c[0] = fmt.Sprint(c[0])
|
||||
c[1] = StringCell
|
||||
}
|
||||
if t == DateCell {
|
||||
if c[1] == FloatCell {
|
||||
c[0] = f.ConvertToDate(c[0].(float64))
|
||||
} else if c[1] == IntegerCell {
|
||||
c[0] = f.ConvertToDate(float64(c[0].(int64)))
|
||||
}
|
||||
c[1] = DateCell
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// NewCell creates a new cell value from any builtin type.
|
||||
func NewCell(value interface{}) Cell {
|
||||
c := make([]interface{}, 2)
|
||||
switch v := value.(type) {
|
||||
case bool:
|
||||
c[0] = v
|
||||
c[1] = BooleanCell
|
||||
case int:
|
||||
c[0] = int64(v)
|
||||
c[1] = IntegerCell
|
||||
case int8:
|
||||
c[0] = int64(v)
|
||||
c[1] = IntegerCell
|
||||
case int16:
|
||||
c[0] = int64(v)
|
||||
c[1] = IntegerCell
|
||||
case int32:
|
||||
c[0] = int64(v)
|
||||
c[1] = IntegerCell
|
||||
case int64:
|
||||
c[0] = int64(v)
|
||||
c[1] = IntegerCell
|
||||
case uint8:
|
||||
c[0] = int64(v)
|
||||
c[1] = IntegerCell
|
||||
case uint16:
|
||||
c[0] = int64(v)
|
||||
c[1] = IntegerCell
|
||||
case uint32:
|
||||
c[0] = int64(v)
|
||||
c[1] = IntegerCell
|
||||
|
||||
case uint:
|
||||
if int64(v) > int64(math.MaxInt64) {
|
||||
c[0] = float64(v)
|
||||
c[1] = FloatCell
|
||||
} else {
|
||||
c[0] = int64(v)
|
||||
c[1] = IntegerCell
|
||||
}
|
||||
case uint64:
|
||||
if v > math.MaxInt64 {
|
||||
c[0] = float64(v)
|
||||
c[1] = FloatCell
|
||||
} else {
|
||||
c[0] = int64(v)
|
||||
c[1] = IntegerCell
|
||||
}
|
||||
|
||||
case float32:
|
||||
c[0] = float64(v)
|
||||
c[1] = FloatCell
|
||||
case float64:
|
||||
c[0] = float64(v)
|
||||
c[1] = FloatCell
|
||||
|
||||
case string:
|
||||
if len(v) == 0 {
|
||||
c[0] = nil
|
||||
c[1] = BlankCell
|
||||
} else {
|
||||
c[0] = v
|
||||
c[1] = StringCell
|
||||
}
|
||||
case []byte:
|
||||
if len(v) == 0 {
|
||||
c[0] = nil
|
||||
c[1] = BlankCell
|
||||
} else {
|
||||
c[0] = string(v)
|
||||
c[1] = StringCell
|
||||
}
|
||||
case []uint16:
|
||||
if len(v) == 0 {
|
||||
c[0] = nil
|
||||
c[1] = BlankCell
|
||||
} else {
|
||||
c[0] = string(utf16.Decode(v))
|
||||
c[1] = StringCell
|
||||
}
|
||||
case []rune:
|
||||
if len(v) == 0 {
|
||||
c[0] = nil
|
||||
c[1] = BlankCell
|
||||
} else {
|
||||
c[0] = string(v)
|
||||
c[1] = StringCell
|
||||
}
|
||||
case time.Time:
|
||||
c[0] = v
|
||||
c[1] = DateCell
|
||||
|
||||
case fmt.Stringer:
|
||||
s := v.String()
|
||||
if len(s) == 0 {
|
||||
c[0] = nil
|
||||
c[1] = BlankCell
|
||||
} else {
|
||||
c[0] = s
|
||||
c[1] = StringCell
|
||||
}
|
||||
default:
|
||||
panic("grate: data type not handled")
|
||||
}
|
||||
return Cell(c)
|
||||
}
|
||||
|
||||
// SetFormatNumber changes the number format stored with the cell.
|
||||
func (c *Cell) SetFormatNumber(f uint16) {
|
||||
if f == 0 {
|
||||
*c = (*c)[:2]
|
||||
return
|
||||
}
|
||||
|
||||
if len(*c) == 2 {
|
||||
*c = append(*c, f)
|
||||
} else {
|
||||
(*c)[2] = f
|
||||
}
|
||||
}
|
||||
|
||||
func (c Cell) Equal(other Cell) bool {
|
||||
if c.Type() == FloatCell || other.Type() == FloatCell ||
|
||||
c.Type() == IntegerCell || other.Type() == IntegerCell {
|
||||
v1, ok := c[0].(float64)
|
||||
v1x, okx := c[0].(int64)
|
||||
if okx {
|
||||
v1 = float64(v1x)
|
||||
ok = true
|
||||
}
|
||||
if !ok {
|
||||
fmt.Sscanf(fmt.Sprint(c[0]), "%g", &v1)
|
||||
}
|
||||
v2, ok := other[0].(float64)
|
||||
v2x, okx := other[0].(int64)
|
||||
if okx {
|
||||
v2 = float64(v2x)
|
||||
ok = true
|
||||
}
|
||||
if !ok {
|
||||
fmt.Sscanf(fmt.Sprint(c[0]), "%g", &v2)
|
||||
}
|
||||
return v1 == v2
|
||||
}
|
||||
|
||||
return c.Less(other) == other.Less(c)
|
||||
}
|
||||
|
||||
func (c Cell) Less(other Cell) bool {
|
||||
if len(c) == 0 {
|
||||
return false
|
||||
}
|
||||
switch v1 := c[0].(type) {
|
||||
case nil:
|
||||
return false
|
||||
case bool:
|
||||
// F < T = T
|
||||
// F < F = F
|
||||
// T < T = F
|
||||
// T < F = F
|
||||
if v1 {
|
||||
return false
|
||||
}
|
||||
|
||||
// if v2 is truthy, return true
|
||||
switch v2 := other[0].(type) {
|
||||
case nil:
|
||||
return false
|
||||
case bool:
|
||||
return v2
|
||||
case int64:
|
||||
return v2 != 0
|
||||
case float64:
|
||||
return v2 != 0.0
|
||||
case string:
|
||||
return boolStrings[v2]
|
||||
}
|
||||
|
||||
case int64:
|
||||
// v1 < v2
|
||||
|
||||
switch v2 := other[0].(type) {
|
||||
case nil:
|
||||
return false
|
||||
case bool:
|
||||
x := int64(0)
|
||||
if v2 {
|
||||
x = 1
|
||||
}
|
||||
return v1 < x
|
||||
case int64:
|
||||
return v1 < v2
|
||||
case float64:
|
||||
if v2 < math.MinInt64 {
|
||||
return false
|
||||
}
|
||||
if v2 > math.MaxInt64 {
|
||||
return true
|
||||
}
|
||||
return float64(v1) < v2
|
||||
case string:
|
||||
var x int64
|
||||
_, err := fmt.Sscanf(v2, "%d", &x)
|
||||
if err == nil {
|
||||
return v1 < x
|
||||
}
|
||||
return fmt.Sprint(v1) < v2
|
||||
}
|
||||
case float64:
|
||||
switch v2 := other[0].(type) {
|
||||
case nil:
|
||||
return false
|
||||
case bool:
|
||||
x := float64(0.0)
|
||||
if v2 {
|
||||
x = 1.0
|
||||
}
|
||||
return v1 < x
|
||||
case int64:
|
||||
if v1 < math.MinInt64 {
|
||||
return true
|
||||
}
|
||||
if v1 > math.MaxInt64 {
|
||||
return false
|
||||
}
|
||||
return v1 < float64(v2)
|
||||
case float64:
|
||||
return v1 < v2
|
||||
case string:
|
||||
var x float64
|
||||
_, err := fmt.Sscanf(v2, "%g", &x)
|
||||
if err == nil {
|
||||
return v1 < x
|
||||
}
|
||||
return fmt.Sprint(v1) < v2
|
||||
}
|
||||
case string:
|
||||
//return v1 < fmt.Sprint(other[0])
|
||||
|
||||
switch v2 := other[0].(type) {
|
||||
case nil:
|
||||
return false
|
||||
case bool:
|
||||
return v2 && !boolStrings[v1]
|
||||
case int64:
|
||||
var x int64
|
||||
_, err := fmt.Sscanf(v1, "%d", &x)
|
||||
if err == nil {
|
||||
return x < v2
|
||||
}
|
||||
return v1 < fmt.Sprint(v2)
|
||||
case float64:
|
||||
var x float64
|
||||
_, err := fmt.Sscanf(v1, "%g", &x)
|
||||
if err == nil {
|
||||
return x < v2
|
||||
}
|
||||
return v1 < fmt.Sprint(v2)
|
||||
case string:
|
||||
return v1 < v2
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
panic("unable to compare cells (invalid internal type)")
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package commonxl
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ConvertToDate converts a floating-point value using the
|
||||
// Excel date serialization conventions.
|
||||
func (x *Formatter) ConvertToDate(val float64) time.Time {
|
||||
// http://web.archive.org/web/20190808062235/http://aa.usno.navy.mil/faq/docs/JD_Formula.php
|
||||
v := int(val)
|
||||
if v < 61 {
|
||||
jdate := val + 0.5
|
||||
if (x.flags & fMode1904) != 0 {
|
||||
jdate += 2416480.5
|
||||
} else {
|
||||
jdate += 2415018.5
|
||||
}
|
||||
JD := int(jdate)
|
||||
frac := jdate - float64(JD)
|
||||
|
||||
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
|
||||
day := L - 2447*J/80
|
||||
L = J / 11
|
||||
month := time.Month(J + 2 - 12*L)
|
||||
year := 100*(N-49) + I + L
|
||||
|
||||
t := time.Duration(float64(time.Hour*24) * frac)
|
||||
return time.Date(year, month, day, 0, 0, 0, 0, time.UTC).Add(t)
|
||||
}
|
||||
frac := val - float64(v)
|
||||
date := time.Date(1904, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
if (x.flags & fMode1904) == 0 {
|
||||
date = time.Date(1899, 12, 30, 0, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
t := time.Duration(float64(time.Hour*24) * frac)
|
||||
return date.AddDate(0, 0, v).Add(t)
|
||||
}
|
||||
|
||||
func timeFmtFunc(f string) FmtFunc {
|
||||
return func(x *Formatter, v interface{}) string {
|
||||
t, ok := v.(time.Time)
|
||||
if !ok {
|
||||
fval, ok := convertToFloat64(v)
|
||||
if !ok {
|
||||
return "MUST BE time.Time OR numeric TO FORMAT CORRECTLY"
|
||||
}
|
||||
t = x.ConvertToDate(fval)
|
||||
}
|
||||
//log.Println("formatting date", t, "with", f, "=", t.Format(f))
|
||||
return t.Format(f)
|
||||
}
|
||||
}
|
||||
|
||||
// same as above but replaces "AM" and "PM" with chinese translations.
|
||||
// TODO: implement others
|
||||
func cnTimeFmtFunc(f string) FmtFunc {
|
||||
return func(x *Formatter, v interface{}) string {
|
||||
t, ok := v.(time.Time)
|
||||
if !ok {
|
||||
fval, ok := convertToFloat64(v)
|
||||
if !ok {
|
||||
return "MUST BE time.Time OR numeric TO FORMAT CORRECTLY"
|
||||
}
|
||||
t = x.ConvertToDate(fval)
|
||||
}
|
||||
s := t.Format(f)
|
||||
s = strings.Replace(s, `AM`, `上午`, 1)
|
||||
return strings.Replace(s, `PM`, `下午`, 1)
|
||||
}
|
||||
}
|
||||
+303
@@ -0,0 +1,303 @@
|
||||
package commonxl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// FmtFunc will format a value according to the designated style.
|
||||
type FmtFunc func(*Formatter, interface{}) string
|
||||
|
||||
func staticFmtFunc(s string) FmtFunc {
|
||||
return func(x *Formatter, v interface{}) string {
|
||||
return s
|
||||
}
|
||||
}
|
||||
|
||||
func surround(pre string, ff FmtFunc, post string) FmtFunc {
|
||||
return func(x *Formatter, v interface{}) string {
|
||||
return pre + ff(x, v) + post
|
||||
}
|
||||
}
|
||||
|
||||
func addNegParens(ff FmtFunc) FmtFunc {
|
||||
return func(x *Formatter, v interface{}) string {
|
||||
s1 := ff(x, v)
|
||||
if s1[0] == '-' {
|
||||
return "(" + s1[1:] + ")"
|
||||
}
|
||||
return s1
|
||||
}
|
||||
}
|
||||
|
||||
func addCommas(ff FmtFunc) FmtFunc {
|
||||
return func(x *Formatter, v interface{}) string {
|
||||
s1 := ff(x, v)
|
||||
isNeg := false
|
||||
if s1[0] == '-' {
|
||||
isNeg = true
|
||||
s1 = s1[1:]
|
||||
}
|
||||
endIndex := strings.IndexAny(s1, ".eE")
|
||||
if endIndex < 0 {
|
||||
endIndex = len(s1)
|
||||
}
|
||||
for endIndex > 3 {
|
||||
endIndex -= 3
|
||||
s1 = s1[:endIndex] + "," + s1[endIndex:]
|
||||
}
|
||||
if isNeg {
|
||||
return "-" + s1
|
||||
}
|
||||
return s1
|
||||
}
|
||||
}
|
||||
|
||||
func identFunc(x *Formatter, v interface{}) string {
|
||||
switch x := v.(type) {
|
||||
case bool:
|
||||
if x {
|
||||
return "TRUE"
|
||||
}
|
||||
return "FALSE"
|
||||
case int64:
|
||||
s := strconv.FormatInt(x, 10)
|
||||
if len(s) <= 11 {
|
||||
return s
|
||||
}
|
||||
case float64:
|
||||
s := strconv.FormatFloat(x, 'f', -1, 64)
|
||||
if len(s) <= 11 || (len(s) == 12 && x < 0) {
|
||||
return s
|
||||
}
|
||||
s = strconv.FormatFloat(x, 'g', 6, 64)
|
||||
if len(s) <= 11 {
|
||||
return s
|
||||
}
|
||||
case string:
|
||||
return x
|
||||
case fmt.Stringer:
|
||||
return x.String()
|
||||
}
|
||||
return fmt.Sprint(v)
|
||||
}
|
||||
|
||||
func sprintfFunc(fs string, mul int) FmtFunc {
|
||||
wantInt64 := strings.Contains(fs, "%d")
|
||||
return func(x *Formatter, v interface{}) string {
|
||||
switch val := v.(type) {
|
||||
case int, uint, int64, uint64, int32, uint32, uint16, int16:
|
||||
return fmt.Sprintf(fs, v)
|
||||
|
||||
case float64:
|
||||
val *= float64(mul)
|
||||
if wantInt64 {
|
||||
v2 := int64(val)
|
||||
return fmt.Sprintf(fs, v2)
|
||||
}
|
||||
return fmt.Sprintf(fs, val)
|
||||
}
|
||||
return fmt.Sprint(v)
|
||||
}
|
||||
}
|
||||
|
||||
func convertToInt64(v interface{}) (int64, bool) {
|
||||
x, ok := convertToFloat64(v)
|
||||
return int64(x), ok
|
||||
}
|
||||
|
||||
func convertToFloat64(v interface{}) (float64, bool) {
|
||||
switch val := v.(type) {
|
||||
case float64:
|
||||
return val, true
|
||||
case bool:
|
||||
if val {
|
||||
return 1.0, true
|
||||
}
|
||||
return 0.0, true
|
||||
case int:
|
||||
return float64(val), true
|
||||
case int8:
|
||||
return float64(val), true
|
||||
case int16:
|
||||
return float64(val), true
|
||||
case int32:
|
||||
return float64(val), true
|
||||
case int64:
|
||||
return float64(val), true
|
||||
case uint:
|
||||
return float64(val), true
|
||||
case uint8:
|
||||
return float64(val), true
|
||||
case uint16:
|
||||
return float64(val), true
|
||||
case uint32:
|
||||
return float64(val), true
|
||||
case uint64:
|
||||
return float64(val), true
|
||||
case float32:
|
||||
return float64(val), true
|
||||
case string:
|
||||
nf, err := strconv.ParseFloat(val, 64)
|
||||
return nf, err == nil
|
||||
default:
|
||||
return 0.0, false
|
||||
}
|
||||
}
|
||||
|
||||
// replaces a zero with a dash
|
||||
func zeroDashFunc(ff FmtFunc) FmtFunc {
|
||||
return func(x *Formatter, v interface{}) string {
|
||||
fval, ok := convertToFloat64(v)
|
||||
if !ok {
|
||||
// strings etc returned as-is
|
||||
return fmt.Sprint(v)
|
||||
}
|
||||
if fval == 0.0 {
|
||||
return "-"
|
||||
}
|
||||
return ff(x, v)
|
||||
}
|
||||
}
|
||||
|
||||
func fracFmtFunc(n int) FmtFunc {
|
||||
return func(x *Formatter, v interface{}) string {
|
||||
f, ok := convertToFloat64(v)
|
||||
if !ok {
|
||||
return "MUST BE numeric TO FORMAT CORRECTLY"
|
||||
}
|
||||
w, n, d := DecimalToWholeFraction(f, n, n)
|
||||
if n == 0 {
|
||||
return fmt.Sprintf("%d", w)
|
||||
}
|
||||
if w == 0 {
|
||||
if f < 0 && n > 0 {
|
||||
n = -n
|
||||
}
|
||||
return fmt.Sprintf("%d/%d", n, d)
|
||||
}
|
||||
return fmt.Sprintf("%d %d/%d", w, n, d)
|
||||
}
|
||||
}
|
||||
|
||||
// handle (up to) all four format cases:
|
||||
// positive;negative;zero;other
|
||||
func switchFmtFunc(pos FmtFunc, others ...FmtFunc) FmtFunc {
|
||||
stringFF := identFunc
|
||||
zeroFF := pos
|
||||
negFF := pos
|
||||
if len(others) > 0 {
|
||||
negFF = others[0]
|
||||
if len(others) > 1 {
|
||||
zeroFF = others[1]
|
||||
if len(others) > 2 {
|
||||
stringFF = others[2]
|
||||
}
|
||||
}
|
||||
}
|
||||
return func(x *Formatter, v interface{}) string {
|
||||
val, ok := convertToFloat64(v)
|
||||
if !ok {
|
||||
return stringFF(x, v)
|
||||
}
|
||||
if val == 0.0 {
|
||||
return zeroFF(x, v)
|
||||
}
|
||||
if val < 0.0 {
|
||||
return negFF(x, v)
|
||||
}
|
||||
return pos(x, v)
|
||||
}
|
||||
}
|
||||
|
||||
// mapping of standard built-ins to Go date format funcs.
|
||||
var goFormatters = map[uint16]FmtFunc{
|
||||
0: identFunc, // FIXME: better "general" formatter
|
||||
49: identFunc,
|
||||
|
||||
14: timeFmtFunc(`01-02-06`),
|
||||
15: timeFmtFunc(`2-Jan-06`),
|
||||
16: timeFmtFunc(`2-Jan`),
|
||||
17: timeFmtFunc(`Jan-06`),
|
||||
20: timeFmtFunc(`15:04`),
|
||||
21: timeFmtFunc(`15:04:05`),
|
||||
22: timeFmtFunc(`1/2/06 15:04`),
|
||||
45: timeFmtFunc(`04:05`),
|
||||
46: timeFmtFunc(`3:04:05`),
|
||||
47: timeFmtFunc(`0405.9`),
|
||||
27: timeFmtFunc(`2006"年"1"月"`),
|
||||
28: timeFmtFunc(`1"月"2"日"`),
|
||||
29: timeFmtFunc(`1"月"2"日"`),
|
||||
30: timeFmtFunc(`1-2-06`),
|
||||
31: timeFmtFunc(`2006"年"1"月"2"日"`),
|
||||
32: timeFmtFunc(`15"时"04"分"`),
|
||||
33: timeFmtFunc(`15"时"04"分"05"秒"`),
|
||||
36: timeFmtFunc(`2006"年"2"月"`),
|
||||
50: timeFmtFunc(`2006"年"2"月"`),
|
||||
51: timeFmtFunc(`1"月"2"日"`),
|
||||
52: timeFmtFunc(`2006"年"1"月"`),
|
||||
53: timeFmtFunc(`1"月"2"日"`),
|
||||
54: timeFmtFunc(`1"月"2"日"`),
|
||||
57: timeFmtFunc(`2006"年"1"月"`),
|
||||
58: timeFmtFunc(`1"月"2"日"`),
|
||||
71: timeFmtFunc(`2/1/2006`),
|
||||
72: timeFmtFunc(`2-Jan-06`),
|
||||
73: timeFmtFunc(`2-Jan`),
|
||||
74: timeFmtFunc(`Jan-06`),
|
||||
75: timeFmtFunc(`15:04`),
|
||||
76: timeFmtFunc(`15:04:05`),
|
||||
77: timeFmtFunc(`2/1/2006 15:04`),
|
||||
78: timeFmtFunc(`04:05`),
|
||||
79: timeFmtFunc(`15:04:05`),
|
||||
80: timeFmtFunc(`04:05.9`),
|
||||
81: timeFmtFunc(`2/1/06`),
|
||||
18: timeFmtFunc(`3:04 PM`),
|
||||
19: timeFmtFunc(`3:04:05 PM`),
|
||||
|
||||
34: cnTimeFmtFunc(`PM 3"时"04"分"`),
|
||||
35: cnTimeFmtFunc(`PM 3"时"04"分"05"秒"`),
|
||||
55: cnTimeFmtFunc(`PM 3"时"04"分"`),
|
||||
56: cnTimeFmtFunc(`PM 3"时"04"分"05"秒`),
|
||||
|
||||
12: fracFmtFunc(1),
|
||||
13: fracFmtFunc(2),
|
||||
|
||||
69: fracFmtFunc(1),
|
||||
70: fracFmtFunc(2),
|
||||
|
||||
1: sprintfFunc(`%d`, 1),
|
||||
2: sprintfFunc(`%4.2f`, 1),
|
||||
59: sprintfFunc(`%d`, 1),
|
||||
60: sprintfFunc(`%4.2f`, 1),
|
||||
|
||||
9: sprintfFunc(`%d%%`, 100),
|
||||
10: sprintfFunc(`%4.2f%%`, 100),
|
||||
67: sprintfFunc(`%d%%`, 100),
|
||||
68: sprintfFunc(`%4.2f%%`, 100),
|
||||
|
||||
3: addCommas(sprintfFunc("%d", 1)),
|
||||
61: addCommas(sprintfFunc("%d", 1)),
|
||||
37: addNegParens(addCommas(sprintfFunc("%d", 1))),
|
||||
38: addNegParens(addCommas(sprintfFunc("%d", 1))),
|
||||
|
||||
4: addCommas(sprintfFunc("%4.2f", 1)),
|
||||
62: addCommas(sprintfFunc("%4.2f", 1)),
|
||||
39: addNegParens(addCommas(sprintfFunc("%4.2f", 1))),
|
||||
40: addNegParens(addCommas(sprintfFunc("%4.2f", 1))),
|
||||
|
||||
11: sprintfFunc(`%4.2E`, 1),
|
||||
48: sprintfFunc(`%3.1E`, 1),
|
||||
|
||||
41: zeroDashFunc(addCommas(sprintfFunc("%d", 1))),
|
||||
43: zeroDashFunc(addCommas(sprintfFunc("%4.2f", 1))),
|
||||
|
||||
42: switchFmtFunc(
|
||||
surround("$", addCommas(sprintfFunc("%d", 1)), ""),
|
||||
surround("$(", addCommas(sprintfFunc("%d", 1)), ")"),
|
||||
staticFmtFunc("$-")),
|
||||
44: switchFmtFunc(
|
||||
surround("$", addCommas(sprintfFunc("%4.2f", 1)), ""),
|
||||
surround("$(", addCommas(sprintfFunc("%4.2f", 1)), ")"),
|
||||
staticFmtFunc("$-")),
|
||||
}
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
package commonxl
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Formatter contains formatting methods common to Excel spreadsheets.
|
||||
type Formatter struct {
|
||||
flags uint64
|
||||
customCodes map[uint16]FmtFunc
|
||||
customCodeTypes map[uint16]CellType
|
||||
}
|
||||
|
||||
const (
|
||||
fMode1904 uint64 = 1
|
||||
)
|
||||
|
||||
// Mode1904 indicates that dates start on Jan 1, 1904
|
||||
// this setting was used in early MacOS Excel applications.
|
||||
func (x *Formatter) Mode1904(enabled bool) {
|
||||
if enabled {
|
||||
x.flags |= fMode1904
|
||||
} else {
|
||||
x.flags = x.flags &^ fMode1904
|
||||
}
|
||||
}
|
||||
|
||||
// Add a custom number format to the formatter.
|
||||
func (x *Formatter) Add(fmtID uint16, formatCode string) error {
|
||||
if x.customCodes == nil {
|
||||
x.customCodes = make(map[uint16]FmtFunc)
|
||||
x.customCodeTypes = make(map[uint16]CellType)
|
||||
}
|
||||
if strings.ToLower(formatCode) == "general" {
|
||||
x.customCodes[fmtID] = goFormatters[0]
|
||||
return nil
|
||||
}
|
||||
_, ok := goFormatters[fmtID]
|
||||
if ok {
|
||||
return errors.New("grate/commonxl: cannot replace default number formats")
|
||||
}
|
||||
|
||||
_, ok2 := x.customCodes[fmtID]
|
||||
if ok2 {
|
||||
return errors.New("grate/commonxl: cannot replace existing number formats")
|
||||
}
|
||||
|
||||
x.customCodes[fmtID], x.customCodeTypes[fmtID] = makeFormatter(formatCode)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Formatter) getCellType(fmtID uint16) (CellType, bool) {
|
||||
if ct, ok := builtInFormatTypes[fmtID]; ok {
|
||||
return ct, true
|
||||
}
|
||||
if x.customCodeTypes != nil {
|
||||
ct, ok := x.customCodeTypes[fmtID]
|
||||
return ct, ok
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
var (
|
||||
minsMatch = regexp.MustCompile("h.*m.*s")
|
||||
nonEsc = regexp.MustCompile(`([^"]|^)"`)
|
||||
squash = regexp.MustCompile(`[*_].`)
|
||||
fixEsc = regexp.MustCompile(`\\(.)`)
|
||||
|
||||
formatMatchBrackets = regexp.MustCompile(`\[[^\]]*\]`)
|
||||
formatMatchTextLiteral = regexp.MustCompile(`"[^"]*"`)
|
||||
)
|
||||
|
||||
func makeFormatter(s string) (FmtFunc, CellType) {
|
||||
//log.Printf("makeFormatter('%s')", s)
|
||||
// remove any coloring marks
|
||||
s = formatMatchBrackets.ReplaceAllString(s, "")
|
||||
if strings.Contains(s, ";") {
|
||||
parts := strings.Split(s, ";")
|
||||
posFF, ctypePos := makeFormatter(parts[0])
|
||||
rem := make([]FmtFunc, len(parts)-1)
|
||||
for i, ps := range parts[1:] {
|
||||
rem[i], _ = makeFormatter(ps)
|
||||
}
|
||||
return switchFmtFunc(posFF, rem...), ctypePos
|
||||
}
|
||||
|
||||
// escaped characters, and quoted text
|
||||
s2 := fixEsc.ReplaceAllString(s, "")
|
||||
s2 = formatMatchTextLiteral.ReplaceAllString(s, "")
|
||||
|
||||
if strings.ContainsAny(s2, "ymdhs") {
|
||||
// it's a date/time format
|
||||
|
||||
if loc := minsMatch.FindStringIndex(s); loc != nil {
|
||||
// m or mm in loc[0]:loc[1] is a minute format
|
||||
inner := s[loc[0]:loc[1]]
|
||||
inner = strings.Replace(inner, "mm", "04", 1)
|
||||
inner = strings.Replace(inner, "m", "4", 1)
|
||||
s = s[:loc[0]] + inner + s[loc[1]:]
|
||||
}
|
||||
dfreps := [][]string{
|
||||
{"hh", "15"}, {"h", "15"},
|
||||
{"ss", "05"}, {"s", "5"},
|
||||
{"mmmmm", "Jan"}, // super ambiguous, replace with 3-letter month
|
||||
{"mmmm", "January"}, {"mmm", "Jan"},
|
||||
{"mm", "01"}, {"m", "1"},
|
||||
{"dddd", "Monday"}, {"ddd", "Mon"},
|
||||
{"dd", "02"}, {"d", "2"},
|
||||
{"yyyy", "2006"}, {"yy", "06"},
|
||||
}
|
||||
if strings.Contains(s, "AM") || strings.Contains(s, "PM") {
|
||||
dfreps[0][1] = "03"
|
||||
dfreps[1][1] = "3"
|
||||
}
|
||||
for _, dfr := range dfreps {
|
||||
s = strings.Replace(s, dfr[0], dfr[1], 1)
|
||||
}
|
||||
|
||||
s = nonEsc.ReplaceAllString(s, `$1`)
|
||||
s = squash.ReplaceAllString(s, ``)
|
||||
s = fixEsc.ReplaceAllString(s, `$1`)
|
||||
|
||||
//log.Printf(" made time formatter '%s'", s)
|
||||
return timeFmtFunc(s), DateCell
|
||||
}
|
||||
|
||||
var ff FmtFunc
|
||||
var ctype CellType
|
||||
if strings.ContainsAny(s, ".Ee") {
|
||||
verb := "f"
|
||||
if strings.ContainsAny(s, "Ee") {
|
||||
verb = "E"
|
||||
}
|
||||
s = regexp.MustCompile("[eE]+[+-]0+").ReplaceAllString(s, "")
|
||||
s2 := strings.ReplaceAll(s, ",", "")
|
||||
i1 := strings.IndexAny(s2, "0")
|
||||
i2 := strings.IndexByte(s2, '.')
|
||||
i3 := strings.LastIndexAny(s2, "0.")
|
||||
mul := 1
|
||||
if strings.Contains(s2, "%") {
|
||||
mul = 100
|
||||
}
|
||||
sf := fmt.Sprintf("%%%d.%d%s", i3-i1, i3-i2, verb)
|
||||
//log.Printf(" made float formatter '%s'", sf)
|
||||
ff = sprintfFunc(sf, mul)
|
||||
ctype = FloatCell
|
||||
} else {
|
||||
s2 := strings.ReplaceAll(s, ",", "")
|
||||
i1 := strings.IndexAny(s2, "0")
|
||||
i2 := strings.LastIndexAny(s2, "0.")
|
||||
mul := 1
|
||||
if strings.Contains(s2, "%") {
|
||||
mul = 100
|
||||
}
|
||||
sf := fmt.Sprintf("%%%dd", i2-i1)
|
||||
if (i2 - i1) == 0 {
|
||||
sf = "%d"
|
||||
}
|
||||
//log.Printf(" made int formatter '%s'", sf)
|
||||
ff = sprintfFunc(sf, mul)
|
||||
ctype = IntegerCell
|
||||
}
|
||||
|
||||
if strings.Contains(s, ",") {
|
||||
ff = addCommas(ff)
|
||||
//log.Printf(" added commas")
|
||||
}
|
||||
|
||||
surReg := regexp.MustCompile(`[0#?,.]+`)
|
||||
prepost := surReg.Split(s, 2)
|
||||
if len(prepost) > 0 && len(prepost[0]) > 0 {
|
||||
prepost[0] = nonEsc.ReplaceAllString(prepost[0], `$1`)
|
||||
prepost[0] = squash.ReplaceAllString(prepost[0], ``)
|
||||
prepost[0] = fixEsc.ReplaceAllString(prepost[0], `$1`)
|
||||
}
|
||||
if len(prepost) == 1 {
|
||||
if prepost[0] == "@" {
|
||||
return identFunc, StringCell
|
||||
}
|
||||
//log.Printf(" added static ('%s')", prepost[0])
|
||||
return staticFmtFunc(prepost[0]), StringCell
|
||||
}
|
||||
if len(prepost[0]) > 0 || len(prepost[1]) > 0 {
|
||||
prepost[1] = nonEsc.ReplaceAllString(prepost[1], `$1`)
|
||||
prepost[1] = squash.ReplaceAllString(prepost[1], ``)
|
||||
prepost[1] = fixEsc.ReplaceAllString(prepost[1], `$1`)
|
||||
|
||||
ff = surround(prepost[0], ff, prepost[1])
|
||||
//log.Printf(" added surround ('%s' ... '%s')", prepost[0], prepost[1])
|
||||
}
|
||||
|
||||
return ff, ctype
|
||||
}
|
||||
|
||||
// Get the number format func to use for formatting values,
|
||||
// it returns false when fmtID is unknown.
|
||||
func (x *Formatter) Get(fmtID uint16) (FmtFunc, bool) {
|
||||
ff, ok := goFormatters[fmtID]
|
||||
if !ok {
|
||||
fs, ok2 := x.customCodes[fmtID]
|
||||
if ok2 {
|
||||
return fs, true
|
||||
}
|
||||
ff = identFunc
|
||||
}
|
||||
|
||||
return ff, ok
|
||||
}
|
||||
|
||||
// Apply the specified number format to the value.
|
||||
// Returns false when fmtID is unknown.
|
||||
func (x *Formatter) Apply(fmtID uint16, val interface{}) (string, bool) {
|
||||
ff, ok := goFormatters[fmtID]
|
||||
if !ok {
|
||||
fs, ok2 := x.customCodes[fmtID]
|
||||
if ok2 {
|
||||
return fs(x, val), true
|
||||
}
|
||||
}
|
||||
return ff(x, val), ok
|
||||
}
|
||||
|
||||
// builtInFormats are all the built-in number formats for XLS/XLSX.
|
||||
var builtInFormats = map[uint16]string{
|
||||
0: `General`,
|
||||
1: `0`,
|
||||
2: `0.00`,
|
||||
3: `#,##0`,
|
||||
4: `#,##0.00`,
|
||||
9: `0%`,
|
||||
10: `0.00%`,
|
||||
|
||||
11: `0.00E+00`,
|
||||
12: `# ?/?`,
|
||||
13: `# ??/??`,
|
||||
14: `mm-dd-yy`,
|
||||
15: `d-mmm-yy`,
|
||||
16: `d-mmm`,
|
||||
17: `mmm-yy`,
|
||||
18: `h:mm AM/PM`,
|
||||
19: `h:mm:ss AM/PM`,
|
||||
20: `h:mm`,
|
||||
21: `h:mm:ss`,
|
||||
22: `m/d/yy h:mm`,
|
||||
37: `#,##0 ;(#,##0)`,
|
||||
38: `#,##0 ;[Red](#,##0)`,
|
||||
39: `#,##0.00;(#,##0.00)`,
|
||||
40: `#,##0.00;[Red](#,##0.00)`,
|
||||
|
||||
41: `_(* #,##0_);_(* \(#,##0\);_(* "-"_);_(@_)`,
|
||||
42: `_("$"* #,##0_);_("$"* \(#,##0\);_("$"* "-"_);_(@_)`,
|
||||
43: `_(* #,##0.00_);_(* \(#,##0.00\);_(* "-"??_);_(@_)`,
|
||||
44: `_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)`,
|
||||
|
||||
45: `mm:ss`,
|
||||
46: `[h]:mm:ss`,
|
||||
47: `mmss.0`,
|
||||
48: `##0.0E+0`,
|
||||
49: `@`,
|
||||
|
||||
// zh-cn format codes
|
||||
27: `yyyy"年"m"月"`,
|
||||
28: `m"月"d"日"`,
|
||||
29: `m"月"d"日"`,
|
||||
30: `m-d-yy`,
|
||||
31: `yyyy"年"m"月"d"日"`,
|
||||
32: `h"时"mm"分"`,
|
||||
33: `h"时"mm"分"ss"秒"`,
|
||||
34: `上午/下午 h"时"mm"分"`,
|
||||
35: `上午/下午 h"时"mm"分"ss"秒"`,
|
||||
36: `yyyy"年"m"月"`,
|
||||
50: `yyyy"年"m"月"`,
|
||||
51: `m"月"d"日"`,
|
||||
52: `yyyy"年"m"月"`,
|
||||
53: `m"月"d"日"`,
|
||||
54: `m"月"d"日"`,
|
||||
55: `上午/下午 h"时"mm"分"`,
|
||||
56: `上午/下午 h"时"mm"分"ss"秒`,
|
||||
57: `yyyy"年"m"月"`,
|
||||
58: `m"月"d"日"`,
|
||||
|
||||
// th-th format codes (in the spec these have a "t" prefix?)
|
||||
59: `0`,
|
||||
60: `0.00`,
|
||||
61: `#,##0`,
|
||||
62: `#,##0.00`,
|
||||
67: `0%`,
|
||||
68: `0.00%`,
|
||||
69: `# ?/?`,
|
||||
70: `# ??/??`,
|
||||
|
||||
// th format code, but translated to aid the parser
|
||||
71: `d/m/yyyy`, // `ว/ด/ปปปป`,
|
||||
72: `d-mmm-yy`, // `ว-ดดด-ปป`,
|
||||
73: `d-mmm`, // `ว-ดดด`,
|
||||
74: `mmm-yy`, // `ดดด-ปป`,
|
||||
75: `h:mm`, // `ช:นน`,
|
||||
76: `h:mm:ss`, // `ช:นน:ทท`,
|
||||
77: `d/m/yyyy h:mm`, // `ว/ด/ปปปป ช:นน`,
|
||||
78: `mm:ss`, // `นน:ทท`,
|
||||
79: `[h]:mm:ss`, // `[ช]:นน:ทท`,
|
||||
80: `mm:ss.0`, // `นน:ทท.0`,
|
||||
81: `d/m/bb`, // `d/m/bb`,
|
||||
}
|
||||
|
||||
// builtInFormatTypes are the underlying datatypes for built-in number formats in XLS/XLSX.
|
||||
var builtInFormatTypes = map[uint16]CellType{
|
||||
// 0 has no defined type
|
||||
1: IntegerCell,
|
||||
2: FloatCell,
|
||||
3: IntegerCell,
|
||||
4: FloatCell,
|
||||
9: FloatCell,
|
||||
10: FloatCell,
|
||||
|
||||
11: FloatCell,
|
||||
12: FloatCell,
|
||||
13: FloatCell,
|
||||
14: DateCell,
|
||||
15: DateCell,
|
||||
16: DateCell,
|
||||
17: DateCell,
|
||||
18: DateCell,
|
||||
19: DateCell,
|
||||
20: DateCell,
|
||||
21: DateCell,
|
||||
22: DateCell,
|
||||
37: IntegerCell,
|
||||
38: IntegerCell,
|
||||
39: FloatCell,
|
||||
40: FloatCell,
|
||||
41: IntegerCell,
|
||||
42: IntegerCell,
|
||||
43: FloatCell,
|
||||
44: FloatCell,
|
||||
45: DateCell, // Durations?
|
||||
46: DateCell,
|
||||
47: DateCell,
|
||||
48: FloatCell,
|
||||
49: StringCell,
|
||||
27: DateCell,
|
||||
28: DateCell,
|
||||
29: DateCell,
|
||||
30: DateCell,
|
||||
31: DateCell,
|
||||
32: DateCell,
|
||||
33: DateCell,
|
||||
34: DateCell,
|
||||
35: DateCell,
|
||||
36: DateCell,
|
||||
50: DateCell,
|
||||
51: DateCell,
|
||||
52: DateCell,
|
||||
53: DateCell,
|
||||
54: DateCell,
|
||||
55: DateCell,
|
||||
56: DateCell,
|
||||
57: DateCell,
|
||||
58: DateCell,
|
||||
59: IntegerCell,
|
||||
60: FloatCell,
|
||||
61: IntegerCell,
|
||||
62: FloatCell,
|
||||
67: FloatCell,
|
||||
68: FloatCell,
|
||||
69: FloatCell,
|
||||
70: FloatCell,
|
||||
71: DateCell,
|
||||
72: DateCell,
|
||||
73: DateCell,
|
||||
74: DateCell,
|
||||
75: DateCell,
|
||||
76: DateCell,
|
||||
77: DateCell,
|
||||
78: DateCell,
|
||||
79: DateCell,
|
||||
80: DateCell,
|
||||
81: DateCell,
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package commonxl
|
||||
|
||||
import (
|
||||
"math"
|
||||
)
|
||||
|
||||
// DecimalToWholeFraction converts a floating point value into a whole
|
||||
// number and fraction approximation with at most nn digits in the numerator
|
||||
// and nd digits in the denominator.
|
||||
func DecimalToWholeFraction(val float64, nn, nd int) (whole, num, den int) {
|
||||
wholeF, part := math.Modf(val)
|
||||
if part == 0.0 {
|
||||
return int(wholeF), 0, 1
|
||||
}
|
||||
if part < 0.0 {
|
||||
part = -part
|
||||
}
|
||||
whole = int(wholeF)
|
||||
num, den = DecimalToFraction(part, nn, nd)
|
||||
return
|
||||
}
|
||||
|
||||
// DecimalToFraction converts a floating point value into a fraction
|
||||
// approximation with at most nn digits in the numerator and nd
|
||||
// digits in the denominator.
|
||||
func DecimalToFraction(val float64, nn, nd int) (num, den int) {
|
||||
// http://web.archive.org/web/20111027100847/http://homepage.smc.edu/kennedy_john/DEC2FRAC.PDF
|
||||
sign := 1
|
||||
z := val
|
||||
if val < 0 {
|
||||
sign = -1
|
||||
z = -val
|
||||
}
|
||||
if nn == 0 {
|
||||
nn = 2
|
||||
}
|
||||
if nd == 0 {
|
||||
nd = 2
|
||||
}
|
||||
maxn := math.Pow(10.0, float64(nn)) // numerator with nn digits
|
||||
maxd := math.Pow(10.0, float64(nd)) // denominator with nd digits
|
||||
|
||||
_, fracPart := math.Modf(val)
|
||||
if fracPart == 0.0 {
|
||||
return int(z) * sign, 1
|
||||
}
|
||||
if fracPart < 1e-9 {
|
||||
return sign, int(1e9)
|
||||
}
|
||||
if fracPart > 1e9 {
|
||||
return int(1e9) * sign, 1
|
||||
}
|
||||
|
||||
diff := 1.0
|
||||
denom := 1.0
|
||||
numer := 0.0
|
||||
var lastDenom, lastNumer float64
|
||||
for diff > 1e-10 && z != math.Floor(z) {
|
||||
z = 1 / (z - math.Floor(z))
|
||||
tmp := denom
|
||||
denom = (denom * math.Floor(z)) + lastDenom
|
||||
lastDenom = tmp
|
||||
lastNumer = numer
|
||||
numer = math.Round(val * denom)
|
||||
if numer >= maxn || denom >= maxd {
|
||||
return sign * int(lastNumer), int(lastDenom)
|
||||
}
|
||||
diff = val - (numer / denom)
|
||||
if diff < 0.0 {
|
||||
diff = -diff
|
||||
}
|
||||
}
|
||||
return sign * int(numer), int(denom)
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
package commonxl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/pbnjay/grate"
|
||||
)
|
||||
|
||||
// Sheet holds raw and rendered values for a spreadsheet.
|
||||
type Sheet struct {
|
||||
Formatter *Formatter
|
||||
NumRows int
|
||||
NumCols int
|
||||
Rows [][]Cell
|
||||
|
||||
CurRow int
|
||||
}
|
||||
|
||||
// Resize the sheet for the number of rows and cols given.
|
||||
// Newly added cells default to blank.
|
||||
func (s *Sheet) Resize(rows, cols int) {
|
||||
for i := range s.Rows {
|
||||
if i > rows {
|
||||
break
|
||||
}
|
||||
n := cols - len(s.Rows[i])
|
||||
if n <= 0 {
|
||||
continue
|
||||
}
|
||||
s.Rows[i] = append(s.Rows[i], make([]Cell, n)...)
|
||||
}
|
||||
|
||||
if rows <= 0 {
|
||||
rows = 1
|
||||
}
|
||||
if cols <= 0 {
|
||||
cols = 1
|
||||
}
|
||||
s.CurRow = 0
|
||||
s.NumRows = rows
|
||||
s.NumCols = cols
|
||||
|
||||
for rows >= len(s.Rows) {
|
||||
s.Rows = append(s.Rows, make([]Cell, cols))
|
||||
}
|
||||
}
|
||||
|
||||
// Put the value at the cell location given.
|
||||
func (s *Sheet) Put(row, col int, value interface{}, fmtNum uint16) {
|
||||
//log.Println(row, col, value, fmtNum)
|
||||
if row >= s.NumRows || col >= s.NumCols {
|
||||
if grate.Debug {
|
||||
log.Printf("grate: cell out of bounds row %d>=%d, col %d>=%d",
|
||||
row, s.NumRows, col, s.NumCols)
|
||||
}
|
||||
|
||||
// per the spec, this is an invalid Excel file
|
||||
// but we'll resize in place instead of crashing out
|
||||
if row >= s.NumRows {
|
||||
s.NumRows = row + 1
|
||||
}
|
||||
if col >= s.NumCols {
|
||||
s.NumCols = col + 1
|
||||
}
|
||||
s.Resize(s.NumRows, s.NumCols)
|
||||
}
|
||||
|
||||
if spec, ok := value.(string); ok {
|
||||
if spec == grate.EndRowMerged || spec == grate.EndColumnMerged || spec == grate.ContinueRowMerged || spec == grate.ContinueColumnMerged {
|
||||
s.Rows[row][col] = NewCell(value)
|
||||
s.Rows[row][col][1] = StaticCell
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
ct, ok := s.Formatter.getCellType(fmtNum)
|
||||
// descrybe patch: Excel shows text as-is under a numeric format; upstream coerced it
|
||||
// (a "0"-formatted "Šifra" header became int 0).
|
||||
if _, isText := value.(string); isText && ct != StringCell {
|
||||
ok = false
|
||||
}
|
||||
if !ok || fmtNum == 0 {
|
||||
s.Rows[row][col] = NewCell(value)
|
||||
} else {
|
||||
s.Rows[row][col] = NewCellWithType(value, ct, s.Formatter)
|
||||
}
|
||||
s.Rows[row][col].SetFormatNumber(fmtNum)
|
||||
}
|
||||
|
||||
// Set changes the value in an existing cell location.
|
||||
// NB Currently only used for populating string results for formulas.
|
||||
func (s *Sheet) Set(row, col int, value interface{}) {
|
||||
if row > s.NumRows || col > s.NumCols {
|
||||
log.Println("grate: cell out of bounds")
|
||||
return
|
||||
}
|
||||
|
||||
s.Rows[row][col][0] = value
|
||||
s.Rows[row][col][1] = StringCell
|
||||
}
|
||||
|
||||
// SetURL adds a hyperlink to an existing cell location.
|
||||
func (s *Sheet) SetURL(row, col int, link string) {
|
||||
if row > s.NumRows || col > s.NumCols {
|
||||
log.Println("grate: cell out of bounds")
|
||||
return
|
||||
}
|
||||
|
||||
s.Rows[row][col].SetURL(link)
|
||||
}
|
||||
|
||||
// Next advances to the next record of content.
|
||||
// It MUST be called prior to any Scan().
|
||||
func (s *Sheet) Next() bool {
|
||||
if (s.CurRow + 1) > len(s.Rows) {
|
||||
return false
|
||||
}
|
||||
s.CurRow++
|
||||
return true
|
||||
}
|
||||
|
||||
// Raw extracts the raw Cell interfaces underlying the current row.
|
||||
func (s *Sheet) Raw() []Cell {
|
||||
rr := make([]Cell, s.NumCols)
|
||||
for i, cell := range s.Rows[s.CurRow-1] {
|
||||
rr[i] = cell.Clone()
|
||||
}
|
||||
return rr
|
||||
}
|
||||
|
||||
// Strings extracts values from the current record into a list of strings.
|
||||
func (s *Sheet) Strings() []string {
|
||||
res := make([]string, s.NumCols)
|
||||
for i, cell := range s.Rows[s.CurRow-1] {
|
||||
if cell.Type() == BlankCell {
|
||||
res[i] = ""
|
||||
continue
|
||||
}
|
||||
if cell.Type() == StaticCell {
|
||||
res[i] = cell.Value().(string)
|
||||
continue
|
||||
}
|
||||
val := cell.Value()
|
||||
fs, ok := s.Formatter.Apply(cell.FormatNo(), val)
|
||||
if !ok {
|
||||
fs = fmt.Sprint(val)
|
||||
}
|
||||
res[i] = fs
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// Types extracts the data types from the current record into a list.
|
||||
// options: "boolean", "integer", "float", "string", "date",
|
||||
// and special cases: "blank", "hyperlink" which are string types
|
||||
func (s *Sheet) Types() []string {
|
||||
res := make([]string, s.NumCols)
|
||||
for i, cell := range s.Rows[s.CurRow-1] {
|
||||
res[i] = cell.Type().String()
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// Formats extracts the format code for the current record into a list.
|
||||
func (s *Sheet) Formats() []string {
|
||||
ok := true
|
||||
res := make([]string, s.NumCols)
|
||||
for i, cell := range s.Rows[s.CurRow-1] {
|
||||
res[i], ok = builtInFormats[cell.FormatNo()]
|
||||
if !ok {
|
||||
res[i] = fmt.Sprint(cell.FormatNo())
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// Scan extracts values from the current record into the provided arguments
|
||||
// Arguments must be pointers to one of 5 supported types:
|
||||
// bool, int64, float64, string, or time.Time
|
||||
// If invalid, returns ErrInvalidScanType
|
||||
func (s *Sheet) Scan(args ...interface{}) error {
|
||||
row := s.Rows[s.CurRow-1]
|
||||
|
||||
for i, a := range args {
|
||||
val := row[i].Value()
|
||||
|
||||
switch v := a.(type) {
|
||||
case bool, int64, float64, string, time.Time:
|
||||
return fmt.Errorf("scan destinations must be pointer (arg %d is not)", i)
|
||||
case *bool:
|
||||
if x, ok := val.(bool); ok {
|
||||
*v = x
|
||||
} else {
|
||||
return fmt.Errorf("scan destination %d expected *%T, not *bool", i, val)
|
||||
}
|
||||
case *int64:
|
||||
if x, ok := val.(int64); ok {
|
||||
*v = x
|
||||
} else {
|
||||
return fmt.Errorf("scan destination %d expected *%T, not *int64", i, val)
|
||||
}
|
||||
case *float64:
|
||||
if x, ok := val.(float64); ok {
|
||||
*v = x
|
||||
} else {
|
||||
return fmt.Errorf("scan destination %d expected *%T, not *float64", i, val)
|
||||
}
|
||||
case *string:
|
||||
if x, ok := val.(string); ok {
|
||||
*v = x
|
||||
} else {
|
||||
return fmt.Errorf("scan destination %d expected *%T, not *string", i, val)
|
||||
}
|
||||
case *time.Time:
|
||||
if x, ok := val.(time.Time); ok {
|
||||
*v = x
|
||||
} else {
|
||||
return fmt.Errorf("scan destination %d expected *%T, not *time.Time", i, val)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("scan destination for arg %d is not supported (%T)", i, a)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsEmpty returns true if there are no data values.
|
||||
func (s *Sheet) IsEmpty() bool {
|
||||
return (s.NumCols <= 1 && s.NumRows <= 1)
|
||||
}
|
||||
|
||||
// Err returns the last error that occured.
|
||||
func (s *Sheet) Err() error {
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user