Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi everyone, there are database and C# datagrid with columns same as my excel file that i want to transfer excel data to database, what's best method?
Posted
Updated 9-Mar-12 18:17pm
v2

You need to use the Excel Interop[^] assemblies to read the data from the excel spreadsheet, and then ADO.Net to save to the database.
 
Share this answer
 
Try this

C#
private void Import_Click(object sender, EventArgs e)
        {
           string excelcon = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\test.xls; Extended Properties=""Excel 8.0;HDR=YES;""";
                SqlConnection sqlcon = new SqlConnection();
                sqlcon.ConnectionString = ConfigurationManager.AppSettings["con"];
                sqlcon.Open();
                OleDbConnection sSourceConnection = new OleDbConnection(excelcon);
                using (sSourceConnection)
                {
                    string sql = string.Format("Select [Name],[Age] FROM [{0}]", "Sheet1$");
                    OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
                    sSourceConnection.Open();
                    using (OleDbDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            string query = "insert into details values (@name,@age)";

                            SqlCommand cmd = new SqlCommand(query, sqlcon);
                            cmd.Parameters.AddWithValue("@name", dr[0].ToString());
                            cmd.Parameters.AddWithValue("@age", dr[1].ToString());
                            cmd.ExecuteNonQuery();

                        }
                        MessageBox.Show("Done");
                    }
                }
        }

Add connection string in app.config file
 
Share this answer
 
v3
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900