我這里分兩種情況處理
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.總結:
- 如果Execl有公式,我們獲取公式的值,可以直接通過獲取其類型,然后取其值
- 如果Execl沒有公式,我自定義公式,想實現自定義公式,我們需要三個步驟:
- 定義公式: string ss = "SUM(B2:B7)";
- 給指定cell設置公式:cell.SetCellFormula(ss);
- 在Execl中創建公式:workbook.GetCreationHelper().CreateFormulaEvaluator().EvaluateFormulaCell(cell);
- 通過類型獲取其值:GetValueType(cell)