GridView 导出到excel ,同时还处理数字过长的办法

本文介绍了一种在ASP.NET应用程序中将GridView数据导出到Excel的方法,包括设置响应头、编码格式及使用StringWriter与HtmlTextWriter进行数据渲染的具体步骤,并提供了一段处理GridView导出时常见错误的代码。

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

public override void VerifyRenderingInServerForm(Control control) //不写这个重载函数容易报错,错误内容为:类型"GridView"的控件"GridView1"必须放在具有 runat=server 的窗体标记内。
        {
            // Confirms that an HtmlForm control is rendered for
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "UTF-8";
            Response.AppendHeader("Content-Disposition", "attachment;filename=SampleInspectation.xls");
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            this.GridView1.RenderControl(oHtmlTextWriter);
            Response.Output.Write(oStringWriter.ToString());
            Response.Flush();
            Response.End();

        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

          //需要操作的列则不能使用此方法,只需在长数字那一列用此方法如是第二列,则代码为:

          e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");//这里是第二列

        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值