【发布时间】:2014-01-24 16:49:38
【问题描述】:
我已经查看了 SO 中类似问题的所有先前答案,但这些答案不起作用。我在 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;? -
是的.. 我刚试了一下,还是不行。过去3天我一直在发布同样的问题,但仍然没有人解决它..谈论挫败感!!!!!
标签: c# asp.net asp.net-mvc-4 openxml openxml-sdk