简体   繁体   中英

C#:How to evaluate a excel formula consisting of Name ranges using NPOI or any other library

I have a formula in the Excel cell which is using a Name range defined using name manager. How can i evaluate the formula using NPOI or any other library in c#?

Example: I have the formula as below

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

where _NameRange1_ is defined as "Sheet1!$A$9:$DS$9"

I managed to do this after going through few blogs. may be there is a better way but for now the below approach resolved my issue using NPOI library.

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 "";
                    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM