c# - 从 excel 读取日期时输入字符串的格式不正确
问题描述
我正在尝试上传 Excel 表格。现在我收到日期列的错误。根据此处的一些建议,我能够将其修复到这一点。这是 excel 上的日期格式 20/4/2020
但我无法从这一点上弄清楚。我不断得到。我能够从 excel 表中获取值并存储在字符串日期中
输入字符串的格式不正确。在 System.Number.ThrowOverflowOrFormatException(ParsingStatus 状态,TypeCode 类型) 在 System.Double.Parse(String s)
这是我下面的代码
//be on the first column [r,c]
int row = 2;
for (int i = 2; i <= noOfRow; i++) //start from the second row
{
if (!string.IsNullOrEmpty(workSheet.Cells[i, 3].Text))
{
string date = workSheet.Cells[i, 3].Value.ToString();
try
{
double d = double.Parse(date);//Error is coming from here
DateTime conv = DateTime.FromOADate(d);
}
catch (Exception ex)
{}
}
}
如果有人可以帮助我,我将不胜感激谢谢
解决方案
出现问题是因为变量中的值date = "11/5/2020"
不是double
值。这是一个DateTime
值。要解决您的问题,您应该使用下一个代码将date
变量中的值转换为DateTime
值:
DateTime d = DateTime.ParseExact(date, "d/M/yyyy", CultureInfo.InvariantCulture);
方法DateTime.ParseExact
允许您设置解析日期的格式。
上面的代码在你与我分享的那一天对我有用。但是现在我遇到了这个错误
{"String '6/3/2020 12:00:00 AM' was not recognized as a valid DateTime."}
,我尝试在 stackoverflow 上实现几乎所有内容。
如果您的excel文件中的日期字符串可以是不同的格式,那么您可以使用DateTime.ParseExact
支持指定几种解析格式的方法的重载。例如:
string[] formats = {"d/M/yyyy", "d/M/yyyy hh:mm:ss tt"};
DateTime d = DateTime.ParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
这是演示该方法重载的完整示例DateTime.ParseExact
。
推荐阅读
- cassandra - 如何从某个节点查询 Cassandra 并仅从该节点自己获取数据?
- variables - Activiti BPMN - 如何在已完成任务的变量/表达式中传递用户名?
- javascript - 选中复选框时PHP更改查询
- javascript - 如何通过带有geojson的谷歌地图的setStyle函数获得虚线
- c# - Can't return byte[ ] with security=Message
- qt - 如何做水平面包屑?行还是列表视图?
- swift - Limit Text to number of lines 3
- admob - AdMob interstellar ad dropped for 99%, but sessions numbers(usage) are the same?
- javascript - Firefox 阻止自行加载资源(“script-src”)
- debian - DRBD device fails timed out at Server boot time