把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>