1

当我从 excel 导入数据集时,我的日期格式发生了变化

我的代码如下:

DataSet ds = new DataSet();
string myConnStr = "";

if (ds != null)
{
    myConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + "; " + "Extended Properties=\"Excel 12.0;HDR=YES\"";
}
else
{
    myConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
}

OleDbConnection myConn = new OleDbConnection(myConnStr);
try
{
    OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$] ",myConn);
    OleDbDataAdapter adapter = new OleDbDataAdapter();
    adapter.SelectCommand = cmd;
    myConn.Open();
    adapter.Fill(ds);
 }
catch
{ }
finally
{
    myConn.Close();
}

如果我从 excel 中逐行读取,那么我可以使用DateTime.FromOADate 在这里我不能这样做。请帮忙

4

1 回答 1

1

一种解决方案是将您的 Integer 转换回 Datetime

示例代码就像

public DateTime ExcelSerialDateToDT(int nSerialDate)
{

int l = nSerialDate + 68569 + 2415019;
int n = ((4 * l) / 146097);
l = l - ((146097 * n + 3) / 4);
int i = ((4000 * (l + 1)) / 1461001);
l = l - ((1461 * i) / 4) + 31;
int j = ((80 * l) / 2447);
int nDay = l - ((2447 * j) / 80);
l = (j / 11);
int nMonth = j + 2 - (12 * l);
int nYear = 100 * (n - 49) + i + l;

return DateTime.Parse(nMonth + "/" + nDay + "/" + nYear);

 }

为我工作......

于 2013-04-11T15:59:34.640 回答