数据导出到Excel方法

=============================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数据控件进行数据绑定
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值