[英]Using NPOI, how do I return a cell value as it has been formatted by Excel?
Using NPOI , is there any buildin possibility to format a cell value (especially numeric and date values) as it has been formatted by Excel ? 使用NPOI ,是否有可能格式化单元格值(特别是数字和日期值),因为它已经由Excel格式化 ?
If not what would be the best way to implement it? 如果不是最好的实现方式是什么? I thought of a formatstring converter from Excel-formatstrings to C#-formatstrings?
我想到了从Excel格式字符串到C#格式字符串的格式字符串转换器?
The following example assumes the Excel-formatstring and the C#-formatstring are the same. 以下示例假定Excel-formatstring和C#-formatstring相同。 So it works for some basic formatstrings like: "#,##0.00"
所以它适用于一些基本的格式字符串,如:“#,## 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 [...]
Found the NPOI built in possibility. 发现NPOI内置的可能性。 However some formats like "Sunday, September 18, 1983" are evaluated like "EEEE, September 18, 1983" .
然而,诸如“1983年9月18日星期日”之类的某些格式被评估为“EEEE,1983年9月18日” 。
using NPOI.SS.UserModel;
DataFormatter dataFormatter = new DataFormatter(CultureInfo.CurrentCulture);
ICell cell = workbook.GetSheet("table1").GetRow(0).GetCell(0);
string value = dataFormatter.FormatCellValue(cell);
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 + ")");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.