首页 > 编程 > .NET > 正文

Accessing an Excel Spreadsheet in ASP.NET (VB and

2024-07-10 13:08:00
字体:
来源:转载
供稿:网友
view a live sample!  

this page provides a simple example of how to query an excel spreadsheet
from an asp.net page using either c# or vb.net. check it out!

this code was written in response to a message posted on one of
charles carroll's asp.net lists. you can sign up for one or all
of the lists here.

c# code
---------------------------------------------
<%@ page language="c#" %>
<%@ import namespace="system.data" %>
<%@ import namespace="system.data.ado" %>

<script language="c#" runat="server">
protected void page_load(object src, eventargs e)
{
string strconn;
strconn = "provider=microsoft.jet.oledb.4.0;" +
"data source=c://exceltest.xls;" +
"extended properties=excel 8.0;";
'you must use the $ after the object you reference in the spreadsheet
adodatasetcommand mycommand = new adodatasetcommand("select * from [sheet1$]", strconn);

dataset mydataset = new dataset();
mycommand.filldataset(mydataset, "excelinfo");
datagrid1.datasource = mydataset.tables["excelinfo"].defaultview;
datagrid1.databind();
}
</script>
<p><asp:label id=label1 runat="server">spreadsheet contents:</asp:label></p>
<asp:datagrid id=datagrid1 runat="server"/>


vb.net code
----------------------------------------------
<%@ page language="vb" %>
<%@ import namespace="system.data" %>
<%@ import namespace="system.data.ado" %>

<script language="vb" runat="server">
sub page_load(sender as object, e as eventargs)
dim mydataset as new dataset()

'you can also use the excel odbc driver i believe - didn't try though
dim strconn as string = "provider=microsoft.jet.oledb.4.0;" & _
"data source=c:/exceltest.xls;" & _
"extended properties=""excel 8.0;"""

'you must use the $ after the object you reference in the spreadsheet
dim myadodatasetcommand as new adodatasetcommand("select * from [sheet1$]", strconn)
myadodatasetcommand.tablemappings.add("table", "exceltest")
myadodatasetcommand.filldataset(mydataset)

datagrid1.datasource = mydataset.tables(0).defaultview
datagrid1.databind()
end sub
</script>
<p><asp:label id=label1 runat="server">spreadsheet contents:</asp:label></p>
<asp:datagrid id=datagrid1 runat="server"/>





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