Excel刷新公式失效处理
最近做Excel文件的处理,发现一个奇怪的现象,用office打开,引用公式的数据显示正常,用wps打开,却没有数据,需
最近做Excel文件的处理,发现一个奇怪的现象,用office打开,引用公式的数据显示正常,用wps打开,却没有数据,需要选中单元格,按Enter键后,数据才刷新。
找了NPOI,尝试刷新公式后保存,结果还是一样。
workbook.SetForceFormulaRecalculation(true);再用Spire.Xls,结果也还是一样
sheet.CalculateAllValue();发现这些第三方组件无效后,就去翻找底层的Openxml文档。经过一番折腾,终于实现了刷新公式引用。
/// /// 刷新公式引用 /// /// public static void RefreshFormulasAndSaveExcelFile(string filePath) { try { using (SpreadsheetDocument document = SpreadsheetDocument.Open(filePath, true)) { WorkbookPart workbookPart = document.WorkbookPart; if (workbookPart != null) { // 尝试获取或创建CalculationProperties CalculationProperties calcProps = workbookPart.Workbook.CalculationProperties; if (calcProps == null) { calcProps = new CalculationProperties(); workbookPart.Workbook.CalculationProperties = calcProps; } calcProps.CalculationMode = new EnumValue(CalculateModeValues.Auto); calcProps.CalculationOnSave = true; calcProps.ForceFullCalculation = true; calcProps.FullCalculationOnLoad = true; calcProps.ConcurrentCalculation = true; CalculationChainPart calcChainPart = workbookPart.CalculationChainPart; // 刷新公式引用 if (calcChainPart != null) { calcChainPart.CalculationChain.Reload(); // 重新加载计算链 } document.Save(); document.Dispose(); } } } catch (Exception ex) { Console.WriteLine("刷新公式引用失败", ex); } }有时候不得不吐槽,office官方给出的openxml相关api,是和实际效果不一样的,文档说明是一套,实际效果是一套,中间可能夹带了私货。