Solution 1: Use OleDB to obtain data from an Excel file and then use DataSet to transfer data to SQL Server. This method has the advantages of being flexible, you can perform operations on cells in an Excel table as needed.
- OpenFileDialog = new OpenFileDialog ();
- OpenFileDialog. Filter = "Excel files (*. xls) | *. xls ";
-
- If (openFileDialog. ShowDialog () = DialogResult. OK)
- {
- FileInfo fileInfo = new FileInfo (openFileDialog. FileName );
- String filePath = fileInfo. FullName;
- String connExcel = "Provider = Microsoft. Jet. OLEDB.4.0; Data Source =" + filePath + "; Extended Properties = Excel 8.0 ";
- Try
- {
- OleDbConnection oleDbConnection = new OleDbConnection (connExcel );
- OleDbConnection. Open ();
- // Obtain an excel table
- DataTable dataTable = oleDbConnection. GetOleDbSchemaTable (OleDbSchemaGuid. Tables, null );
-
- // Obtain the sheet name, where [0] [1]... [N]: The form Element arranged by name
- String tableName = dataTable. Rows [0] [2]. ToString (). Trim ();
- TableName = "[" + tableName. Replace ("", "") + "]";
-
- // Obtain data from an Excel file using SQL statements
- // String query = "SELECT classDate, classpdate, classTeacher, classTitle, classID FROM" + tableName;
- String query = "SELECT date, course class city, Lecturer, course name, duration FROM" + tableName;
- DataSet = new DataSet ();
-
- // OleDbCommand oleCommand = new OleDbCommand (query, oleDbConnection );
- // OleDbDataAdapter oleAdapter = new OleDbDataAdapter (oleCommand );
- OleDbDataAdapter oleAdapter = new OleDbDataAdapter (query, connExcel );
- OleAdapter. Fill (dataSet, "gch_Class_Info ");
- // Insert records into the SQL Server data table after obtaining data from the excel file
- DataTable ableable1 = new DataTable ();
- SqlDataAdapter sqlDA1 = new SqlDataAdapter (@ "SELECT classID, classDate,
- ClassPlace, classTeacher, classTitle, durativeDate FROM gch_Class_Info ", sqlConnection1 );
- // SqlCommandBuilder sqlCB1 = new SqlCommandBuilder (sqlDA1 );
- SqlDA1.Fill (dataTable1 );
-
- Foreach (DataRow dataRow in dataSet. Tables ["gch_Class_Info"]. Rows)
- {
- DataRow dataRow1 = ableable1.newrow ();
- DataRow1 ["classDate"] = dataRow ["date"];
- DataRow1 ["classPlace"] = dataRow ["course class city"];
- DataRow1 ["classTeacher"] = dataRow [""];
- & Nb