zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    gym101350 c h m
    Gym
    poj 1511 Invitation Cards(最短路中等题)
    POJ 1062 昂贵的聘礼(最短路中等题)
    POJ 1125 Stockbroker Grapevine(最短路基础题)
    【Linux】buffer cache free 理解
    python 绘图 工具
    【Linux】时间跟时区的校正
    python conda、pip区别,python 下 faiss 安装
    celery-demo
  • 原文地址:https://www.cnblogs.com/2828sea/p/13161176.html
Copyright © 2011-2022 走看看