Import Data from Excel in C#
Use the code below to import data from excel
OleDbConnection cnn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""E:\Book1.xlsx""; Extended Properties=Excel 12.0;");
OleDbCommand oconn = new OleDbCommand("select * from [sheet1$]", cnn);
cnn.Open();
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
try
{
SqlConnection cnn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["connString"].ToString());
SqlCommand cmd = new SqlCommand();
cnn1.Open();
for (int i = 0; i < dt.Rows.Count; i++)
{
cmd = new SqlCommand("Insert into Student ([Name],[FatherName])" +
"Values ('" + dt.Rows[i]["name"] + "','" + dt.Rows[i]["fname"] + "'")", cnn1);
cmd.ExecuteNonQuery();
// Modify your command as per your need.
}
cnn.Close();
}
catch (Exception ex)
{
}
0 Comment(s)