Click here to Skip to main content
15,876,991 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?
Updated 9-Mar-12 18:17pm

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

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"];
                OleDbConnection sSourceConnection = new OleDbConnection(excelcon);
                using (sSourceConnection)
                    string sql = string.Format("Select [Name],[Age] FROM [{0}]", "Sheet1$");
                    OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
                    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());


Add connection string in app.config file
Share this answer
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