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";
}
}
}
I am trying to import data from excel to SQL Server, it works fine till I am not passing date but now I want to pass the date to SQL Server it provides error as datatype not matches.
Anyone has logic or please suggest me what can I do to ..
4条答案
按热度按时间c9x0cxw01#
Might be the column in the Excel Sheet is not in a valid date format.
Change it to Date Type.
Then you try to Import...
3mpgtkmj2#
The
DateTime
you read from excel is OLE Automation date and you have to convert it to c#DateTime
before you insert in to sql server. It would be double value for date when you read from excel. You can use DateTime.FromOADate to convert the double value toDateTime
. You can use SqlBulkCopy.WriteToServer(DataTable table) , this method allows you to pass the datatable. You can change the date in datatable in require format and use it to save bulk data in sql server. You can import excel data to datatable, this article will help you.gdx19jrr3#
It works i tried to convert it in datatble den change datatype and then insert
in this i had created a function txtdob which converts my string to datetime format Thank you i tried it workes if u feel so mark it as answer
cngwdvgl4#