Thursday, March 12, 2009

from Excel file to Sql table.

Hello again,

Here is the code to fill sql table from data in excel file:

protected void button_click(object sender, EventArgs e)
{
string sqlTblName = "nitinSongs";
string excelFileName = "WT_codes.xls";
string workBook = "[nitin$]";
string exlConStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("WT_codes.xls") + ";" + "Extended Properties=Excel 8.0;";
string sqlConStr = "Data Source=SERVER NAME;Database=DATABASE NAME;Persist Security Info=True;User ID=LOGINID;Password=PASSWORD";

SqlConnection sqlCon = new SqlConnection(sqlConStr);
SqlCommand sqlCom = new SqlCommand("DELETE FROM " + sqlTblName, sqlCon);
sqlCon.Open();
sqlCom.ExecuteNonQuery();
sqlCon.Close();

OleDbConnection oleCon = new OleDbConnection(exlConStr);
OleDbCommand oleCom = new OleDbCommand("select * from " + workBook, oleCon);
oleCon.Open();
OleDbDataReader dr = oleCom.ExecuteReader();
SqlBulkCopy bCopy = new SqlBulkCopy(sqlConStr);
bCopy.DestinationTableName = sqlTblName;
bCopy.WriteToServer(dr);
oleCon.Close();
}

No comments:

Post a Comment