I am trying to read date cell from excel file, Here's the code
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;
}
Can someone help me out?, By the way it's an apnetzero mvc Solution and i am using npoi for the excel functions
CodePudding user response:
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;
}
}
CodePudding user response:
Sorry i have sorted it put apparently @Fredy was right
var cellValue = worksheet.GetRow(row).GetCell(column).DateCellValue;
if (cellValue != null)
{
return cellValue.ToString();
}
CodePudding user response:
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;
}