简体   繁体   中英

converting excel data to datetime using c#

I am new to C# and I have a C# program and an excel file exported from another program. How can I convert it to DateTime? Here is the code, where dtFrom and dtTo are DateTimePicker variables:

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);

I think it's probably not your only problem, but to answer your question, if you replace

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);

with

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);

you'll probably be on the right track. Not 100% sure exactly which OleDbType you need, but you can see the available options easily enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM