说三道四技术文摘-感悟人生的经典句子
说三道四 > 文档快照

使用C#读取上传的Excel文件

HTML文档下载 WORD文档下载 PDF文档下载
在C#中以OLEDB方式读取EXCEL表单数据

 

下面给出的代码是在C#中以OLEDB方式读取EXCEL表单数据。 

 

建立一个网站工程,添加文件上传控件和按钮,在按钮点击事件处理中我们读取上传的文件,然后用OLEDB来连接它,执行SQL语句读取数据。

具体的代码如下:

 

using System;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.Data.OleDb;public partial class _Default : System.Web.UI.Page {protected void Page_Load(object sender, EventArgs e){ }protected void Button1_Click(object sender, EventArgs e){string path = System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName);string connString = "provider=Microsoft.Jet.OLEDB.4.0;" + @"data source="+path +";" + "Extended Properties=Excel 8.0;"; OleDbConnection oledbConn = new OleDbConnection(connString);try{oledbConn.Open();OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);OleDbDataAdapter oleda = new OleDbDataAdapter();oleda.SelectCommand = cmd;DataSet ds = new DataSet();oleda.Fill(ds, "Table");GridView1.DataSource = ds.Tables[0].DefaultView;GridView1.DataBind();}catch{}finally{oledbConn.Close();} }}

 

 

 

备案号:鲁ICP备13029499号-2 说三道四 www.s3d4.cn 说三道四技术文摘