解决字串乱码的问题,(例子,导出文件时,中文文件名乱码)

本文介绍了一种在ASP.NET应用程序中将GridView控件的数据导出到Excel文件的方法。通过设置响应头和编码方式,可以确保浏览器正确下载并显示Excel文件。此方法还涉及到禁用事件验证以避免安全性检查。

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

使用 设置为fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);

如下:

 public override void VerifyRenderingInServerForm(Control control)
        {
            //base.VerifyRenderingInServerForm(control);
        }


        /// <summary>
        /// 导出XLS(注意设置EnableEventValidation="false" )
        /// </summary>
        /// <param name="gv">GV</param>
        /// <param name="name">导出XLS文件名</param>  
        public void GridViewToExcel(GridView gv, string name)
        {
            gv.AllowPaging = false;
            Gvdatasorce();
            if (gv.Rows.Count == 0)
            {
                return;
            }
            for (int i = 0; i < gv.Rows.Count; i++)
            {
                ((Button)gv.Rows[i].FindControl("Button3")).Visible = false;

            }
           
            string style = @"<style> .text { mso-number-format:\@; } </script> ";
            System.Web.HttpContext.Current.Response.ClearContent();
            System.Web.HttpContext.Current.Response.Charset = "GB2312";
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.GetEncoding("utf-8")) + ".xls");
            System.Web.HttpContext.Current.Response.ContentType = "application/excel; charset=GB2312";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            System.Web.HttpContext.Current.Response.Write(style);
            System.Web.HttpContext.Current.Response.Write(sw.ToString());
            System.Web.HttpContext.Current.Response.End();
            gv.AllowPaging = true;
        }


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值