首页 > 开发 > .Net > 正文

asp.net Excel转换为SQL Server的方法

2020-04-24 22:09:16
字体:
来源:转载
供稿:网友
1.功能分析
通过Microsoft.Jet.OLEDB.4.0方式可实现使用ADO.NET访问Excel的目的,如以下示例代码为连接Excel数据的字符串:
代码如下:
string strOdbcCon = @"Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=D:/2010年图书销售情况.xls;Extended Properties=Excel 8.0";

2.实施方法
程序开发步骤:
(1)新建一个网站,命名为25,其主页默认为Default.aspx。
(2)Default.aspx页面中添加一个Table表格,用来布局页面,然后在该Table表格中添加一个iframe框架、两个Button控件和一个GridView控件,其中,iframe框架用来显示原始Excel数据表中的数据;Button控件分别用来将指定Excel中的数据表导入到SQL Server数据库中和将导入SQL Server数据库中的Excel数据绑定到GridView控件上;GridView控件用来显示导入SQL Server数据库中的Excel数据。
(3)程序主要代码如下。
Default.aspx页面中,首先自定义一个LoadData方法,该方法为无返回值类型方法,主要用来将Excel数据表中的数据导入到SQL Server数据库中。LoadData方法实现代码如下:
代码如下:
public void LoadData(string StyleSheet)
{
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source =" + Server.MapPath
("usersdb.xls") + ";Extended Properties=Excel 8.0";
OleDbConnection myConn = new OleDbConnection(strCon);
myConn.Open(); //打开数据链接,得到一个数据集
DataSet myDataSet = new DataSet(); //创建DataSet对象
string StrSql = "select * from [" + StyleSheet + "$]";
OleDbDataAdapter myCommand = new OleDbDataAdapter(StrSql, myConn);
myCommand.Fill(myDataSet, "[" + StyleSheet + "$]");
myCommand.Dispose();
DataTable DT = myDataSet.Tables["[" + StyleSheet + "$]"];
myConn.Close();
myCommand.Dispose();
string strConn = "Data Source=(local);DataBase=Usersdb;Uid=sa;Pwd=";
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
for (int j = 0; j < DT.Rows.Count; j++)
{
string UserID = DT.Rows[j][0].ToString();
string EmailAddress = DT.Rows[j][1].ToString();
string FirstName = DT.Rows[j][2].ToString();
string LastName = DT.Rows[j][3].ToString();
string Address1 = DT.Rows[j][4].ToString();
string Address2 = DT.Rows[j][5].ToString();
string City = DT.Rows[j][6].ToString();
string strSql = "insert into Usersdb(EmailAddress,FirstName,
LastName,Address1,Address2,City) ";
strSql = strSql + "values('" + EmailAddress + "','" + FirstName + "',
'" + LastName + "','" + Address1 + "','" + Address2 + "','" + City + "')";
SqlCommand comm = new SqlCommand(strSql, conn);
comm.ExecuteNonQuery();
if (j == DT.Rows.Count - 1)
{
Label1.Visible = true;
}
else
{
Label1.Visible = false;
}
}
conn.Close();
}

单击【Excel数据写入数据库中】按钮,定义一个string类型的变量,用来为LoadData传入参数,然后调用LoadData自定义方法将指定的Excel中的数据表导入到SQL Server数据库中。【Excel数据写入数据库中】按钮的Click事件代码如下:
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表