我正在使用OleDb从Excel文件中读取数据。读取数据的代码如下:
OleDbCommand oleDbCommand = new OleDbCommand(selectCommandText, oleDbConnection);
using (OleDbDataReader dr = oleDbCommand.ExecuteReader())
{
DataTable dt = new DataTable();
dt.Load(dr);
return dt;
}
问题是读取的数据有时随机显示为字符串(例如“ 16.02.1995” )或数字-时间戳( 41187 )像这样convert Excel Date Serial Number to Regular Date。
有什么办法解决这个问题?我想始终以一种格式读取数据,而不管它是数字还是字符串。
编辑:我发现打开Excel文件时,读取的日期为数字格式(日期序列号),而当我没有打开文件时,日期为字符串格式。有人知道为什么吗?
Edit2:日期单元格中使用的个性化格式
答案 0 :(得分:4)
要将日期数字或日期字符串转换为c#,您需要两种不同的方法。
一个转换字符串,另一个转换数字为日期格式。
因此,关于将字符串转换为日期,在c#中有TryParse
方法,而关于日期的数字对话在SO中已经有answer。
放在一起,我们可以做类似的事情:
public static DateTime? GetDateTime(object o)
{
DateTime? date;
try
{
date = FromStringToDate(o.ToString());
if (date == DateTime.MinValue)
{
date = FromExcelSerialDate((int)o);
}
}
catch (Exception e)
{
//log your exception
date = null;
}
return date;
}
private static DateTime FromExcelSerialDate(int serialDate)
{
if (serialDate > 59) serialDate -= 1; //Excel/Lotus 2/29/1900 bug
return new DateTime(1899, 12, 31).AddDays(serialDate);
}
private static DateTime FromStringToDate(string stringDate)
{
DateTime.TryParse(stringDate, out DateTime result);
return result;
}
要使用它,在主要的测试方法中,您可以执行以下操作:
List<object> excelData = new List<object>()
{
"16.02.1995",
41187,
13131.3242,
"",
null
};
foreach (object o in excelData)
{
var dateTime = GetDateTime(o);
if (dateTime != null)
{
Console.WriteLine(dateTime);
}
}
输出将是:
16-02-1995 00:00:00
05-10-2012 00:00:00
我也已经测试过了。
注意:这仅是示例,您可以改进方法,更改顺序,添加更多保护性线条以免中断,例如,如果Excel中的日期为空,空或错误格式以适合您的业务逻辑。 / p>