asp.net 訪問Excel的方法 收藏 < type="text/javascript">google_ad_client = "pub-2048279401139630";google_ad_slot = "8856771542";google_ad_width = 728;google_ad_height = 90;document.write(""); 方法一: 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./TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www./1999/xhtml" > <head runat="server"> <title>西狐 連接EXCEL數(shù)據(jù)源</title> </head> <body> <form id="form1" runat="server"> <div> <asp:DataGrid ID="MyDataGrid" runat=server></asp:DataGrid> </div> </form> </body> </html> ======================== 再建一個(gè)張Excel工作表,就OK了。本例保存EXCEL在D:\hooyes\wwwroot\excelsample.xls :ohh: 西狐掃盲貼 HOHO:ohh: 這是用ODBC.net 還可以用OLEDB.net 訪問 Excel表,引入名命空間不一樣就是了。 < type="text/javascript">google_ad_client = "pub-2048279401139630";google_ad_slot = "8856771542";google_ad_width = 728;google_ad_height = 90;document.write(""); 方法二: 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表格內(nèi)容:</asp:Label></p> <asp:DataGrid id=DataGrid1 runat="server"/> < type="text/javascript">google_ad_client = "pub-2048279401139630";google_ad_slot = "8856771542";google_ad_width = 728;google_ad_height = 90;document.write(""); 本文來自CSDN博客,轉(zhuǎn)載請(qǐng)標(biāo)明出處:http://blog.csdn.net/aspgreener/archive/2007/09/05/1772753.aspx |
|