我在Excel单元格中有一个公式,它使用名称管理器定义的名称范围。如何使用NPOI或c#中的任何其他库评估公式?
示例:我的公式如下
=IF(ISBLANK(\_NameRange1\_),"0",2)
其中_NameRange1_
定义为"Sheet1!$A$9:$DS$9"
答案 0 :(得分:0)
经过一些博客后,我设法做到了这一点。可能有更好的方法,但目前以下方法使用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 "";
}