forked from qax-os/excelize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
calc.go
3147 lines (3012 loc) · 84.2 KB
/
calc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 - 2020 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 / XLSM / XLTM files. Supports reading and writing
// spreadsheet documents generated by Microsoft Exce™ 2007 and later. Supports
// complex components by high compatibility, and provided streaming API for
// generating or reading data from a worksheet with huge amounts of data. This
// library needs Go version 1.10 or later.
package excelize
import (
"bytes"
"container/list"
"errors"
"fmt"
"math"
"math/rand"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/xuri/efp"
)
// Excel formula errors
const (
formulaErrorDIV = "#DIV/0!"
formulaErrorNAME = "#NAME?"
formulaErrorNA = "#N/A"
formulaErrorNUM = "#NUM!"
formulaErrorVALUE = "#VALUE!"
formulaErrorREF = "#REF!"
formulaErrorNULL = "#NULL"
formulaErrorSPILL = "#SPILL!"
formulaErrorCALC = "#CALC!"
formulaErrorGETTINGDATA = "#GETTING_DATA"
)
// cellRef defines the structure of a cell reference.
type cellRef struct {
Col int
Row int
Sheet string
}
// cellRef defines the structure of a cell range.
type cellRange struct {
From cellRef
To cellRef
}
// formula criteria condition enumeration.
const (
_ byte = iota
criteriaEq
criteriaLe
criteriaGe
criteriaL
criteriaG
criteriaBeg
criteriaEnd
)
// formulaCriteria defined formula criteria parser result.
type formulaCriteria struct {
Type byte
Condition string
}
// ArgType is the type if formula argument type.
type ArgType byte
// Formula argument types enumeration.
const (
ArgUnknown ArgType = iota
ArgString
ArgMatrix
)
// formulaArg is the argument of a formula or function.
type formulaArg struct {
String string
Matrix [][]formulaArg
Type ArgType
}
// formulaFuncs is the type of the formula functions.
type formulaFuncs struct{}
// CalcCellValue provides a function to get calculated cell value. This
// feature is currently in working processing. Array formula, table formula
// and some other formulas are not supported currently.
//
// Supported formulas:
//
// ABS, ACOS, ACOSH, ACOT, ACOTH, ARABIC, ASIN, ASINH, ATAN2, ATANH, BASE,
// CEILING, CEILING.MATH, CEILING.PRECISE, COMBIN, COMBINA, COS, COSH, COT,
// COTH, COUNTA, CSC, CSCH, DECIMAL, DEGREES, EVEN, EXP, FACT, FACTDOUBLE,
// FLOOR, FLOOR.MATH, FLOOR.PRECISE, GCD, INT, ISBLANK, ISERR, ISERROR,
// ISEVEN, ISNA, ISNONTEXT, ISNUMBER, ISO.CEILING, ISODD, LCM, LN, LOG,
// LOG10, MDETERM, MEDIAN, MOD, MROUND, MULTINOMIAL, MUNIT, NA, ODD, PI,
// POWER, PRODUCT, QUOTIENT, RADIANS, RAND, RANDBETWEEN, ROUND, ROUNDDOWN,
// ROUNDUP, SEC, SECH, SIGN, SIN, SINH, SQRT, SQRTPI, SUM, SUMIF, SUMSQ,
// TAN, TANH, TRUNC
//
func (f *File) CalcCellValue(sheet, cell string) (result string, err error) {
var (
formula string
token efp.Token
)
if formula, err = f.GetCellFormula(sheet, cell); err != nil {
return
}
ps := efp.ExcelParser()
tokens := ps.Parse(formula)
if tokens == nil {
return
}
if token, err = f.evalInfixExp(sheet, tokens); err != nil {
return
}
result = token.TValue
return
}
// getPriority calculate arithmetic operator priority.
func getPriority(token efp.Token) (pri int) {
var priority = map[string]int{
"*": 2,
"/": 2,
"+": 1,
"-": 1,
}
pri, _ = priority[token.TValue]
if token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix {
pri = 3
}
if token.TSubType == efp.TokenSubTypeStart && token.TType == efp.TokenTypeSubexpression { // (
pri = 0
}
return
}
// evalInfixExp evaluate syntax analysis by given infix expression after
// lexical analysis. Evaluate an infix expression containing formulas by
// stacks:
//
// opd - Operand
// opt - Operator
// opf - Operation formula
// opfd - Operand of the operation formula
// opft - Operator of the operation formula
//
// Evaluate arguments of the operation formula by list:
//
// args - Arguments of the operation formula
//
// TODO: handle subtypes: Nothing, Text, Logical, Error, Concatenation, Intersection, Union
//
func (f *File) evalInfixExp(sheet string, tokens []efp.Token) (efp.Token, error) {
var err error
opdStack, optStack, opfStack, opfdStack, opftStack := NewStack(), NewStack(), NewStack(), NewStack(), NewStack()
argsList := list.New()
for i := 0; i < len(tokens); i++ {
token := tokens[i]
// out of function stack
if opfStack.Len() == 0 {
if err = f.parseToken(sheet, token, opdStack, optStack); err != nil {
return efp.Token{}, err
}
}
// function start
if token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStart {
opfStack.Push(token)
continue
}
// in function stack, walk 2 token at once
if opfStack.Len() > 0 {
var nextToken efp.Token
if i+1 < len(tokens) {
nextToken = tokens[i+1]
}
// current token is args or range, skip next token, order required: parse reference first
if token.TSubType == efp.TokenSubTypeRange {
if !opftStack.Empty() {
// parse reference: must reference at here
result, err := f.parseReference(sheet, token.TValue)
if err != nil {
return efp.Token{TValue: formulaErrorNAME}, err
}
if result.Type != ArgString {
return efp.Token{}, errors.New(formulaErrorVALUE)
}
opfdStack.Push(efp.Token{
TType: efp.TokenTypeOperand,
TSubType: efp.TokenSubTypeNumber,
TValue: result.String,
})
continue
}
if nextToken.TType == efp.TokenTypeArgument || nextToken.TType == efp.TokenTypeFunction {
// parse reference: reference or range at here
result, err := f.parseReference(sheet, token.TValue)
if err != nil {
return efp.Token{TValue: formulaErrorNAME}, err
}
if result.Type == ArgUnknown {
return efp.Token{}, errors.New(formulaErrorVALUE)
}
argsList.PushBack(result)
continue
}
}
// check current token is opft
if err = f.parseToken(sheet, token, opfdStack, opftStack); err != nil {
return efp.Token{}, err
}
// current token is arg
if token.TType == efp.TokenTypeArgument {
for !opftStack.Empty() {
// calculate trigger
topOpt := opftStack.Peek().(efp.Token)
if err := calculate(opfdStack, topOpt); err != nil {
return efp.Token{}, err
}
opftStack.Pop()
}
if !opfdStack.Empty() {
argsList.PushBack(formulaArg{
String: opfdStack.Pop().(efp.Token).TValue,
Type: ArgString,
})
}
continue
}
// current token is logical
if token.TType == efp.OperatorsInfix && token.TSubType == efp.TokenSubTypeLogical {
}
// current token is text
if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeText {
argsList.PushBack(formulaArg{
String: token.TValue,
Type: ArgString,
})
}
// current token is function stop
if token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStop {
for !opftStack.Empty() {
// calculate trigger
topOpt := opftStack.Peek().(efp.Token)
if err := calculate(opfdStack, topOpt); err != nil {
return efp.Token{}, err
}
opftStack.Pop()
}
// push opfd to args
if opfdStack.Len() > 0 {
argsList.PushBack(formulaArg{
String: opfdStack.Pop().(efp.Token).TValue,
Type: ArgString,
})
}
// call formula function to evaluate
result, err := callFuncByName(&formulaFuncs{}, strings.NewReplacer(
"_xlfn", "", ".", "").Replace(opfStack.Peek().(efp.Token).TValue),
[]reflect.Value{reflect.ValueOf(argsList)})
if err != nil {
return efp.Token{}, err
}
argsList.Init()
opfStack.Pop()
if opfStack.Len() > 0 { // still in function stack
opfdStack.Push(efp.Token{TValue: result, TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
} else {
opdStack.Push(efp.Token{TValue: result, TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
}
}
}
}
for optStack.Len() != 0 {
topOpt := optStack.Peek().(efp.Token)
if err = calculate(opdStack, topOpt); err != nil {
return efp.Token{}, err
}
optStack.Pop()
}
if opdStack.Len() == 0 {
return efp.Token{}, errors.New("formula not valid")
}
return opdStack.Peek().(efp.Token), err
}
// calcAdd evaluate addition arithmetic operations.
func calcAdd(opdStack *Stack) error {
if opdStack.Len() < 2 {
return errors.New("formula not valid")
}
rOpd := opdStack.Pop().(efp.Token)
lOpd := opdStack.Pop().(efp.Token)
lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
if err != nil {
return err
}
rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
if err != nil {
return err
}
result := lOpdVal + rOpdVal
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
return nil
}
// calcSubtract evaluate subtraction arithmetic operations.
func calcSubtract(opdStack *Stack) error {
if opdStack.Len() < 2 {
return errors.New("formula not valid")
}
rOpd := opdStack.Pop().(efp.Token)
lOpd := opdStack.Pop().(efp.Token)
lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
if err != nil {
return err
}
rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
if err != nil {
return err
}
result := lOpdVal - rOpdVal
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
return nil
}
// calcMultiply evaluate multiplication arithmetic operations.
func calcMultiply(opdStack *Stack) error {
if opdStack.Len() < 2 {
return errors.New("formula not valid")
}
rOpd := opdStack.Pop().(efp.Token)
lOpd := opdStack.Pop().(efp.Token)
lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
if err != nil {
return err
}
rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
if err != nil {
return err
}
result := lOpdVal * rOpdVal
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
return nil
}
// calcDivide evaluate division arithmetic operations.
func calcDivide(opdStack *Stack) error {
if opdStack.Len() < 2 {
return errors.New("formula not valid")
}
rOpd := opdStack.Pop().(efp.Token)
lOpd := opdStack.Pop().(efp.Token)
lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
if err != nil {
return err
}
rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
if err != nil {
return err
}
result := lOpdVal / rOpdVal
if rOpdVal == 0 {
return errors.New(formulaErrorDIV)
}
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
return nil
}
// calculate evaluate basic arithmetic operations.
func calculate(opdStack *Stack, opt efp.Token) error {
if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorPrefix {
if opdStack.Len() < 1 {
return errors.New("formula not valid")
}
opd := opdStack.Pop().(efp.Token)
opdVal, err := strconv.ParseFloat(opd.TValue, 64)
if err != nil {
return err
}
result := 0 - opdVal
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
}
if opt.TValue == "+" {
if err := calcAdd(opdStack); err != nil {
return err
}
}
if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorInfix {
if err := calcSubtract(opdStack); err != nil {
return err
}
}
if opt.TValue == "*" {
if err := calcMultiply(opdStack); err != nil {
return err
}
}
if opt.TValue == "/" {
if err := calcDivide(opdStack); err != nil {
return err
}
}
return nil
}
// parseOperatorPrefixToken parse operator prefix token.
func (f *File) parseOperatorPrefixToken(optStack, opdStack *Stack, token efp.Token) (err error) {
if optStack.Len() == 0 {
optStack.Push(token)
} else {
tokenPriority := getPriority(token)
topOpt := optStack.Peek().(efp.Token)
topOptPriority := getPriority(topOpt)
if tokenPriority > topOptPriority {
optStack.Push(token)
} else {
for tokenPriority <= topOptPriority {
optStack.Pop()
if err = calculate(opdStack, topOpt); err != nil {
return
}
if optStack.Len() > 0 {
topOpt = optStack.Peek().(efp.Token)
topOptPriority = getPriority(topOpt)
continue
}
break
}
optStack.Push(token)
}
}
return
}
// isOperatorPrefixToken determine if the token is parse operator prefix
// token.
func isOperatorPrefixToken(token efp.Token) bool {
if (token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix) ||
token.TValue == "+" || token.TValue == "-" || token.TValue == "*" || token.TValue == "/" {
return true
}
return false
}
func (f *File) getDefinedNameRefTo(definedNameName string, currentSheet string) (refTo string) {
for _, definedName := range f.GetDefinedName() {
if definedName.Name == definedNameName {
refTo = definedName.RefersTo
// worksheet scope takes precedence over scope workbook when both definedNames exist
if definedName.Scope == currentSheet {
break
}
}
}
return refTo
}
// parseToken parse basic arithmetic operator priority and evaluate based on
// operators and operands.
func (f *File) parseToken(sheet string, token efp.Token, opdStack, optStack *Stack) error {
// parse reference: must reference at here
if token.TSubType == efp.TokenSubTypeRange {
refTo := f.getDefinedNameRefTo(token.TValue, sheet)
if refTo != "" {
token.TValue = refTo
}
result, err := f.parseReference(sheet, token.TValue)
if err != nil {
return errors.New(formulaErrorNAME)
}
if result.Type != ArgString {
return errors.New(formulaErrorVALUE)
}
token.TValue = result.String
token.TType = efp.TokenTypeOperand
token.TSubType = efp.TokenSubTypeNumber
}
if isOperatorPrefixToken(token) {
if err := f.parseOperatorPrefixToken(optStack, opdStack, token); err != nil {
return err
}
}
if token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStart { // (
optStack.Push(token)
}
if token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStop { // )
for optStack.Peek().(efp.Token).TSubType != efp.TokenSubTypeStart && optStack.Peek().(efp.Token).TType != efp.TokenTypeSubexpression { // != (
topOpt := optStack.Peek().(efp.Token)
if err := calculate(opdStack, topOpt); err != nil {
return err
}
optStack.Pop()
}
optStack.Pop()
}
// opd
if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeNumber {
opdStack.Push(token)
}
return nil
}
// parseReference parse reference and extract values by given reference
// characters and default sheet name.
func (f *File) parseReference(sheet, reference string) (arg formulaArg, err error) {
reference = strings.Replace(reference, "$", "", -1)
refs, cellRanges, cellRefs := list.New(), list.New(), list.New()
for _, ref := range strings.Split(reference, ":") {
tokens := strings.Split(ref, "!")
cr := cellRef{}
if len(tokens) == 2 { // have a worksheet name
cr.Sheet = tokens[0]
if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[1]); err != nil {
return
}
if refs.Len() > 0 {
e := refs.Back()
cellRefs.PushBack(e.Value.(cellRef))
refs.Remove(e)
}
refs.PushBack(cr)
continue
}
if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[0]); err != nil {
return
}
e := refs.Back()
if e == nil {
cr.Sheet = sheet
refs.PushBack(cr)
continue
}
cellRanges.PushBack(cellRange{
From: e.Value.(cellRef),
To: cr,
})
refs.Remove(e)
}
if refs.Len() > 0 {
e := refs.Back()
cellRefs.PushBack(e.Value.(cellRef))
refs.Remove(e)
}
arg, err = f.rangeResolver(cellRefs, cellRanges)
return
}
// prepareValueRange prepare value range.
func prepareValueRange(cr cellRange, valueRange []int) {
if cr.From.Row < valueRange[0] || valueRange[0] == 0 {
valueRange[0] = cr.From.Row
}
if cr.From.Col < valueRange[2] || valueRange[2] == 0 {
valueRange[2] = cr.From.Col
}
if cr.To.Row > valueRange[1] || valueRange[1] == 0 {
valueRange[1] = cr.To.Row
}
if cr.To.Col > valueRange[3] || valueRange[3] == 0 {
valueRange[3] = cr.To.Col
}
}
// prepareValueRef prepare value reference.
func prepareValueRef(cr cellRef, valueRange []int) {
if cr.Row < valueRange[0] || valueRange[0] == 0 {
valueRange[0] = cr.Row
}
if cr.Col < valueRange[2] || valueRange[2] == 0 {
valueRange[2] = cr.Col
}
if cr.Row > valueRange[1] || valueRange[1] == 0 {
valueRange[1] = cr.Row
}
if cr.Col > valueRange[3] || valueRange[3] == 0 {
valueRange[3] = cr.Col
}
}
// rangeResolver extract value as string from given reference and range list.
// This function will not ignore the empty cell. For example, A1:A2:A2:B3 will
// be reference A1:B3.
func (f *File) rangeResolver(cellRefs, cellRanges *list.List) (arg formulaArg, err error) {
// value range order: from row, to row, from column, to column
valueRange := []int{0, 0, 0, 0}
var sheet string
// prepare value range
for temp := cellRanges.Front(); temp != nil; temp = temp.Next() {
cr := temp.Value.(cellRange)
if cr.From.Sheet != cr.To.Sheet {
err = errors.New(formulaErrorVALUE)
}
rng := []int{cr.From.Col, cr.From.Row, cr.To.Col, cr.To.Row}
sortCoordinates(rng)
cr.From.Col, cr.From.Row, cr.To.Col, cr.To.Row = rng[0], rng[1], rng[2], rng[3]
prepareValueRange(cr, valueRange)
if cr.From.Sheet != "" {
sheet = cr.From.Sheet
}
}
for temp := cellRefs.Front(); temp != nil; temp = temp.Next() {
cr := temp.Value.(cellRef)
if cr.Sheet != "" {
sheet = cr.Sheet
}
prepareValueRef(cr, valueRange)
}
// extract value from ranges
if cellRanges.Len() > 0 {
arg.Type = ArgMatrix
for row := valueRange[0]; row <= valueRange[1]; row++ {
var matrixRow = []formulaArg{}
for col := valueRange[2]; col <= valueRange[3]; col++ {
var cell, value string
if cell, err = CoordinatesToCellName(col, row); err != nil {
return
}
if value, err = f.GetCellValue(sheet, cell); err != nil {
return
}
matrixRow = append(matrixRow, formulaArg{
String: value,
Type: ArgString,
})
}
arg.Matrix = append(arg.Matrix, matrixRow)
}
return
}
// extract value from references
for temp := cellRefs.Front(); temp != nil; temp = temp.Next() {
cr := temp.Value.(cellRef)
var cell string
if cell, err = CoordinatesToCellName(cr.Col, cr.Row); err != nil {
return
}
if arg.String, err = f.GetCellValue(cr.Sheet, cell); err != nil {
return
}
arg.Type = ArgString
}
return
}
// callFuncByName calls the no error or only error return function with
// reflect by given receiver, name and parameters.
func callFuncByName(receiver interface{}, name string, params []reflect.Value) (result string, err error) {
function := reflect.ValueOf(receiver).MethodByName(name)
if function.IsValid() {
rt := function.Call(params)
if len(rt) == 0 {
return
}
if !rt[1].IsNil() {
err = rt[1].Interface().(error)
return
}
result = rt[0].Interface().(string)
return
}
err = fmt.Errorf("not support %s function", name)
return
}
// formulaCriteriaParser parse formula criteria.
func formulaCriteriaParser(exp string) (fc *formulaCriteria) {
fc = &formulaCriteria{}
if exp == "" {
return
}
if match := regexp.MustCompile(`^([0-9]+)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaEq, match[1]
return
}
if match := regexp.MustCompile(`^=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaEq, match[1]
return
}
if match := regexp.MustCompile(`^<(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaLe, match[1]
return
}
if match := regexp.MustCompile(`^>(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaGe, match[1]
return
}
if match := regexp.MustCompile(`^<=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaL, match[1]
return
}
if match := regexp.MustCompile(`^>=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaG, match[1]
return
}
if strings.Contains(exp, "*") {
if strings.HasPrefix(exp, "*") {
fc.Type, fc.Condition = criteriaEnd, strings.TrimPrefix(exp, "*")
}
if strings.HasSuffix(exp, "*") {
fc.Type, fc.Condition = criteriaBeg, strings.TrimSuffix(exp, "*")
}
return
}
fc.Type, fc.Condition = criteriaEq, exp
return
}
// formulaCriteriaEval evaluate formula criteria expression.
func formulaCriteriaEval(val string, criteria *formulaCriteria) (result bool, err error) {
var value, expected float64
var prepareValue = func(val, cond string) (value float64, expected float64, err error) {
value, _ = strconv.ParseFloat(val, 64)
if expected, err = strconv.ParseFloat(criteria.Condition, 64); err != nil {
return
}
return
}
switch criteria.Type {
case criteriaEq:
return val == criteria.Condition, err
case criteriaLe:
if value, expected, err = prepareValue(val, criteria.Condition); err != nil {
return
}
return value <= expected, err
case criteriaGe:
if value, expected, err = prepareValue(val, criteria.Condition); err != nil {
return
}
return value >= expected, err
case criteriaL:
if value, expected, err = prepareValue(val, criteria.Condition); err != nil {
return
}
return value < expected, err
case criteriaG:
if value, expected, err = prepareValue(val, criteria.Condition); err != nil {
return
}
return value > expected, err
case criteriaBeg:
return strings.HasPrefix(val, criteria.Condition), err
case criteriaEnd:
return strings.HasSuffix(val, criteria.Condition), err
}
return
}
// Math and Trigonometric functions
// ABS function returns the absolute value of any supplied number. The syntax
// of the function is:
//
// ABS(number)
//
func (fn *formulaFuncs) ABS(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ABS requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Abs(val))
return
}
// ACOS function calculates the arccosine (i.e. the inverse cosine) of a given
// number, and returns an angle, in radians, between 0 and π. The syntax of
// the function is:
//
// ACOS(number)
//
func (fn *formulaFuncs) ACOS(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ACOS requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Acos(val))
return
}
// ACOSH function calculates the inverse hyperbolic cosine of a supplied number.
// of the function is:
//
// ACOSH(number)
//
func (fn *formulaFuncs) ACOSH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ACOSH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Acosh(val))
return
}
// ACOT function calculates the arccotangent (i.e. the inverse cotangent) of a
// given number, and returns an angle, in radians, between 0 and π. The syntax
// of the function is:
//
// ACOT(number)
//
func (fn *formulaFuncs) ACOT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ACOT requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Pi/2-math.Atan(val))
return
}
// ACOTH function calculates the hyperbolic arccotangent (coth) of a supplied
// value. The syntax of the function is:
//
// ACOTH(number)
//
func (fn *formulaFuncs) ACOTH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ACOTH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Atanh(1/val))
return
}
// ARABIC function converts a Roman numeral into an Arabic numeral. The syntax
// of the function is:
//
// ARABIC(text)
//
func (fn *formulaFuncs) ARABIC(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ARABIC requires 1 numeric argument")
return
}
charMap := map[rune]float64{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
val, last, prefix := 0.0, 0.0, 1.0
for _, char := range argsList.Front().Value.(formulaArg).String {
digit := 0.0
if char == '-' {
prefix = -1
continue
}
digit, _ = charMap[char]
val += digit
switch {
case last == digit && (last == 5 || last == 50 || last == 500):
result = formulaErrorVALUE
return
case 2*last == digit:
result = formulaErrorVALUE
return
}
if last < digit {
val -= 2 * last
}
last = digit
}
result = fmt.Sprintf("%g", prefix*val)
return
}
// ASIN function calculates the arcsine (i.e. the inverse sine) of a given
// number, and returns an angle, in radians, between -π/2 and π/2. The syntax
// of the function is:
//
// ASIN(number)
//
func (fn *formulaFuncs) ASIN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ASIN requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Asin(val))
return
}
// ASINH function calculates the inverse hyperbolic sine of a supplied number.
// The syntax of the function is:
//
// ASINH(number)
//
func (fn *formulaFuncs) ASINH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ASINH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Asinh(val))
return
}
// ATAN function calculates the arctangent (i.e. the inverse tangent) of a
// given number, and returns an angle, in radians, between -π/2 and +π/2. The
// syntax of the function is:
//
// ATAN(number)
//
func (fn *formulaFuncs) ATAN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ATAN requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Atan(val))
return
}
// ATANH function calculates the inverse hyperbolic tangent of a supplied
// number. The syntax of the function is:
//
// ATANH(number)
//
func (fn *formulaFuncs) ATANH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ATANH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Atanh(val))
return
}
// ATAN2 function calculates the arctangent (i.e. the inverse tangent) of a
// given set of x and y coordinates, and returns an angle, in radians, between
// -π/2 and +π/2. The syntax of the function is:
//
// ATAN2(x_num,y_num)
//
func (fn *formulaFuncs) ATAN2(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("ATAN2 requires 2 numeric arguments")
return
}
var x, y float64
if x, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)