使用c#将Excel数据转换为datetime

时间:2012-11-22 06:27:36

标签: c# excel

我是C#的新手,我有一个C#程序和一个从另一个程序导出的excel文件。如何将其转换为DateTime?以下是代码,其中dtFromdtToDateTimePicker变量:

System.Data.DataTable dtExcel = new System.Data.DataTable();
dtExcel.TableName = "MyExcelData";
string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" +        this.textBox1.Text + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection con = new OleDbConnection(SourceConstr);
string query = "Select Customer, SUM(Wt) AS Weight from [Sheet0$] WHERE (CONVERT(datetime, [Date]) >= " + this.dtFrom.Value.Month + ") GROUP BY Customer order by Customer"; 
OleDbDataAdapter data = new OleDbDataAdapter(query, con);
data.Fill(dtExcel);

1 个答案:

答案 0 :(得分:0)

我认为这可能不是你唯一的问题,但要回答你的问题,如果你更换

string query = "Select Customer, SUM(Wt) AS Weight from [Sheet0$] WHERE (CONVERT(datetime, [Date]) >= " + this.dtFrom.Value.Month + ") GROUP BY Customer order by Customer"; 
OleDbDataAdapter data = new OleDbDataAdapter(query, con);

string query = "Select Customer, SUM(Wt) AS Weight from [Sheet0$] WHERE (CONVERT(datetime, [Date]) >= @Date) GROUP BY Customer order by Customer"; 
OleDbCommand command = new OleDbCommand(query);
command.Parameters.Add("@Date", OleDbType.DBTimeStamp).Value = this.dtFrom.Value;
OleDbDataAdapter data = new OleDbDataAdapter(command, con);

你可能会走上正轨。不是100%确切地确定您需要哪个OleDbType,但是您可以很容易地看到可用的选项。