Using NPOI, how do I return a cell value as it has been formatted by Excel?

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

Using NPOI, is there any buildin possibility to format a cell value (especially numeric and date values) as it has been formatted by Excel?

If not what would be the best way to implement it? I thought of a formatstring converter from Excel-formatstrings to C#-formatstrings?

The following example assumes the Excel-formatstring and the C#-formatstring are the same. So it works for some basic formatstrings like: "#,##0.00"

using NPOI.SS.UserModel;  ICell cell = workbook.GetSheet("table1").GetRow(0).GetCell(0); string value = null;  if(cell.CellType == CellType.String) {     value = cell.StringCellValue; } else if(cell.CellType == CellType.Numeric) {     string formatString = cell.CellStyle.GetDataFormatString();      if(DateUtil.IsCellDateFormatted(cell)) {         value = cell.DateCellValue.ToString(formatString);     } else {         value = cell.NumericCellValue.ToString(formatString);     } } else [...] 

回答1:

Found the NPOI built in possibility. However some formats like "Sunday, September 18, 1983" are evaluated like "EEEE, September 18, 1983".

using NPOI.SS.UserModel;  DataFormatter dataFormatter = new DataFormatter(CultureInfo.CurrentCulture); ICell cell = workbook.GetSheet("table1").GetRow(0).GetCell(0);  string value = dataFormatter.FormatCellValue(cell); 


回答2:

private static CellValue EvaluateFormulaCellValue(XSSFWorkbook wb, ICell cell)         {              WorkbookEvaluator _bookEvaluator = null;             _bookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.Create(wb), null, null);             // XSSFFormulaEvaluator.EvaluateAllFormulaCells(wb);             ValueEval eval = _bookEvaluator.Evaluate(new XSSFEvaluationCell((XSSFCell)cell));             if (eval is NumberEval)             {                 NumberEval ne = (NumberEval)eval;                 return new NPOI.SS.UserModel.CellValue(ne.NumberValue);             }             if (eval is BoolEval)             {                 BoolEval be = (BoolEval)eval;                 return NPOI.SS.UserModel.CellValue.ValueOf(be.BooleanValue);             }             if (eval is StringEval)             {                 StringEval ne = (StringEval)eval;                 return new NPOI.SS.UserModel.CellValue(ne.StringValue);             }             if (eval is ErrorEval)             {                 return NPOI.SS.UserModel.CellValue.GetError(((ErrorEval)eval).ErrorCode);             }             throw new InvalidOperationException("Unexpected eval class (" + eval.GetType().Name + ")");         } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!