C# 打开xml sdk读取excel公式单元格

C# 打开xml sdk读取excel公式单元格,c#,excel,asp.net-mvc-4,openxml-sdk,C#,Excel,Asp.net Mvc 4,Openxml Sdk,我有一个excel文件,在单元格C4中有公式=SUM(C2:C3)。我在单元格C2和C3中分别有值15和17。通过编程,我希望能够执行C4公式并返回值32(公式的结果) 有人建议我应该使用OpenXMLSDK。因为此代码将由Windows Azure网站托管和使用 这是我到目前为止的代码,单元格不执行C4中的公式 string filename = Server.MapPath("/") + "ExcelData.xlsx"; using (SpreadsheetDocument docume

我有一个excel文件,在单元格C4中有公式=SUM(C2:C3)。我在单元格C2和C3中分别有值15和17。通过编程,我希望能够执行C4公式并返回值32(公式的结果)

有人建议我应该使用OpenXMLSDK。因为此代码将由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));

}
string filename=Server.MapPath(“/”+“ExcelData.xlsx”;
使用(电子表格文档=电子表格文档.Open(文件名,true))
{
document.WorkbookPart.Workbook.CalculationProperties.forcellCalculation=true;
document.WorkbookPart.Workbook.CalculationProperties.fullcalculationnload=true;
工作表=document.WorkbookPart.Workbook.subjections().SingleOrDefault(s=>s.Name==“myRange1”);
如果(工作表==null)
{
抛出新的ArgumentException(
Format(“在电子表格{1}”、“myRange1”、文件名、“sheetName”中找不到名为{0}的工作表”);
}
工作表部件工作表部件=(工作表部件)document.WorkbookPart.GetPartById(sheet.Id);
int rowIndex=int.Parse(“C4”。子字符串(1));
Row Row=工作表部分。工作表。GetFirstChild()。
Elements().FirstOrDefault(r=>r.RowIndex==RowIndex);
Cell Cell=row.Elements().FirstOrDefault(c=>C4.Equals(c.CellReference.Value));
}
根据:

使用CellFormula()元素定义公式文本。公式 可以包含数学表达式,其中包括广泛的 预定义函数。CellValue()元素存储缓存的 公式值基于上次计算公式的时间

根据:

使用CellFormula()元素定义公式文本。公式 可以包含数学表达式,其中包括广泛的 预定义函数。CellValue()元素存储缓存的 公式值基于上次计算公式的时间


我通过添加以下行Convert.ToDouble(cell.CellValue.InnerText)自己解决了这个问题;但我会相信你对我的回应。ThanksI通过添加以下行Convert.ToDouble(cell.CellValue.InnerText)自己解决了这个问题;但我会相信你对我的回应。谢谢
document.WorkbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;
document.WorkbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;