C# NPOI计算Execl里面的公式

我这里分两种情况处理

1.Execl中表格中存在公式,我们通过公式获取数据


我们通过Npoi,获取列的属性:

private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return null;
                case CellType.Boolean:
                    return cell.BooleanCellValue;
                case CellType.Numeric:
                    return cell.NumericCellValue;
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Error:
                    return cell.ErrorCellValue;
                case CellType.Formula:
                    return cell.NumericCellValue;
                default:
                    return "=" + cell.CellFormula;
            }
        }

我们在获取Execl的文件对象的之后,通过Npoi组件获取任意Sheet下面的Row和Cell,我们在获取Cell,我们可以通关上面的这个方法,判断其类型,然后获取其结果!

2.Execl中表格中不存在公式,我们自定义的公式添加到表格,那该如何计算?

比如如下,一开始我们不去设置公式:

     ICell cell = sheet.GetRow(i).GetCell(j);
     //自定义公式
     string Formula= "SUM(B2:B7)";
     //给列设置公式
     cell.SetCellFormula(Formula);
     //这个很重要,在Execl创建公式
     workbook.GetCreationHelper().CreateFormulaEvaluator().EvaluateFormulaCell(cell);
     //获取其值
     GetValueType(sheet.GetRow(i).GetCell(j));

3.总结:

  1. 如果Execl有公式,我们获取公式的值,可以直接通过获取其类型,然后取其值
  2. 如果Execl没有公式,我自定义公式,想实现自定义公式,我们需要三个步骤:
    1. 定义公式: string ss = "SUM(B2:B7)";
    2. 给指定cell设置公式:cell.SetCellFormula(ss);
    3. 在Execl中创建公式:workbook.GetCreationHelper().CreateFormulaEvaluator().EvaluateFormulaCell(cell);
    4. 通过类型获取其值:GetValueType(cell)
posted @ 2020-06-19 09:19  喜欢吃鱼的青年  阅读(4386)  评论(0编辑  收藏  举报