date从Excel表单中返回不正确
我有一些Excel数据表。 其中我有一个date栏。 当我读取date列的Excel工作表时,它会返回一个不正确的date(date格式月/日/年)。
以下是Excel工作表中date值的示例
01/01/2014
以及从C#中读取的date值
1/1/2014
但它正确地parsingdate2015年5 05/24/2015
。
所以当我TryParseExact
它的有效date,它总是返回false。 有没有解决这个问题的好办法?
更新:
if (!DateTime.TryParseExact(row["ColoumnNo"].ToString(), "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) <br> { //code }
当你看你的Excel表,你会看到以下格式:MM / DD / YYYY。 你的date只是格式化程序在Excel中显示的格式。 在引擎盖下是一个datetypes。 当你在c#中以datetypes的forms读取date时,你的datetypes为M / d / yyyy。 所以你必须改变你的TryParse的面具为:“M / d / yyyy”。 你可以直接从excel表单读取date值,如果你改变你的文化,你会从你的Excel表格中读取其他的date格式。
正如其他人所暗示的,通过信任Excel来告诉你是否有date,你最好避免这个问题。 Range.Value
是object
types,如果Excel将内容识别为date,将返回DateTime
。 所以你的代码可以写成:
var value = row[".."].Value; if (value is DateTime) { var date = (DateTime)value; //code }