SoFunction
Updated on 2025-04-05

How to import Excel data into SQL2008 database instance method


private void AddManyData_Click(object sender, RoutedEventArgs e)
       {
           OpenFileDialog openFileDialog = new OpenFileDialog();
= "Excel file|*.xls";

           if ((bool)())  
           {  
                FileInfo fileInfo = new FileInfo();  
                string filePath = ;  
                string connExcel = "Provider=.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0";

                using (OleDbConnection oleDbConn = new OleDbConnection(connExcel))
                {
                    ();

//Get excel table
                    DataTable dt = (, null);
//Get the table name of the Excel table
                    string tableName = [0][2].ToString().Trim();
//Remove spaces
                    tableName = "[" + ("'", "") + "]";

//Use SQL statements to get data from Excel files
string query = @"SELECT Student ID, name, public welfare labor, electronic process internship, operating system, computer composition, numerical analysis, network equipment and integration, dynamic website development experiment week, dynamic website development, equal score, ranking FROM ";+ tableName;
                     DataSet dataSet = new DataSet();

                     using (OleDbCommand oleDbcomm = ())
                     {
                         = query;
                         OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleDbcomm);
                         (dataSet);
                     }
                     string connStr = "Data Source=HESHUHUA-PC;Initial Catalog=RSMSystem;Integrated Security=True";
//Batch insert data using SqlBulkCopy
                    using (SqlBulkCopy sqlbc = new SqlBulkCopy(connStr))
                    {
                        = "T_StuScore";
// ("StuNum", "StuNum"), the first parameter corresponds to the column name in the database,
//The second parameter corresponds to the column name of the corresponding table in the database
("StuNum");
("Name", "StuName");
("Public welfare labor", "Activity");
("ElecAct");
("Operation System", "OPrationSystem");
("Computer Maded", "ComputerMaded");
("Numerical Analysis", "DataAnalyze");
("NetWork");
("Dynamic Website Development Experiment Week", "WebWeek");
("Dynamic Website Development", "WebMake");
("Equal Segment", "AvScore");
("Ranking", "StuPaiMing");
                        ([0]);
("Data import was successfully!");

                    }
                }  

           }  

       }