方法一:
ODBC方法:
=================connectExcel.aspx.cs中源码这样写下来==============================
using System;
using System.Data;
using System.Data.Odbc;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class connectExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String connstr = @"Driver=Microsoft Excel Driver (*.xls);Dbq=D:/hooyes/wwwroot/excelsample.xls;";
OdbcConnection myConnection = new OdbcConnection(connstr);
myConnection.Open();
OdbcCommand myCommand = new OdbcCommand("select * from[Sheet1$]", myConnection);
MyDataGrid.DataSource = myCommand.ExecuteReader();
MyDataGrid.DataBind();
myConnection.Close();
}
}
然后新建一张 connectExcel.aspx===================================
代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="connectExcel.aspx.cs" Inherits="connectExcel" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>西狐 连接EXCEL数据源</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataGrid ID="MyDataGrid" runat=server></asp:DataGrid>
</div>
</form>
</body>
</html>
========================
再建一个张Excel工作表,就OK了。本例保存EXCEL在D:/hooyes/wwwroot/excelsample.xls
:ohh: 西狐扫盲贴 HOHO:ohh:
这是用ODBC.net 还可以用OLEDB.net 访问 Excel表,引入名命空间不一样就是了。
<script type="text/javascript">google_ad_client = "pub-2048279401139630";google_ad_slot = "8856771542";google_ad_width = 728;google_ad_height = 90;document.write("<s"+"cript type='text/javascript' s"+"rc='http://pagead2.googlesyndication.com/pagead/show_ads"+"."+"js'></scr"+"ipt>");</script>
方法二:
OLEDB
<%@ 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;";
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">Excel表格内容:</asp:Label></p>
<asp:DataGrid id=DataGrid1 runat="server"/>