将txt文件和excel文件导入SQL2000数据库

在做一些web数据库管理系统的时候经常要实现将帐户批量注册的功能,今天就来讲讲如何在C#-web项目中将txt文件和excel文件导入SQL2000数据库。
1.数据库准备
在SQL2000数据库的实例数据库pubs中建立一个数据表txtInsert,字段很简单:id,name两个。
2.txt文本文件导入
对于数据文件导入与导出SQL2000提供了BULK INSERT和BCP语句,在这里可以使用BULK INSERT命令实现。假设在c盘上有一个文本文件stu.txt内容为:
    1,tom
    2,jack
    3,jhon
    ......
实现导入的C#代码如下:
protected System.Web.UI.HtmlControls.HtmlInputFile fName; 
protected System.Web.UI.WebControls.Button BtnInsert;
//上面两个控件自己添加
None.gif private   void  BtnInsert_Click( object  sender, System.EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif  
dot.gif {
InBlock.gif                
string fPath=this.fName.PostedFile.FileName;//获得要导入的文本文件                  
InBlock.gif
            string extName=fPath.Substring(fPath.LastIndexOf(".")+1);//获得文件的扩展名            
InBlock.gif
            SqlConnection con=new SqlConnection("server=.;database=pubs;uid=sa;pwd=;");//数据库连接对象
InBlock.gif
            con.Open();
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{                    
InBlock.gif                    SqlCommand com
=new SqlCommand("BULK INSERT pubs.dbo.txtInsert FROM '"+fPath+"' WITH  (FIELDTERMINATOR = ',',ROWTERMINATOR= '\n')",con);
InBlock.gif                       
//其中的FIELDTERMINATOR=','指明字段间所使用的分隔符为逗号
InBlock.gif                       
//其中ROWTERMINATOR= '\n'指明记录间所使用的分隔符为回车
InBlock.gif
                    com.ExecuteNonQuery();
InBlock.gif                    Response.Write(
"<script language=javascript>alert('数据导入成功!')</script>");                    
ExpandedSubBlockEnd.gif                }

InBlock.gif             
catch (SqlException SQLexc)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    Response.Write(
"导入数据库时出错:" + SQLexc.ToString());
ExpandedSubBlockEnd.gif                }

InBlock.gifcon.Close();
ExpandedBlockEnd.gif}

好了,这个txt文件的导入相对简单,在数据库中我也没有设置主键,我在里面也没有加出错回滚事务操作,在下面的excel文件的导入中介绍。
3.excel文件的导入
在c盘里建立一个stu.xls文件,在sheet1工作表中有两列数据如下:
     编号  姓名
     1        tom
     2        jack
     3        john
     ......
