面朝大海,春暖华开

focus on scientific computue, 3dgis, spatial database
专注于科学计算、GIS空间分析

 

asp.net2.0 GridView 导出到 Excel

step 1:
在再这页的aspx文件<%@ Page Language="C#" AutoEventWireup="true"  %>
中加上EnableEventValidation="false"
step 2:
把这段代码加在cs 文件中
public override void VerifyRenderingInServerForm(Control control)
    {
        // base.VerifyRenderingInServerForm(control);
    }
step 3:
后台(1)
protected void btnExcel_Click(object sender, EventArgs e)
{
//导出到excel
GVStaff.AllowPaging = false;
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=人员信息.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
this.EnableViewState = false;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
GV1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
后台(2)
    protected void Button1_Click(object sender, EventArgs e)
    {
        System.Web.UI.Control ctl = GridView1;
        bool CurrCtlVisible = ctl.Visible;
        ctl.Visible = true;
        Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.ContentType = "application/ms-excel";
        ctl.Page.EnableViewState = false;
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
        ctl.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();

        ctl.Page.EnableViewState = true;
        ctl.Visible = CurrCtlVisible;
    }

posted on   风过 无痕  阅读(354)  评论(0编辑  收藏  举报

(评论功能已被禁用)
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

统计

向日葵支付宝收钱码
点击右上角即可分享
微信分享提示