繁体   English   中英

打开XML SDK读取Excel公式单元格

[英]open xml sdk read excel formula cell

我有在单元格C4中具有公式= SUM(C2:C3)的Excel文件。 我在单元格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

使用CellFormula (<f>)元素定义公式文本。 公式可以包含数学表达式,其中包括各种预定义函数。 CellValue (<v>)元素根据上次计算公式的时间存储缓存的公式值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM