a simple and easy way to export grid(grid view) to excel

本文介绍了一种简单的方法来实现在ASP.NET中使用GridView控件导出数据到Excel文件的功能。通过设置HTTP响应头、使用StringWriter和HtmlTextWriter渲染控件,并最终将输出流发送给客户端完成导出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

how to export  a gird/gridview data to an excel file ? 

有一种比较简单的实现方式,代码如下:

  protected void Button1_Click(object sender, EventArgs e)
    
{
        Response.Clear();
        Response.AddHeader(
"content-disposition","attachment;filename=myexcel.xls");
        
//http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
        Response.ContentType = "application/vnd.xls";
        StringWriter sw 
= new StringWriter();
        HtmlTextWriter htw 
= new HtmlTextWriter(sw);
        
this.GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
        sw.Dispose();
        htw.Dispose();
 

    }
  • 有可能出现的问题:

    1.   Control 'ctl00_ContentPlaceHolder1_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.

   解决:

                             在页面的CodeBehind中添加(什么都不做,只是 跳过验证):

   public override void VerifyRenderingInServerForm(Control control)

    {

        //base.VerifyRenderingInServerForm(control);

}

                 2.  RegisterForEventValidation can only be called during Render();

   解决:

        在页面的Page  directive中添加: EnableEventValidation="false"

   3.为什么最后一定要有:Respobnse.End()

              原因:利用Response.End(),设置将Stream的写入中断。如果不这样处理,在文件下载的最后,生成aspx文件的HTML内容就会被写入。另外,这样做的话,就可以发现从Prgramm写入Response Stream是在aspx文件生成HTML前。
4.如果下载的文件名中含有英文字符的时候,需要利用HttpServerUtility类的UrlEncode

 string fname = System.Web.HttpServerUtility.UrlEncode("てすと.xls");

5.类推,我们可以导出成word(pdf)格式,只需要把文件名的后缀改为.doc(.pdf).

6.效果:

aspx页面:

导出的excell:


 在代码中如果注释掉
Respobnse.End() 后,导出的结果如下:


由此可见,从Prgramm写入Response Stream是在aspx文件生成HTML前。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值