程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 將Excel文件數據導入到SqlServer數據庫的三種方案

將Excel文件數據導入到SqlServer數據庫的三種方案

編輯:C#入門知識

方案一: 通過OleDB方式獲取Excel文件的數據,然後通過DataSet中轉到SQL Server,這種方法的優點是非常的靈活,可以對Excel表中的各個單元格進行用戶所需的操作。

 

  1. openFileDialog = new OpenFileDialog();  
  2. openFileDialog.Filter = "Excel files(*.xls)|*.xls";  
  3.  
  4. if(openFileDialog.ShowDialog()==DialogResult.OK)  
  5. {  
  6.     FileInfo fileInfo = new FileInfo(openFileDialog.FileName);  
  7.     string filePath = fileInfo.FullName;  
  8.     string connExcel = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0";  
  9.       
  10.     try 
  11.     {  
  12.         OleDbConnection oleDbConnection = new OleDbConnection(connExcel);  
  13.         oleDbConnection.Open();  
  14.           
  15.         //獲取excel表  
  16.         DataTable dataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);  
  17.  
  18.         //獲取sheet名,其中[0][1]...[N]: 按名稱排列的表單元素  
  19.         string tableName = dataTable.Rows[0][2].ToString().Trim();  
  20.         tableName = "[" + tableName.Replace("","") + "]";  
  21.  
  22.         //利用SQL語句從Excel文件裡獲取數據  
  23.         //string query = "SELECT classDate,classPlace,classTeacher,classTitle,classID FROM " + tableName;  
  24.         string query = "SELECT 日期,開課城市,講師,課程名稱,持續時間 FROM " + tableName;  
  25.         dataSet = new DataSet();  
  26.  
  27.         //OleDbCommand oleCommand = new OleDbCommand(query, oleDbConnection);  
  28.         //OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);  
  29.         OleDbDataAdapter oleAdapter = new OleDbDataAdapter(query,connExcel);  
  30.         oleAdapter.Fill(dataSet,"gch_Class_Info");  
  31.         //從excel文件獲得數據後,插入記錄到SQL Server的數據表
  32.         DataTable dataTable1 = new DataTable();  
  33.           
  34.         SqlDataAdapter sqlDA1 = new SqlDataAdapter(@"SELECT classID, classDate,  
  35. classPlace, classTeacher, classTitle, durativeDate FROM gch_Class_Info",sqlConnection1);  
  36.           
  37.         //SqlCommandBuilder sqlCB1 = new SqlCommandBuilder(sqlDA1);  
  38.           
  39.         sqlDA1.Fill(dataTable1);  
  40.  
  41.         foreach(DataRow dataRow in dataSet.Tables["gch_Class_Info"].Rows)  
  42.         {  
  43.             DataRow dataRow1 = dataTable1.NewRow();  
  44.               
  45.             dataRow1["classDate"] = dataRow["日期"];  
  46.             dataRow1["classPlace"] = dataRow["開課城市"];  
  47.             dataRow1["classTeacher"] = dataRow["講師"];  
  48. &nb

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved