string server = "server_adress";
string db = "db_name";
string user = "user_name";
string pass = "password";
string tableName="table_name";
string filename="C:\Wins.xlsx";
string serverConnectionString="Server="+server+";Database="+db+";Uid="+user+";Pwd="+pass+";";
//step 1
// Load Excel data into DataTable
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=" + filename + ";Extended Properties='Excel 12.0;HDR=YES;'";
string strSQL = "SELECT * FROM [Sheet1$]";
OleDbConnection excelConnection = new OleDbConnection(connectionString);
excelConnection.Open(); // This code will open excel file.
OleDbCommand dbCommand = new OleDbCommand(strSQL, excelConnection);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(dbCommand);
// create data table
DataTable dTable = new DataTable();
//fill table with echel data
dataAdapter.Fill(dTable);
//step 2
//connect to server
using (SqlConnection destinationConnection =
new SqlConnection(serverConnectionString))
{
destinationConnection.Open();
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(destinationConnection))
{
//Destination Table must match columns in Excel sheet
bulkCopy.DestinationTableName = tableName;
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(dTable);
}
catch (Exception ex)
{
Label1.Text=ex.Message;
}
destinationConnection.Close();
}
}
// dispose used objects
dTable.Dispose();
dataAdapter.Dispose();
dbCommand.Dispose();
excelConnection.Close();
excelConnection.Dispose();
}
}