diff --git a/calc.go b/calc.go index 6c0a3b0..46d7852 100644 --- a/calc.go +++ b/calc.go @@ -815,7 +815,7 @@ func (f *File) calcCellValue(ctx *calcContext, sheet, cell string) (result formu return } -func (f *File) CalcFormulaValue(ctx *calcContext, sheet, formula string) (result string, err error) { +func (f *File) CalcFormulaValue(sheet, formula string) (result string, err error) { var ( token formulaArg ) @@ -824,7 +824,12 @@ func (f *File) CalcFormulaValue(ctx *calcContext, sheet, formula string) (result if tokens == nil { return } - if token, err = f.evalInfixExp(ctx, sheet, "", tokens); err != nil { + if token, err = f.evalInfixExp(&calcContext{ + entry: fmt.Sprintf("%s!%s", sheet, ""), + maxCalcIterations: getOptions().MaxCalcIterations, + iterations: make(map[string]uint), + iterationsCache: make(map[string]formulaArg), + }, sheet, "", tokens); err != nil { return } result = token.Value() diff --git a/calc_test.go b/calc_test.go index c740e6b..73357cb 100644 --- a/calc_test.go +++ b/calc_test.go @@ -5888,3 +5888,59 @@ func TestCalcCellResolver(t *testing.T) { assert.Equal(t, expected, result, formula) } } + +func TestFile_CalcFormulaValue(t *testing.T) { + cellData := [][]interface{}{ + {1, 4, nil, "Month", "Team", "Sales"}, + {2, 5, nil, "Jan", "North 1", 36693}, + {3, nil, nil, "Jan", "North 2", 22100}, + {0, nil, nil, "Jan", "South 1", 53321}, + {nil, nil, nil, "Jan", "South 2", 34440}, + {nil, nil, nil, "Feb", "North 1", 29889}, + {nil, nil, nil, "Feb", "North 2", 50090}, + {nil, nil, nil, "Feb", "South 1", 32080}, + {nil, nil, nil, "Feb", "South 2", 45500}, + } + type args struct { + sheet string + formula string + } + tests := []struct { + name string + f *File + args args + wantResult string + wantErr bool + }{ + { + name: "test CalcFormulaValue", + f: prepareCalcData(cellData), + args: args{ + sheet: "Sheet1", + formula: "A1+B1", + }, + wantResult: "5", + }, + { + name: "test Power CalcFormulaValue", + f: prepareCalcData(cellData), + args: args{ + sheet: "Sheet1", + formula: "A1^2+LN(B1)", + }, + wantResult: "2.386294361119891", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gotResult, err := tt.f.CalcFormulaValue(tt.args.sheet, tt.args.formula) + if (err != nil) != tt.wantErr { + t.Errorf("File.CalcFormulaValue() error = %v, wantErr %v", err, tt.wantErr) + return + } + if gotResult != tt.wantResult { + t.Errorf("File.CalcFormulaValue() = %v, want %v", gotResult, tt.wantResult) + } + }) + } +}