C#:如何评估使用NPOI或任何其他库的名称范围组成的Excel公式

我在Excel单元格中使用名称pipe理器定义的名称范围中有一个公式。 我如何评估使用NPOI或任何其他库在C#中的公式?

例如:我有下面的公式

=IF(ISBLANK(\_NameRange1\_),"0",2) 

其中_NameRange1_被定义为"Sheet1!$A$9:$DS$9"

通过几个博客,我设法做到这一点。 可能有更好的办法,但现在下面的方法解决了我的问题,使用NPOI库。

 String sheetName="SheetName"; // sheetname from the workbook int Row=2;//Some desired Row int Col=5 //Some desired Col XSSFWorkbook hssfwb = new XSSFWorkbook(new file("FilePath"); ISheet sheet = hssfwb.GetSheet(sheetName); XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(hssfwb); //Get Cell formula with defined names String formula=sheet.GetRow(Row).GetCell(Col).CellFormula; //Extract the Defined Names from the Formula var regexCollection=Regex.Matches(formula,"_\\w+"); foreach (Match item in regex_regexCollection) { String nameRange=hssfwb.GetName(item.Value).RefersToFormula //Replace all defined names in the formula with with actual name ranges formula = formula.Replace(item.Value, nameRange); } //set the new formula into the cell back again after name replacement sheet.GetRow(Row).GetCell(Col).CellFormula = formula; CellValue currentCell=evaluator.Evaluate(sheet.GetRow(Row).GetCell(Col)); string dataformat = sheet.GetRow(CellRow).GetCell(CellCol).CellStyle.GetDataFormatString(); switch (currentCell.CellType) { case CellType.Unknown: return "Unknown"; case CellType.Numeric: return currentCell.NumberValue.ToString(dataformat); case CellType.String: return currentCell.StringValue; case CellType.Formula: return currentCell.StringValue; case CellType.Blank: return ""; case CellType.Boolean: return currentCell.BooleanValue.ToString(); case CellType.Error: return "Error"; default: return ""; }