Asp.net导出数据到Excel中

本文详细介绍了如何在ASP.NET页面中使用GridView控件进行数据绑定,并将其导出为Excel文件。通过自定义方法实现数据转换为HTML格式,再通过响应输出至客户端,最终实现数据的高效导出。
 

using System;
using System.Collections.Generic;
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.SqlClient;
using System.IO;
using System.Collections;
using System.Text;

public class ClassA
{
    public string id { get; set; }
    public string Name { get; set;}
}
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
            this.BindGridView();
    }

    private void BindGridView()
    {
        ////创建使用Windows登陆的 SqlConnection对象
        //SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=accp;database=DemoDB");
        ////创建SqlCommand对象
        //SqlCommand com = con.CreateCommand();
        //com.CommandText = "SELECT * FROM Employee";

        ////创建数据适配器对象
        //SqlDataAdapter adpt = new SqlDataAdapter();
        //adpt.SelectCommand = com;

        ////填充DataSet
        //DataSet ds = new DataSet();
        //adpt.Fill(ds);


        //数据绑定
        IList<ClassA> lst = new List<ClassA>();
        ClassA a;
        a=new ClassA();
        a.id = "1";
        a.id = "name1";
        lst.Add(a);
        a = new ClassA();
        a.id = "1";
        a.id = "name1";
        lst.Add(a);
        this.GridView1.DataSource = lst;
        this.GridView1.DataBind();
    }

    /// <summary>
    /// 复写该方法保证GridView控件一定处于Form标记中
    /// 才可以保证GridView的RenderControl方法调用正确 不会抛出异常
    /// </summary>
    /// <param name="control"></param>
    public override void VerifyRenderingInServerForm(Control control)
    {
        //如果回发或使用客户端脚本的服务器控件没有包含在 HtmlForm 服务器控件
        //(<form runat="server">) 标记中,它们将无法正常工作
    }

    protected void Convert2Excel(string fileName)
    {
        //设定输入文件流的字符集
        this.Response.Charset = "gb2312";
        //设定编码方式为UTF7
        this.Response.ContentEncoding = Encoding.UTF7;
        //设定响应头 即响应中含有附件
        this.Response.AppendHeader("Content-Disposition",
            string.Format("attachments;filename={0}",
            HttpUtility.UrlEncode(fileName,Encoding.UTF8).ToString())
            );

        //设定响应类型为Excel文件
        this.Response.ContentType = "application/ms-excel";
        //响应不存储于ViewState中
        this.EnableViewState = false;

        //实例化字符流写入器
        StringWriter writer = new StringWriter();
        //实例化Html字符流写入器
        HtmlTextWriter hw = new HtmlTextWriter(writer);
        //将GridView中所有的数据和格式转化为Html代码并写入至Html字符流写入器
        this.GridView1.RenderControl(hw);
        //在响应中输出GridView控件的Html代码
        this.Response.Write(writer.ToString());
        //停止响应
        this.Response.End();
    }

    protected void btnConvert2Excel_Click(object sender, EventArgs e)
    {
        //输入文件名   导入至Excel文件中
        //this.Convert2Excel("~/员工信息.xls");
        this.ToExcel(this.GridView1,"~/员工信息.xls");

    }
    protected void GridView1_DataBinding(object sender, EventArgs e)
    {
       
    }

    private void ToExcel(Control ctl, string FileName)
    {
        HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
        ctl.Page.EnableViewState = false;
        System.IO.StringWriter tw = new System.IO.StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        ctl.RenderControl(hw);
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
    }

 

 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值