从 Excel 中读取日期列
我正在尝试从 Excel 文件读取日期单元格:
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;
}
但在尝试返回 cellValue
时遇到错误:
无法将 System.DateTime 类型隐式转换为字符串
if (cellValue != null)
{
return cellValue;
}
我正在将 NPOI 用于 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以从 Excel 中以字符串形式读取日期时间值,然后将其转换为 DateTime 对象。
示例转换器代码:
You can read the datetime value as string from excel then convert it to a DateTime object.
Sample converter code:
如果您需要从方法返回
DateTime
,则需要更改方法签名以返回DateTime
而不是string
。考虑到空值的可能性,我还建议您实际上返回一个可为空的日期,并确保此方法的调用者以与您期望它们处理空字符串相同的方式处理空值:If you require a
DateTime
to be returned from your method you need to change the method signature to returnDateTime
instead ofstring
. 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:我已经整理好了。 @Fredy 的评论是正确的。
I have sorted it. @Fredy’s comment was right.