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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM