1. 程式人生 > >C#將Excel資料表匯入SQL資料庫的兩種方法

C#將Excel資料表匯入SQL資料庫的兩種方法

方法一:

實現在c#中可高效的將excel資料匯入到sqlserver資料庫中,很多人通過迴圈來拼接sql,這樣做不但容易出錯而且效率低下,最好的辦法是使用bcp,也就是System.Data.SqlClient.SqlBulkCopy 類來實現。

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.ComponentModel;    
  4. using System.Data;    
  5. using System.Drawing;    
  6. using System.Linq;    
  7. using System.Text;    
  8. using System.Windows.Forms;    
  9. using System.Data.OleDb;    
  10. namespace ExcelToSQL    
  11. {    
  12. public partial class Form1 : Form    
  13.     {    
  14. public Form1()    
  15.         {    
  16.             InitializeComponent();    
  17.         }    
  18. privatevoid button1_Click(object sender, EventArgs e)    
  19.         {    
  20. //測試,將excel中的student匯入到sqlserver的db_test中,如果sql中的資料表不存在則建立      
  21. string connString = "server = (local); uid = sa; pwd = sa; database = db_test";    
  22.             System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();       
  23. if (fd.ShowDialog() == DialogResult.OK)       
  24.             {    
  25.                 TransferData(fd.FileName, "student", connString);    
  26.             }       
  27.         }       
  28. publicvoid TransferData(string excelFile, string sheetName, string connectionString)       
  29.         {       
  30.             DataSet ds = new DataSet();    
  31. try
  32.             {    
  33. //獲取全部資料   
  34. string strConn = "Provider = Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFile + ";" + "Extended Properties = Excel 8.0;";       
  35.                 OleDbConnection conn = new OleDbConnection(strConn);    
  36.                 conn.Open();    
  37. string strExcel = "";    
  38.                 OleDbDataAdapter myCommand = null;       
  39.                 strExcel = string.Format("select * from [{0}$]", sheetName);    
  40.                 myCommand = new OleDbDataAdapter(strExcel, strConn);    
  41.                 myCommand.Fill(ds, sheetName);    
  42. //如果目標表不存在則建立,excel檔案的第一行為列標題,從第二行開始全部都是資料記錄   
  43. string strSql = string.Format("if not exists(select * from sysobjects where name = '{0}') create table {0}(", sheetName);   //以sheetName為表名   
  44. foreach (System.Data.DataColumn c in ds.Tables[0].Columns)    
  45.                 {       
  46.                     strSql += string.Format("[{0}] varchar(255),", c.ColumnName);       
  47.                 }       
  48.                 strSql = strSql.Trim(',') + ")";       
  49. using (System.Data.SqlClient.SqlConnection sqlconn = new System.Data.SqlClient.SqlConnection(connectionString))       
  50.                 {    
  51.                     sqlconn.Open();       
  52.                     System.Data.SqlClient.SqlCommand command = sqlconn.CreateCommand();       
  53.                     command.CommandText = strSql;       
  54.                     command.ExecuteNonQuery();       
  55.                     sqlconn.Close();    
  56.                 }       
  57. //用bcp匯入資料      
  58. //excel檔案中列的順序必須和資料表的列順序一致,因為資料匯入時,是從excel檔案的第二行資料開始,不管資料表的結構是什麼樣的,反正就是第一列的資料會插入到資料表的第一列欄位中,第二列的資料插入到資料表的第二列欄位中,以此類推,它本身不會去判斷要插入的資料是對應資料表中哪一個欄位的   
  59. using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connectionString))       
  60.                 {       
  61.                     bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);       
  62.                     bcp.BatchSize = 100;//每次傳輸的行數      
  63.                     bcp.NotifyAfter = 100;//進度提示的行數      
  64.                     bcp.DestinationTableName = sheetName;//目標表      
  65.                     bcp.WriteToServer(ds.Tables[0]);    
  66.                 }       
  67.             }       
  68. catch (Exception ex)       
  69.             {       
  70.                 System.Windows.Forms.MessageBox.Show(ex.Message);       
  71.             }     
  72.         }       
  73. //進度顯示      
  74. void bcp_SqlRowsCopied(object sender, System.Data.SqlClient.SqlRowsCopiedEventArgs e)       
  75.         {       
  76. this.Text = e.RowsCopied.ToString();       
  77. this.Update();       
  78.         }      
  79.     }       
  80. }    

方法二:

先將Excel檔案轉換成DataTable,然後再迴圈將記錄插入到資料庫表中,這種方式可以任由程式設計師來選擇將哪列資料匯入到資料表的哪個欄位中
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.Data.OleDb;  
  10. using System.Data.SqlClient;  
  11. namespace ExcelToSQL  
  12. {  
  13. public partial class Form2 : Form  
  14.     {  
  15. public Form2()  
  16.         {  
  17.             InitializeComponent();  
  18.         }  
  19.         DataTable dt = new DataTable();  
  20. string connString = "server = (local); uid = sa; pwd = sa; database = db_test";  
  21.         SqlConnection conn;  
  22. privatevoid button1_Click(object sender, EventArgs e)  
  23.         {  
  24.             System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();  
  25. if (fd.ShowDialog() == DialogResult.OK)  
  26.             {  
  27. string fileName = fd.FileName;  
  28.                 bind(fileName);  
  29.             }  
  30.         }  
  31. privatevoid bind(string fileName)  
  32.         {  
  33. string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +  
  34. "Data Source=" + fileName + ";" +  
  35. "Extended Properties='Excel 8.0; HDR=Yes; IMEX=1'";  
  36.             OleDbDataAdapter da = new OleDbDataAdapter("SELECT *  FROM [student$]", strConn);  
  37.             DataSet ds = new DataSet();  
  38. try
  39.             {  
  40.                 da.Fill(ds);  
  41.                 dt = ds.Tables[0];  
  42. this.dataGridView1.DataSource = dt;  
  43.             }  
  44. catch (Exception err)  
  45.             {  
  46.                 MessageBox.Show("操作失敗!" + err.ToString());  
  47.             }  
  48.         }  
  49. //將Datagridview1的記錄插入到資料庫  
  50. privatevoid button2_Click(object sender, EventArgs e)  
  51.         {  
  52.             conn = new SqlConnection(connString);  
  53.             conn.Open();  
  54. if (dataGridView1.Rows.Count > 0)  
  55.             {  
  56.                 DataRow dr = null;  
  57. for (int i = 0; i < dt.Rows.Count; i++)  
  58.                 {  
  59.                     dr = dt.Rows[i];  
  60.                     insertToSql(dr);  
  61.                 }  
  62.                 conn.Close();  
  63.                 MessageBox.Show("匯入成功!");  
  64.             }  
  65. else
  66.             {  
  67.                 MessageBox.Show("沒有資料!");  
  68.             }  
  69.         }  
  70. privatevoid insertToSql(DataRow dr)  
  71.         {  
  72. //excel表中的列名和資料庫中的列名一定要對應
  73. string name = dr["StudentName"].ToString();  
  74. string sex = dr["Sex"].ToString();  
  75. string no = dr["StudentIDNO"].ToString();  
  76. string major = dr["Major"].ToString();  
  77. string sql = "insert into student values('" + name + "','" + sex + "','" + no + "','" + major +"')";           
  78.             SqlCommand cmd = new SqlCommand(sql, conn);             
  79.             cmd.ExecuteNonQuery();  
  80.         }  
  81.     }