注意,工作表的第一行是作为标题行的不会被插入到数据库中,真正导入从第二行开始。
为了演示事物出错回滚,在这里将txtInsert数据库表中的id字段设置为主键。实现的C#代码如下:
None.gif private   void  BtnInsert_Click( object  sender, System.EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif  
dot.gif {
InBlock.gif   
string fPath=this.fName.PostedFile.FileName;//获得要导入的文本文件     
InBlock.gif
   string extName=fPath.Substring(fPath.LastIndexOf(".")+1);//获得文件的扩展名   
InBlock.gif
   SqlConnection con=new SqlConnection("server=.;database=pubs;uid=sa;pwd=;");//数据库连接对象
InBlock.gif
   con.Open();   
InBlock.gif    
//注意下面的连接字符串,是它起到了导入的作用
InBlock.gif
    SqlCommand excelCmd=new SqlCommand("insert into txtInsert select * from OPENROWSET('MICROSOFT.JET.OLEDB.4.0','Excel 5.0;HDR=YES;DATABASE="+fPath+"',Sheet1$)",con);
InBlock.gif    SqlTransaction myTran
=con.BeginTransaction();//开始一个事务操作
InBlock.gif
    excelCmd.Transaction=myTran;
InBlock.gif    
try
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{       
InBlock.gif     excelCmd.ExecuteNonQuery();
InBlock.gif     myTran.Commit();
//提交事务       
InBlock.gif
     Response.Write("<script language=javascript>alert('数据导入成功!')</script>");
ExpandedSubBlockEnd.gif    }

InBlock.gif    
catch (SqlException err)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{       
InBlock.gif     myTran.Rollback(); 
//出错回滚事务操作
InBlock.gif     
//以下三行是去掉数据库出错信息中的非法字符单引号、回车和换行符,否则在使用时javascript代码将有语法错误
InBlock.gif     
//因为js的编码和c#的编码不同
InBlock.gif
     string errString=err.Message.Replace("'"," ");
InBlock.gif     errString
=errString.Replace(Convert.ToChar(13).ToString(),"");
InBlock.gif     errString
=errString.Replace(Convert.ToChar(10).ToString(),"");
InBlock.gif     
//显示出错信息框
InBlock.gif
     Response.Write("<script language=javascript>alert('导入数据库时出错!详细信息:"+errString+"')</script>");         
ExpandedSubBlockEnd.gif    }
   
InBlock.gif   con.Close();
ExpandedBlockEnd.gif  }
None.gif
这里“显示出错信息框”开始我没有田间那三行代码,结果搞了半天,最后还是在html文件中发现javascript代码部分出现了分行,老是提示“未结束的字符串常量”,所以导致不能打开信息框,郁闷死我了,花了好多时间。
4.将excel中部分列导入数据库的方法
上面讲了关于将整个excel文件导入数据库的方法,那么在实际项目中遇到将excel文件中若干列导入数据库怎么办的呢,原理差不多,我就将代码直接给出了:
                    string   fPath=this.fName.PostedFile.FileName;//获得要导入的文本文件     
                    string   extName=fPath.Substring(fPath.LastIndexOf(".")+1);//获得文件的扩展名   
                   SqlConnection con=new SqlConnection("server=.;database=pubs;uid=sa;pwd=;");//数据库连接对象
                   con.Open(); None.gif                 
                   string  mystring = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = ' " + fPath + " ';Extended Properties=Excel 8.0 " ;
None.gif                OleDbConnection cnnxls 
=   new  OleDbConnection (mystring);
None.gif                OleDbDataAdapter myDa 
= new  OleDbDataAdapter( " select * from [Sheet1$] " ,cnnxls);
None.gif                DataSet myDs 
= new  DataSet();
None.gif                myDa.Fill(myDs);
None.gif                
if (myDs.Tables[ 0 ].Rows.Count  >   0 )
ExpandedBlockStart.gifContractedBlock.gif                
dot.gif {
InBlock.gif                    
string strSql = "";
InBlock.gif                    
string CnnString="Provider=SQLOLEDB;database=pubs;server=.;uid=sa;pwd=";
InBlock.gif                    OleDbConnection conn 
=new OleDbConnection(CnnString);
InBlock.gif                    conn.Open ();
InBlock.gif                    OleDbCommand myCmd 
=null;                    
InBlock.gif                    
for(int i=0; i<myDs.Tables[0].Rows.Count;i++)//第一个工作表中行数,不包括第一行,
ExpandedSubBlockStart.gifContractedSubBlock.gif
                    dot.gif{
InBlock.gif                        
strSql="insert into txtInsert(id,name) values (";
InBlock.gif                        strSql 
+= myDs.Tables[0].Rows[i].ItemArray[0].ToString() + ", '";
InBlock.gif                        strSql 
+= myDs.Tables[0].Rows[i].ItemArray[1].ToString() + "')";
InBlock.gif                        myCmd
=new OleDbCommand(strSql,conn);
                        
InBlock.giftry
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{                            
InBlock.gif                            myCmd.ExecuteNonQuery();InBlock.gif                                                        
InBlock.gif                            Response.Write(
"<script language=javascript>alert('数据导入成功!')</script>");
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        
catch (OleDbException err)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{                            InBlock.gif                           
InBlock.gif                            Response.Write(
"导入数据库时出错:" +err.ToString());
InBlock.gif                            
break;
ExpandedSubBlockEnd.gif                        }

ExpandedSubBlockEnd.gif                    }

InBlock.gif                    conn.Close();
其他部分代码自己加吧,这里就是出错失误回滚有点不好处理,请高手指教!!

转载于:https://www.cnblogs.com/mc-dragon/archive/2007/01/18/624238.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值