Setting *both* Value & Formula in EPPlus

十年热恋 提交于 2021-02-08 05:42:09

问题


Is there any way to set both the Value & Formula properties of a cell so that they persist into the written XLSX file?

Since EPPlus does not calculate the formulas (it relies on excel to do so), I am pre-calculating the result for the user. This is so that if they do not open the file, but then re-upload it, the 'value' is not null. The formulas are really simple.

Note: sheet.SetValue() and .Value both reset the Formula property of the ExcelCell class, so .Value must be called first. See the source code for ExcelCell.SetRichText() to see it happening.

Here is almost the exact code from the test case:

var package = new ExcelPackage(); // and setup code
var sheet = package.Workbook.Worksheets.First(); 
sheet.Cells["A2"].Value = 10; 
sheet.Cells["A2"].Formula = "=A1 * 3";
// Cell is OK now.  shows both ".Value" and ".Formula"

using (var s = new MemoryStream()) { 
    package.Save(s);
    var newPackage = new ExcelPackage(s);
    var newSheet = newPackage.Workbook.Worksheets.First();
    var cell = newSheet.Cells["A2"];
    // cell.Value == null
    // cell.Formula = "=A1 * 3"
}

回答1:


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

cell.Calculate();

and after that the cell.Value will return the expected result.

UPDATE

From the official documentation:

EPPlus supports formula calculation from version 4. This means that you can let EPPlus calculate the results of the formulas in a workbook.

This is done by calling the Calculate() method, which is available on Workbook, Worksheet and Range level. When Calculate() is called EPPlus will evaluate the result of the formula and store the result as the Value of the cell - just like Excel do.

Example

using(var package = new ExcelPackage(new FileInfo(@"c:\temp\tmp.xlsx")))
{
   // calculate all formulas in the workbook
   package.Workbook.Calculate();
   // calculate one worksheet
   package.Workbook.Worksheets["my sheet"].Calculate();
  // calculate a range
  package.Workbook.Worksheets["my sheet"].Cells["A1"].Calculate();
}

Known issues

The following features of Excel are currently not supported by EPPlus when it comes to Formula caluclation: Array Formulas, the Intersect operator, references to external workbooks.



来源:https://stackoverflow.com/questions/20946947/setting-both-value-formula-in-epplus

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