我已經查看了所有以前對SO中類似問題的回答,但這些回答不起作用。我在excel中傳遞值,並希望公式單元格重新計算,但仍顯示舊值。打開xml sdk excel公式重新計算緩存問題
我已經使用了2種技術1)從單元格中刪除計算值2)以編程方式打開和關閉文件。他們兩個都不適合我。這是我的代碼。請幫忙。
string filename = Server.MapPath("/") + "ExcelData.xlsx";
// getting 2 numbers in excel sheet, saving, and closing it.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(filename, 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("C3".Substring(1));
Row row = worksheetPart.Worksheet.GetFirstChild<SheetData>().
Elements<Row>().FirstOrDefault(r => r.RowIndex == rowIndex);
Cell cell3 = row.Elements<Cell>().FirstOrDefault(c => "C3".Equals(c.CellReference.Value));
if (cell3 != null)
{
cell3.CellValue = new CellValue("13");
cell3.DataType = new DocumentFormat.OpenXml.EnumValue<CellValues>(CellValues.Number);
}
document.WorkbookPart.WorksheetParts
.SelectMany(part => part.Worksheet.Elements<SheetData>())
.SelectMany(data => data.Elements<Row>())
.SelectMany(row1 => row1.Elements<Cell>())
.Where(cell => cell.CellFormula != null && cell.CellValue != null)
.ToList()
.ForEach(cell => cell.CellValue.Remove());
worksheetPart.Worksheet.Save();
}
// getting the result out of excel.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(filename, false))
{
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));
calculatedvalue = Convert.ToDouble(cell.CellValue.InnerText);
}
你試過'ForceFullCalculation = true; '在第一次打開電子表格後的第一個代碼塊中? – rene
是的,我只是試了一下,它不起作用。我過去3天一直在發佈相同的問題,但仍然沒有人解決不了問題。談論挫折!!!!! –