2014-01-21 50 views
2

我有excel文件,在单元格C4中有公式= SUM(C2:C3)。在单元格C2和C3中分别有值15和17。以编程方式,我希望能够执行C4公式并获取值32(公式的结果)。打开xml sdk读取Excel公式单元格

有人建议我应该使用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)); 

} 

回答

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

作为每MSDN

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

+1

我想通过加入下面一行ConvertdToToMouse(cell.CellValue.InnerText);但我会以任何方式给你信任来回应我。谢谢 –