gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:59:58 33 4
gpt4 key购买 nike

我在 Excel 单元格中有一个公式,它使用使用名称管理器定义的名称范围。如何使用 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 "";
}

关于C#:如何使用 NPOI 或任何其他库评估由名称范围组成的 excel 公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38224238/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com