Open XML SDK无法读取/计算Excel公式单元格。

3
我有一个Excel文件,其中单元格C4中的公式为=SUM(C2:C3)。我在单元格C2和C3中分别有数值15和17。从程序上讲,我希望能够执行C4公式并获得值32(即公式的结果)。

有人建议我使用OpenXml SDK。因为这个代码将被Windows Azure Website托管和使用。

这是我的代码目前的情况,但单元格不会执行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));

}
1个回答

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

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

1
我自己找到解决办法了,只需要添加以下这行代码 Convert.ToDouble(cell.CellValue.InnerText); 但是不管怎样还是要感谢你对我的回应。谢谢 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接