=============================myPage.aspx 页面 代码如下==============================
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="myPage.aspx.cs" Inherits="myPage" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>myPage</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</form>
</body>
</html>
=============================myPage.aspx.cs 代码如下===============================
using System;
using System.Data;
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;
using System.Data.SqlClient;
public partial class myPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.Response.ContentType = "application/vnd.ms-excel"; //表示以Excel方式输出.
string ConnStr = "server=localhost;uid=sa;pwd=;database=northwind"; //创建连接字符串
SqlConnection Conn = new SqlConnection(ConnStr); //创建SqlConnection连接对象
Conn.Open(); //打开连接对象
string sqlcmd = "select lastname,firstname,title, address, city from employees";
SqlCommand cmd = new SqlCommand(sqlcmd, Conn); //创建SqlCommand 对象cmd 用于执行SQL操作
SqlDataAdapter adapter = new SqlDataAdapter(cmd); //创建SqlDataAdapter 数据适配器
DataSet ds = new DataSet(); //创建DataSet 数据集合
adapter.Fill(ds); //填充数据
this.GridView1.DataSource = ds.Tables[0].DefaultView;
this.GridView1.DataBind(); //对GridView数据控件进行数据绑定
}
}
}