c# - 打开 xml sdk 不读取/计算 excel 公式单元格

标签 c# excel asp.net-mvc-4 openxml-sdk calculated-field

我的 Excel 文件在单元格 C4 中包含公式 =SUM(C2:C3)。我在单元格 C2 和 C3 中的值分别为 15 和 17。以编程方式,我希望能够执行 C4 公式并取回值 32(公式的结果)。

有人建议我应该使用 OpenXml SDK。因为此代码将由 Windows Azure 网站托管和使用。

到目前为止,这是我的代码,单元格不执行 C4 中的公式。

string filename = Server.MapPath("/") + "ExcelData.xlsx";

using (SpreadsheetDocument document = SpreadsheetDocument.Open(filename, true))
{
    document.WorkbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;
    document.WorkbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;

    Sheet sheet = document.WorkbookPart.Workbook.Descendants<Sheet>().SingleOrDefault(s => s.Name == "myRange1");
    if (sheet == null)
    {
        throw new ArgumentException(
            String.Format("No sheet named {0} found in spreadsheet {1}", "myRange1", filename), "sheetName");
    }
    WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheet.Id);

    int rowIndex = int.Parse("C4".Substring(1));

    Row row = worksheetPart.Worksheet.GetFirstChild<SheetData>().
            Elements<Row>().FirstOrDefault(r => r.RowIndex == rowIndex);

    Cell cell = row.Elements<Cell>().FirstOrDefault(c => "C4".Equals(c.CellReference.Value));

}

最佳答案

document.WorkbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;
document.WorkbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;

根据 MSDN :

Use the CellFormula (<f>) element to define the formula text. Formulas can contain mathematical expressions that include a wide range of predefined functions. The CellValue (<v>) element, stores the cached formula value based on the last time the formula was calculated.

关于c# - 打开 xml sdk 不读取/计算 excel 公式单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21249980/

相关文章:

c# - 您可以在不需要集成测试的情况下自行测试 razor View 吗?

asp.net-membership - 为什么 Membership.GetUser() 尝试创建表应用程序?

javascript - addRemoveLinks 在我的 Dropzone 上不起作用

c# - 将十进制值保存到数字字段 SQL

c# - 如何使用 C# 返回序列化为 JSON

JavaScript 弹出窗口未触发?

Excel 基于颜色条件格式化数据条

php - 从一个读取并写入第二个excel文件 - PHP

c# - 有人可以描述一种比双线性插值更好的二维插值方法吗?

c# - 对于 Visual Studio 2008 中的 C#,我应该从哪个单元测试框架开始? (Windows 窗体应用程序)