IpadNF
IpadNF

Reputation: 1

Reading date columns from Excel

I am trying to read date cell from Excel file:

private string GetDateValueFromRowOrNull(ISheet worksheet, int row, int column, StringBuilder exceptionMessage, CellType? cellType = null)
{
    var cell = worksheet.GetRow(row).GetCell(column);
    if (cell == null)
    {
        return string.Empty;
    }

    if (cellType != null)
    {
        cell.SetCellType(cellType.Value);
    }

    var cellValue = worksheet.GetRow(row).GetCell(column).DateCellValue;

    if (cellValue != null)
    {
        return cellValue;
    }

    return String.Empty;
}

But I am getting an error while trying to return the cellValue:

Can not implicitly convert type System.DateTime to string

if (cellValue != null)
{
    return cellValue;
}

I am using NPOI for the Excel functions.

Upvotes: 0

Views: 738

Answers (3)

IpadNF
IpadNF

Reputation: 1

I have sorted it. @Fredy’s comment was right.

var cellValue = worksheet.GetRow(row).GetCell(column).DateCellValue;

    if (cellValue != null)
    {
        return cellValue.ToString();
    }

Upvotes: 0

Crowcoder
Crowcoder

Reputation: 11514

If you require a DateTime to be returned from your method you need to change the method signature to return DateTime instead of string. Given the possibility of a null value, I also suggest you actually return a nullable date and make sure callers of this method handle nulls the same way you were expecting them to handle empty string:

private DateTime? GetDateValueFromRowOrNull(ISheet worksheet, int row, int column, StringBuilder exceptionMessage, CellType? cellType = null)
{
    var cell = worksheet.GetRow(row).GetCell(column);
    if (cell == null)
    {
        return null;
    }

    if (cellType != null)
    {
        cell.SetCellType(cellType.Value);
    }

    var cellValue = worksheet.GetRow(row).GetCell(column).DateCellValue;

    if (cellValue != null)
    {
        return cellValue;
    }

    return null;
}

Upvotes: 0

Tafsir Ahamed
Tafsir Ahamed

Reputation: 956

You can read the datetime value as string from excel then convert it to a DateTime object.

Sample converter code:

public static DateTime GetDateTime(string day, string month, string year)
{
    try
    {
        return Convert.ToDateTime(string.Format("{0} {1}, {2}", (object)day, (object)month, (object)year));
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Upvotes: 4

Related Questions