Question

I have excel file that has formula =SUM(C2:C3) in cell C4. I have values 15 and 17 in cells C2 and C3 respectively. Programmatically, I want to be able to execute C4 formula and get back the value 32 (result of the formula).

Some one suggested that I should use OpenXml SDK. Because this code will be hosted and used by Windows Azure Website.

Here is my code so far and the cell does not execute formula in 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));

}
Was it helpful?

Solution

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

As per 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top