[英]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.