且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

asp.net中将Excel文件(.xls)绑定到DataGrid

更新时间:2022-09-19 08:20:58

asp.net中将Excel文件(.xls)绑定到DataGrid! 
首先,在*.aspx.cs文件头部添加如下引用:
using System.Data.OleDb;//用于将Excel文件绑定到DataGrid
其次,在Page_Load()函数中添如下示例代码:
if(!IsPostBack)
   {
    string strCon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath("../xls_bang/bang.xls")+";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
    OleDbConnection oleCon=new OleDbConnection(strCon);
    OleDbDataAdapter oleDA=new OleDbDataAdapter("select * from [Sheet1$]",oleCon);
    DataSet ds=new DataSet();
    oleDA.Fill(ds);
    dgBang.DataSource=ds;
    dgBang.DataBind();
     
   }
说明:bang.xls是需要绑到DataGrid(dgBang)的Excel文件。
Sheet1是bang.xls中的一个工作表单(work sheet)
"HDR=Yes;" :说明第一行包含的是列名,而不是数据
"IMEX=1;" :告诉驱动总是读交叉数据列作为文本
("HDR=Yes;" indicates that the first row contains columnnames, not data
"IMEX=1;" tells the driver to always read "intermixed" data columns as text)















本文转自terryli51CTO博客,原文链接: http://blog.51cto.com/terryli/519597,如需转载请自行联系原作者