Default.aspx
View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 id="Head1" runat="server"> <title>访问Excel文件</title> </head> <body> <form id="form1" runat="server"> <div> <div style="text-align: center"> <div style="text-align: center"> <table style="border-left-color: #996600; border-bottom-color: #996600; width: 500px; border-top-style: solid; border-top-color: #996600; border-right-style: solid; border-left-style: solid; border-right-color: #996600; border-bottom-style: solid"> <tr> <td style="width: 100px"> <asp:Label ID="Label1" runat="server" Text="访问Excel文件" Width="111px"></asp:Label></td> </tr> <tr> <td style="width: 100px"> <asp:GridView ID="GridView1" runat="server" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Width="471px"> <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" /> <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" /> <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" /> <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" /> <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" /> </asp:GridView> </td> </tr> <tr> <td style="width: 100px; height: 36px"> <asp:Button ID="BtnOk" runat="server" OnClick="BtnOk_Click" Text="连接" Width="49px" /></td> </tr> </table> </div> </div> </div> </form> </body> </html>
Default.aspx.cs
View Code
using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.OleDb; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void BtnOk_Click(object sender, EventArgs e) { try { string strConn; strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("学生成绩.xls") + ";" + "Extended Properties=Excel 8.0;"; OleDbDataAdapter cmd = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn); DataSet ds = new DataSet(); cmd.Fill(ds, "Excelstudent"); this.GridView1.DataSource = ds.Tables["Excelstudent"].DefaultView; this.GridView1.DataBind(); Response.Write("<script language=javascript>alert('恭喜您!Excel文件访问成功!')</script>"); } catch { Response.Write("<script language=javascript>alert('很遗憾!Excel文件访问失败!')</script>"); } } }