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)
  • 相关阅读:
    CC++ 文件操作
    loadrunner之Paramater在负载测试中的数据生成规则
    loadrunner关联及web_reg_save_param方法浅析
    mysql union 与 union all 语法及用法
    sql 语句中as的用法和作用
    数据库主从复制和读写分离
    《剑指offer》算法题第十二天
    《剑指offer》算法题第十一天
    《剑指offer》算法题第十天
    《剑指offer》算法题第九天
  • 原文地址:https://www.cnblogs.com/2828sea/p/13161176.html
Copyright © 2011-2022 走看看