首先,在*.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)