日期:2014-05-17 浏览次数:20877 次
Asp.Net将Excel数据导入Sql Server数据库的的例子,是调用存储过程的,大家分享. 前言:cmd.CommandText="Proc_Address";这句话是调用存储过程"Proc_Address" 该存储过程代码为: CREATE Proc Proc_Address @CardNo char(20),@ToAddress char(50),@CCAddress char(50) ,@YYYYMM char(12) as declare @strSql char (400) set @strSql = 'Insert into EmailAddress' + @YYYYMM + ' values(''+@CardNo+'',''+@ToAddress+'',''+@CCAddress+'',''+'1')' --插入一条记录 exec (@strSql) GO private void Button1_Click(object sender, System.EventArgs e) { CreateTable(); //先将EXCEL导入到数据库,一:先把EXCEL导入dateView,二:然后将dateView里的数据导入到数据库里面 //EXCEL 的连接串 string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + File1.PostedFile.FileName.ToString() + ";" + "Extended Properties=Excel 8.0;"; //建立EXCEL的连接 OleDbConnection objConn = new OleDbConnection(sConnectionString); objConn.Open(); OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM [Sheet1$]", objConn); OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(); objAdapter1.SelectCommand = objCmdSelect; DataSet objDataset1 = new DataSet(); objAdapter1.Fill(objDataset1, "XLData"); // DataGrid1.DataSource = objDataset1.Tables[0].DefaultView; //测试代码,用来测试是否能读出EXCEL上面的数据 // DataGrid1.DataBind(); DataTable dt = objDataset1.Tables[0]; DataView myView = new DataView(dt); //SQL SERVER的数据库连接 SqlConnection conn; string dns =System.Configuration.ConfigurationSettings.AppSettings["ConStr"];//连接串 conn=new SqlConnection(dns); SqlCommand cmd =conn.CreateCommand(); cmd.CommandType =CommandType.StoredProcedure; cmd.CommandText="Proc_Address"; int count=0;//用来记录出错的条数 try { foreach (DataRowView myDrv in myView) { count++; //要关闭上一次的SQL Server的连接 if (conn.State.ToString()!="Closed") conn.Close(); //每一次都要清空所有的CMD的参数 cmd.Parameters.Clear(); //执行存储过程 //首先获得参数 共 3个 //@CardNo,@ToAddress,@CCAddress SqlParameter paraCardNo =cmd.Parameters.Add("@CardNo",SqlDbType.Char); SqlParameter paraToAddress =cmd.Parameters.Add("@ToAddress",SqlDbType.Char); SqlParameter paraCCAddress =cmd.Parameters.Add("@CCAddress",SqlDbType.Char); SqlParameter paraYYYYMM =cmd.Parameters.Add("@YYYYMM",SqlDbType.Char); //表示是输入参数 paraCardNo.Direction = ParameterDirection.Input; paraToAddress.Direction = ParameterDirection.Input; paraCCAddress.Direction = ParameterDirection.Input; paraYYYYMM.Direction = ParameterDirection.Input; //参数赋值 paraCardNo.Value = myDrv[0].ToString().Trim(); paraToAddress.Value = myDrv[1].ToString().Trim(); paraCCAddress.Value = myDrv[2].ToString().Trim(); paraYYYYMM.Value = ddlYear.Items[ddlYear.SelectedIndex].Value + ddlMonth.Items[ddlMonth.SelectedIndex].Value; conn.Open(); cmd.ExecuteNonQuery();//写入SQL数据库 } } catch { Page.Response.Write("alert('第"+count.ToString()+"条数据出错!');" objConn.Close();//关闭EXCEL的连接 } objConn.Close();//关闭EXCEL的连接
------解决方案--------------------
excel
access