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

本文介绍如何在ASP.NET中使用OleDb将Excel文件(.xls)的数据绑定到DataGrid控件上。通过示例代码展示了连接字符串配置、数据适配器及数据集的使用方法。
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,如需转载请自行联系原作者




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值