invoke formula in excel via epplus

筅森魡賤 提交于 2019-12-13 11:59:12

问题


I have an excel sheet in ASP.NET MVC4 C# project and I am able to read from excel sheet successfully using EPPlus. Now, I want to be able to pass in 2 numbers into cell C:2 and C:3 and be able to invoke formula in C:4 which is =SUM(C2:C3).

So from C# I want to pass in 4 and 6 and invoke the formula and be able to get the result back from C:4 which is 40 (SUM of 10 and 30). How do I accomplish that in C#.

In the following code, I get back zero for d.Average

d.Average = Convert.ToDouble(currentWorksheet.Cells["C4"].Value);

Here is my following code in c# so far to traverse a row.

        using (var package = new ExcelPackage(existingFile))
        {
            ExcelWorkbook workBook = package.Workbook;
            var currentWorksheet = workBook.Worksheets.First();
            currentWorksheet.Workbook.CalcMode = ExcelCalcMode.Automatic;
            currentWorksheet.Cells["C4"].Formula = "=SUM(C2:C3)";
            currentWorksheet.Cells["C2"].Value = 10;
            currentWorksheet.Cells["C3"].Value = 30;
            package.Save();


        }

        using (var package = new ExcelPackage(existingFile))
        {
            ExcelWorkbook workBook = package.Workbook;
            var currentWorksheet = workBook.Worksheets.First();
            d.Average = Convert.ToDouble(currentWorksheet.Cells["C4"].Value);
        }

回答1:


Skip the = in the formula string.

Replace currentWorksheet.Cells["C4"].Formula = "=SUM(C2:C3)";

with

currentWorksheet.Cells["C4"].Formula = "SUM(C2:C3)";




回答2:


As of EpPlus 4.0.1.1, there is an extension method Calculate(this ExcelRangeBase range). Invoke it before accessing Value property:

currentWorksheet.Cells["C4"].Calculate();

and currentWorksheet.Cells["C4"].Value will return the expected value of 40 after that.




回答3:


I was reviewing my previous answer and found out that the calculation engine of EPPLUS is still in development.

See this discussion on CodePlex. (dating from 2011)

A cite from the roadmap page:

Version 3.2

Formula parser, calc engine

Replacing the Package API with DotNetZip

New cellstore to imporve insert, delete performance and memory consumtion

Last edited Feb 14, 2013



来源:https://stackoverflow.com/questions/21189163/invoke-formula-in-excel-via-epplus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!