Monday, 15 August 2011

How to import data from excel into Sql server

In this tutorial you will learn how to import data from excel into database (Sql server).
//Here is aspx code




//Here is aspx.cs code
string path = uploadExel.FileName;//Here you will get file from asp uploader
uploadExel.SaveAs(Server.MapPath("~/Folder Name/" + path));//
//Here you nee to establish a connection with excel file
//if your code is running locally then use only file name instead of 'server.mapPaht' 

OleDbConnection conn = newOleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath(path)+";Extended Properties=Excel 8.0");                
oconn.Open();                        

//Here sheet1 is the sheet name in your excel file from which you will get data
OleDbCommand cmd = newOleDbCommand("select * from [Sheet1$]", conn);
OleDbDataReader dr = cmd.ExecuteReader();
string id = "";
string service = "";
string name= "";
while (dr.Read())
{
id = valid(dr, 0);//valid is function created for checking empty values.
service = valid(dr, 1);
name = valid(dr, 2);
//Now save your data into sql server.
_obj.saveData(id, service, name);

}

oconn.Close();            

//Valid Function to check empty values
protectedstring valid(OleDbDataReader reader, int val)//if any columns are      
{       

//if found null then they are replaced by zero
object val = reader[val];
if (val != DBNull.Value)
return val.ToString();
else
returnConvert.ToString(0);

}

No comments:

Post a Comment