将Excel转换为SQLServer数据库方法详解

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

作者:cuicheng0826 日期:2011-5-11 10:26:47

Excel是一种非常灵活的电子表格软件,用它可以存储各种数据,本节将对如何将Excel转换为SQL Server进行详细介绍。

1.方案分析

通过Microsoft.Jet.OLEDB.4.0方式可实现使用访问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.Tabl es[ "[" + 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事件代码如下:

protected void Button1_Click(object sender, EventArgs e)

相关文档
最新文档