首页 > 开发 > 综合 > 正文

把Excel文件中的数据读入到DataGrid中

2024-07-21 02:23:09
字体:
来源:转载
供稿:网友
使用excel文件做为datagrid的数据源是非常简单的,一旦数据被装载进来,就可以把数据再保存进sql server或xml中。我们只需要简单地使用ole db provider 来访问excel文件,然后返回dataset即可。
下面是要显示的excel数据contact.xls:


姓名 性别 地址
net_lover male [email protected]
amxh male [email protected]
孟子 e 章 male [email protected]


只需要指定excel路径,并用[]选择一个工作表即可。

完整代码如下:
<%@ page language="c#" debug="true" %>
<%@ import namespace="system.data"%>
<%@ import namespace="system.data.oledb"%>

<script runat="server">

private dataset createdatasource(){
string strconn;
strconn = "provider=microsoft.jet.oledb.4.0;" +
"data source=c://inetpub//wwwroot//contacts.xls;"+
"extended properties=excel 8.0;";
oledbconnection conn = new oledbconnection(strconn);
oledbdataadapter mycommand = new oledbdataadapter("select * from [contactlist$]", strconn);
dataset mydataset = new dataset();
mycommand.fill(mydataset);
return mydataset;
}


public void page_load(object sender, eventargs e){
if (!ispostback) {
mygrid.datasource = createdatasource();
mygrid.databind();
}

}


</script>


<center>
<form runat="server">
<asp:datagrid runat="server" autogeneratecolumns="false"
width="500" id="mygrid">

<headerstyle bordercolor="white" backcolor="black"
forecolor="white"
font-bold="true"
font-name="arial"
font-size="9" horizontalalign="center"/>

<itemstyle bordercolor=""
backcolor="#fffff0"
forecolor="black"
font-name="arial"
font-size="8"
font-bold="false" horizontalalign="center"/>

<columns>

<asp:boundcolumn headertext="姓名" readonly="true" datafield="姓名"/>
<asp:boundcolumn headertext="性别" readonly="true" datafield="性别"/>
<asp:boundcolumn headertext="email" readonly="true" datafield="地址"/>
</columns>

</asp:datagrid>
</form>




发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表