使用 EPPlus 库将公式替换为 Excel 中的值

Using EPPlus library to replace formulas by their values in Excel

我读到 Microsoft.Office.Interop.Excel 是用 Excel 中的值替换公式的最简单方法,但它需要安装 Office。由于我需要在 Windows 服务器(2008 或 2012)上进行部署,因此我正在寻找最好的 and/or 最简单的方法来使用 EPPlus

添加公式有据可查,例如

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

但我找不到任何将整个工作表的公式替换为等效值的示例。基本上是复制,然后是 Excel.

中的选择性粘贴选项

我认为 Epplus 中没有任何内置功能可以为您集体完成这项工作。但是您可以利用 WorksheetCells 集合仅包含具有内容的单元格的条目这一事实。所以这样的事情应该不会太痛苦performance-wise:

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

currentWorksheet.Cells["D2"].Value = 15;
currentWorksheet.Cells["D3"].Value = 25;
currentWorksheet.Cells["D4"].Formula = "SUM(D2:D3)";

//Calculate the formulas and the overwrite them with their values
currentWorksheet.Cells.Calculate();
foreach (var cell in currentWorksheet.Cells.Where(cell => cell.Formula != null))
    cell.Value = cell.Value;

我知道这是 3 年前的事了,但如果你现在正在读这篇文章,EPPlus 现在有功能 .ClearFormulas() 可以做到这一点,只需做

yourSheetHere.Calculate();   
yourSheetHere.ClearFormulas();

一切顺利。