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.     
  11. namespace ExcelToSQL    
  12. {    
  13.     public partial class Form1 : Form    
  14.     {    
  15.         public Form1()    
  16.         {    
  17.             InitializeComponent();    
  18.         }    
  19.     
  20.         private void button1_Click(object sender, EventArgs e)    
  21.         {    
  22.             //测试,将excel中的student导入到sqlserver的db_test中,如果sql中的数据表不存在则创建        
  23.             string connString = "server = (local); uid = sa; pwd = sa; database = db_test";    
  24.             System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();       
  25.             if (fd.ShowDialog() == DialogResult.OK)       
  26.             {    
  27.                 TransferData(fd.FileName, "student", connString);    
  28.             }       
  29.         }       
  30.     
  31.         public void TransferData(string excelFile, string sheetName, string connectionString)       
  32.         {       
  33.             DataSet ds = new DataSet();    
  34.             try      
  35.             {    
  36.                 //获取全部数据     
  37.                 string strConn = "Provider = Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFile + ";" + "Extended Properties = Excel 8.0;";       
  38.                 OleDbConnection conn = new OleDbConnection(strConn);    
  39.                 conn.Open();    
  40.                 string strExcel = "";    
  41.                 OleDbDataAdapter myCommand = null;       
  42.                 strExcel = string.Format("select * from [{0}$]", sheetName);    
  43.                 myCommand = new OleDbDataAdapter(strExcel, strConn);    
  44.                 myCommand.Fill(ds, sheetName);    
  45.       
  46.                 //如果目标表不存在则创建,excel文件的第一行为列标题,从第二行开始全部都是数据记录     
  47.                 string strSql = string.Format("if not exists(select * from sysobjects where name = '{0}') create table {0}(", sheetName);   //以sheetName为表名     
  48.     
  49.                 foreach (System.Data.DataColumn c in ds.Tables[0].Columns)    
  50.                 {       
  51.                     strSql += string.Format("[{0}] varchar(255),", c.ColumnName);       
  52.                 }       
  53.                 strSql = strSql.Trim(',') + ")";       
  54.       
  55.                 using (System.Data.SqlClient.SqlConnection sqlconn = new System.Data.SqlClient.SqlConnection(connectionString))       
  56.                 {    
  57.                     sqlconn.Open();       
  58.                     System.Data.SqlClient.SqlCommand command = sqlconn.CreateCommand();       
  59.                     command.CommandText = strSql;       
  60.                     command.ExecuteNonQuery();       
  61.                     sqlconn.Close();    
  62.                 }       
  63.                 //用bcp导入数据        
  64.                 //excel文件中列的顺序必须和数据表的列顺序一致,因为数据导入时,是从excel文件的第二行数据开始,不管数据表的结构是什么样的,反正就是第一列的数据会插入到数据表的第一列字段中,第二列的数据插入到数据表的第二列字段中,以此类推,它本身不会去判断要插入的数据是对应数据表中哪一个字段的     
  65.                 using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connectionString))       
  66.                 {       
  67.                     bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);       
  68.                     bcp.BatchSize = 100;//每次传输的行数        
  69.                     bcp.NotifyAfter = 100;//进度提示的行数        
  70.                     bcp.DestinationTableName = sheetName;//目标表        
  71.                     bcp.WriteToServer(ds.Tables[0]);    
  72.                 }       
  73.             }       
  74.             catch (Exception ex)       
  75.             {       
  76.                 System.Windows.Forms.MessageBox.Show(ex.Message);       
  77.             }     
  78.         }       
  79.       
  80.         //进度显示        
  81.         void bcp_SqlRowsCopied(object sender, System.Data.SqlClient.SqlRowsCopiedEventArgs e)       
  82.         {       
  83.             this.Text = e.RowsCopied.ToString();       
  84.             this.Update();       
  85.         }      
  86.     }       
  87. }    

方法二:

先将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.  
  12. namespace ExcelToSQL  
  13. {  
  14.     public partial class Form2 : Form  
  15.     {  
  16.         public Form2()  
  17.         {  
  18.             InitializeComponent();  
  19.         }  
  20.  
  21.         DataTable dt = new DataTable();  
  22.         string connString = "server = (local); uid = sa; pwd = sa; database = db_test";  
  23.         SqlConnection conn;  
  24.  
  25.         private void button1_Click(object sender, EventArgs e)  
  26.         {  
  27.             System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();  
  28.             if (fd.ShowDialog() == DialogResult.OK)  
  29.             {  
  30.                 string fileName = fd.FileName;  
  31.                 bind(fileName);  
  32.             }  
  33.         }  
  34.         private void bind(string fileName)  
  35.         {  
  36.             string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +  
  37.                  "Data Source=" + fileName + ";" +  
  38.                  "Extended Properties='Excel 8.0; HDR=Yes; IMEX=1'";  
  39.             OleDbDataAdapter da = new OleDbDataAdapter("SELECT *  FROM [student$]", strConn);  
  40.             DataSet ds = new DataSet();  
  41.             try 
  42.             {  
  43.                 da.Fill(ds);  
  44.                 dt = ds.Tables[0];  
  45.                 this.dataGridView1.DataSource = dt;  
  46.             }  
  47.             catch (Exception err)  
  48.             {  
  49.                 MessageBox.Show("操作失败!" + err.ToString());  
  50.             }  
  51.         }  
  52.  
  53.         //将Datagridview1的记录插入到数据库    
  54.         private void button2_Click(object sender, EventArgs e)  
  55.         {  
  56.             conn = new SqlConnection(connString);  
  57.             conn.Open();  
  58.             if (dataGridView1.Rows.Count > 0)  
  59.             {  
  60.                 DataRow dr = null;  
  61.                 for (int i = 0; i < dt.Rows.Count; i++)  
  62.                 {  
  63.                     dr = dt.Rows[i];  
  64.                     insertToSql(dr);  
  65.                 }  
  66.                 conn.Close();  
  67.                 MessageBox.Show("导入成功!");  
  68.             }  
  69.             else 
  70.             {  
  71.                 MessageBox.Show("没有数据!");  
  72.             }  
  73.         }  
  74.         private void insertToSql(DataRow dr)  
  75.         {  
  76.             //excel表中的列名和数据库中的列名一定要对应  
  77.             string name = dr["StudentName"].ToString();  
  78.             string sex = dr["Sex"].ToString();  
  79.             string no = dr["StudentIDNO"].ToString();  
  80.             string major = dr["Major"].ToString();  
  81.             string sql = "insert into student values('" + name + "','" + sex + "','" + no + "','" + major +"')";           
  82.             SqlCommand cmd = new SqlCommand(sql, conn);             
  83.             cmd.ExecuteNonQuery();  
  84.         }  
  85.     }  
  • 0
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值