从Excel导入数据到Sql Server 2008#2

string path = string.Concat(Server.MapPath("~/TempFiles/"), FileUpload1.FileName); //Save File as Temp then you can delete it if you want FileUpload1.SaveAs(path); string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path); // Create Connection to Excel Workbook using (OleDbConnection connection = new OleDbConnection(excelConnectionString)) { OleDbCommand command = new OleDbCommand ("Select * FROM [Sheet1$]", connection); connection.Open(); // Create DbDataReader to Data Worksheet using (DbDataReader dr = command.ExecuteReader()) { // SQL Server Connection String string sqlConnectionString = @conn; // Bulk Copy to SQL Server using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString)) { bulkCopy.DestinationTableName ="Table1"; bulkCopy.WriteToServer(dr); Label1.Text = "The Client data has been exported successfully from Excel to SQL"; } } } 

我想从Excel导入数据到SQL Server,它工作正常,直到我没有通过date,但现在我想通过date到SQL Server它提供了错误,因为数据types不匹配。

任何人有逻辑或请build议我该怎么做..

可能是Excel表中的列不是有效的date格式。

将其更改为datetypes。

 Select the Column in the Excel Sheet -> Right Click -> Format Cells -> Number Tab -> Select Date -> Choose your desired Type -> Ok 

然后你尝试导入…

您从Excel中读取的date时间是OLE自动化date,并且在插入到sql server之前必须将其转换为c# DateTime 。 从excel中读取date会是双重价值。 您可以使用DateTime.FromOADate将double值转换为DateTime 。 你可以使用SqlBulkCopy.WriteToServer(DataTable表) ,这个方法允许你传递数据表 。 您可以更改数据表中的要求格式的date,并使用它来保存在sql服务器的批量数据。 你可以导入Excel数据到数据表,这篇文章会帮助你。

 DateTime dt = DateTime.FromOADate(double.Parse(stringVariableContainingDateTime)); 

它的工作原理我试图把它转换成数据库改变数据types,然后插入

  string sqlConnectionString = @conn; command.CommandType = CommandType.Text; OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(command); DataTable dt = new DataTable(); DataSet objDataset1 = new DataSet(); objAdapter1.Fill(dt); for (int i = 0; i < dt.Rows.Count; i++) { if (dt.Rows[0][5].ToString() != "") { DateTime dt1 = cf.texttodb(dt.Rows[0][5].ToString()); dt.Rows[i][5] = dt1; }} using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString)) { bulkCopy.DestinationTableName = "Tablename"; bulkCopy.WriteToServer(dt); Label1.Text = "The Client data has been exported successfully from Excel to SQL"; } 

在这个我创build了一个函数txtdob将我的string转换为date时间格式谢谢你,我试过它的工作,如果你觉得所以标记为答案