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

Moc*_*hoa 7 c# devexpress visual-studio npoi

我有一个Excel文件,我使用DevExpress编辑,我正在使用NPOI阅读.当我尝试将日期单元格的值作为字符串时,它不保留原始值.

例如:在DevExpress网格中,我设置了这个值:2016-08-12.我想在我的字符串中获得相同的值,但我得到了42689.

获取单元格值的代码如下:

    ICell cell = row.GetCell(i);
    cell.SetCellType(CellType.String);
    string fieldString = cell.StringCellValue;
    result = result + ";" + FieldValue; 
Run Code Online (Sandbox Code Playgroud)

如何获取原始格式化的日期值?

Bri*_*ers 12

在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,像这样使用它:

ICell cell = row.GetCell(i);
string fieldString = cell.GetFormattedCellValue();
result = result + ";" + FieldValue;
Run Code Online (Sandbox Code Playgroud)

可选:如果单元格中有任何公式,并且您希望评估这些公式,则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;
Run Code Online (Sandbox Code Playgroud)