Some times in any application we need to import data from the out source like excel sheet using DOTNET
and this create problem so here I present you the solution.
On asp control on button's click event you have to put this code to import data from Exce sheet.
protected void btninsertdata_Click(object sender, EventArgs e)
{
OleDbConnection ocon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("example.xls") + ";Extended Properties=Excel 8.0");
try
{
OleDbCommand ocmd = new OleDbCommand("select * from [Sheet1$]", ocon);
ocon.Open();
OleDbDataReader ObjOleDr = ocmd.ExecuteReader();
string fname = "";
string lname = "";
string mobnum = "";
string city = "";
string state = "";
string zip = "";
while (ObjOleDr.Read())
{
fname = ValidData(ObjOleDr, 0);
lname = ValidData(ObjOleDr, 1);
mobnum = ValidData(ObjOleDr, 2);
city = ValidData(ObjOleDr, 3);
state = ValidData(ObjOleDr, 4);
zip = ValidData(ObjOleDr, 5);
insertdataintosql(fname, lname, mobnum, city, state, zip);
}
ocon.Close();
}
catch (DataException ee)
{
lblmsg.Text = ee.Message;
lblmsg.ForeColor = System.Drawing.Color.Red;
}
finally
{
lblmsg.Text = "Data Inserted Sucessfully";
lblmsg.ForeColor = System.Drawing.Color.Green;
}
}
protected string ValidData(OleDbDataReader myreader, int stval)
{
object ObjVal = myreader[stval];
if (ObjVal != DBNull.Value)
return ObjVal.ToString();
else
return Convert.ToString(0);
}
public void insertdataintosql(string fname, string lname, string mobnum, string city, string state, string zip)
{
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Project\Online Examination\Reserch Data\ImportExcel2SQLServer\ImportExcel2SQLServer\ImportExcel2SQLServer\App_Data\exceltosql.mdf;Integrated Security=True;User Instance=True");
string Query = "insert into emp(fname,lname,mobnum,city,state,zip) values('"+fname+"','"+lname+"','"+mobnum+"','"+city+"','"+state+"','"+zip+"')";
SqlCommand cmd = new SqlCommand(Query,con);
cmd.CommandType = CommandType.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
So , This is the solution.
If you still having problem then Request is I will give you a project which show you same thing.
1492 views