C#:How to evaluate a excel formula consisting of Name ranges using NPOI or any other library -
i have formula in excel cell using name range defined using name manager. how can evaluate formula using npoi or other library in c#?
example: have formula below
=if(isblank(\_namerange1\_),"0",2)
where _namerange1_
defined "sheet1!$a$9:$ds$9"
i managed after going through few blogs. may there better way below approach resolved issue using npoi library.
string sheetname="sheetname"; // sheetname 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 defined names string formula=sheet.getrow(row).getcell(col).cellformula; //extract defined names formula var regexcollection=regex.matches(formula,"_\\w+"); foreach (match item in regex_regexcollection) { string namerange=hssfwb.getname(item.value).referstoformula //replace defined names in formula with actual name ranges formula = formula.replace(item.value, namerange); } //set new formula cell 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 ""; }
Comments
Post a Comment