After updating a cell and save excel, formulas based on this cell doesnt recalculate

六月ゝ 毕业季﹏ 提交于 2019-12-10 16:24:10

问题


Hi,

Im using XML SDK to update some cells on an excel file.

This is the code that im using to update a cell for a given text (and its working fine).

WorksheetPart worksheetPart = GetWorksheetPartByName(spreadSheet, sheetname);

spreadSheet.WorkbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;

spreadSheet.WorkbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;

    if (worksheetPart != null)
    {
       Cell cell = GetCell(worksheetPart.Worksheet, columnName, rowIndex);
       cell.CellValue = new CellValue(text);
       cell.DataType = new EnumValue<CellValues>(CellValues.Number);
       // Save the worksheet.
       worksheetPart.Worksheet.Save();
    }

For other hand now i want to open again the excel file and get the updated values from other cells whose formulas are based on the previous cell but even with the following lines im not able to do it:

spreadSheet.WorkbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;

spreadSheet.WorkbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;

Do you know why im not getting the updated values?

Thanks

Regards.

Jose


回答1:


Execute the below function for every cell that contains a formula.

public void ReCalcuateFormula(Cell cell)
{
    if (cell.CellFormula != null)
        cell.CellFormula.CalculateCell = new BooleanValue(true);
}



回答2:


See Vincent's answer here: OpenXML - refresh Excel sheet after cell update

Open XML SDK doesn't refresh the calculation results of formulas. Only Excel does that (or other spreadsheet software). So even if you set ForceFullCalculation and FullCalculationOnLoad to true, you only tell Excel to force a full calculation and do it when loading the spreadsheet file.

This is why you always get the "old" value. Because there's no "new" value to speak of.

To test this, you can set the CellValue (of the Cell class) to say "3.14159" with the CellFormula intact. Excel will calculate and display the correct value of your formula, even though you specifically set the cell value as "3.14159". [Unless of course, your formula evaluates to PI...]

To solve this, you either have a calculation engine to read in the formula and calculate the result for you. Or save the spreadsheet and run Excel (in Interop mode) to calculate all the formulas, but that kind of defeat the purpose of using Open XML SDK in the first place.



来源:https://stackoverflow.com/questions/11727898/after-updating-a-cell-and-save-excel-formulas-based-on-this-cell-doesnt-recalcu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!