2016-07-06 5 views

Antwort

0

ich dies durch einige Blogs nach tun wird verwaltet. Vielleicht gibt es einen besseren Weg, aber im Moment löste der folgende Ansatz mein Problem mit der NPOI-Bibliothek.

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