我的 Excel 文件在单元格 C4 中包含公式 =SUM(C2:C3)。我在单元格 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 :
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.
关于c# - 打开 xml sdk 不读取/计算 excel 公式单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21249980/