我正尝试使用OpenXML从Excel中删除所有公式,包括共享公式

我正尝试使用OpenXML(包含共享公式)从Excel中删除所有公式。 如果Excel不包含任何共享公式,它可以无缝地工作,但是当它包含任何共享公式时,那么Excel文件被损坏的消息

删除logging:从/xl/worksheets/sheet1.xml部分共享公式从/xl/calcChain.xml部分删除logging:公式(计算属性

我使用类似于下面的代码(我正在使用堆栈溢出现有的代码)

public static void ReplaceFormulasWithValue() { try { CalculationChainPart calculationChainPart = _spreadSheet.WorkbookPart.CalculationChainPart; CalculationChain calculationChain = calculationChainPart.CalculationChain; var calculationCells = calculationChain.Elements<CalculationCell>().ToList(); foreach (Row row in _worksheetPart.Worksheet.GetFirstChild<SheetData>().Elements<Row>()) { foreach (Cell cell in row.Elements<Cell>()) { if (cell.CellFormula != null && cell.CellValue != null) { string cellRef = cell.CellReference; CalculationCell calculationCell = calculationCells.Where(c => c.CellReference == cellRef).FirstOrDefault(); UpdateCell(cell, DataTypes.String, cell.CellValue.InnerText); cell.CellFormula.Remove(); if(calculationCell != null) { calculationCell.Remove(); calculationCells.Remove(calculationCell); } else { //Something is went wrong - log it } } if (calculationCells.Count == 0) _spreadSheet.WorkbookPart.DeletePart(calculationChainPart); } _worksheetPart.Worksheet.Save(); } } catch(Exception ex) { Console.WriteLine(ex); } }