我有一个使用 DevExpress 编辑的 Excel 文件,并且正在使用 NPOI 阅读。当我尝试以字符串形式获取日期单元格的值时,它不会保留原始值。
例如:
在 DevExpress 网格中我设置了这个值:2016-08-12
。我想在字符串中获得相同的值,但我得到了42689
.
我获取单元格值的代码如下:
ICell cell = row.GetCell(i);
cell.SetCellType(CellType.String);
string fieldString = cell.StringCellValue;
result = result + ";" + FieldValue;
如何获取原始格式化日期值?
在 Excel 中,日期存储为数字。如果你想获取格式化的日期,你需要检查单元格是否包含日期(有一个实用方法),然后获取单元格的日期值,获取数据格式,最后将日期转换为使用格式的字符串。你不应该强迫CellType
字符串,否则您将无法再知道该单元格最初包含日期。我建议创建一个像这样的扩展方法来根据其类型获取格式化的单元格值:
using NPOI.SS.UserModel;
public static class NpoiExtensions
{
public static string GetFormattedCellValue(this ICell cell, IFormulaEvaluator eval = null)
{
if (cell != null)
{
switch (cell.CellType)
{
case CellType.String:
return cell.StringCellValue;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(cell))
{
DateTime date = cell.DateCellValue;
ICellStyle style = cell.CellStyle;
// Excel uses lowercase m for month whereas .Net uses uppercase
string format = style.GetDataFormatString().Replace('m', 'M');
return date.ToString(format);
}
else
{
return cell.NumericCellValue.ToString();
}
case CellType.Boolean:
return cell.BooleanCellValue ? "TRUE" : "FALSE";
case CellType.Formula:
if (eval != null)
return GetFormattedCellValue(eval.EvaluateInCell(cell));
else
return cell.CellFormula;
case CellType.Error:
return FormulaError.ForInt(cell.ErrorCellValue).String;
}
}
// null or blank cell, or unknown cell type
return string.Empty;
}
}
然后,像这样使用它:
ICell cell = row.GetCell(i);
string fieldString = cell.GetFormattedCellValue();
result = result + ";" + FieldValue;
可选:如果您的单元格中有任何公式并且您希望对这些公式进行求值,则创建一个IFormulaEvaluator
根据您的工作簿类型并将评估器传递给GetFormattedCellValue()
方法。例如:
IFormulaEvaluator eval;
if (workbook is XSSFWorkbook)
eval = new XSSFFormulaEvaluator(workbook);
else
eval = new HSSFFormulaEvaluator(workbook);
...
ICell cell = row.GetCell(i);
string fieldString = cell.GetFormattedCellValue(eval);
result = result + ";" + FieldValue;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)