gpt4 book ai didi

c# - 如何获取包含日期的单元格的值并使用 NPOI 保留原始格式

转载 作者:太空狗 更新时间:2023-10-29 20:04:15 27 4
gpt4 key购买 nike

我有一个使用 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;

关于c# - 如何获取包含日期的单元格的值并使用 NPOI 保留原始格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40426827/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com