Excel数据导入sql数据库(一)

本文提供了一个使用C#将Excel文件中的数据导入到SQL Server数据库的例子。通过OpenDataSource功能读取Excel文件,并利用SqlCommand对象执行SQL语句完成数据导入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有多种方式这里介绍第一种:  这里是完整的例子、很简单就不仔细写了
protected void BuploadTeacher() {       
  //OpenFileDialog openFileDialog = new OpenFileDialog();       
  // openFileDialog.Filter = "Excel files(*.xls)|*.xls";         
   SqlConnection sqlConnection1 = null;        
 string filePath = this.FImportStudent.FileName;        
 sqlConnection1 = new SqlConnection();        
 sqlConnection1.ConnectionString=ConfigurationManager.ConnectionStrings["ThesisConnectionString"].ConnectionString;  
 //export SQL Server 2000 into excel         
/*string exportSQL = @"EXEC master..xp_cmdshell 'bcp Library.dbo.live41 out " + filePath + "-c -q -S" + "/"" + "/"" +             " -U" + "/"" + "/"" + " -P" + "/"" + "/"" + "/'";*/         
 string importSQL = "SELECT * into test1 FROM OpenDataSource" +         "('Microsoft.Jet.OLEDB.4.0','Data Source=" + "/"" + "E://a.xls" + "/"" +         "; User ID=;Password=; Extended properties=Excel 5.0')...[Sheet1$]";        
 try {            
   sqlConnection1.Open();                    
    SqlCommand sqlCommand2 = new SqlCommand();            
    sqlCommand2.Connection = sqlConnection1;             
    sqlCommand2.CommandText = importSQL;             
    sqlCommand2.ExecuteNonQuery();            
     
  }        
 catch (Exception ex)        
 {                 
 }               
 if (sqlConnection1 != null)       
  {           
  sqlConnection1.Close();           
  sqlConnection1 = null;      
   } 
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值