DataGrid使用最佳实践(导出excel)

本文介绍了一种解决导出Excel文件时出现乱码的方法,通过调整编码和响应类型来确保中文正常显示。提供了完整的代码示例。

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

 导出excel问题:

朋友们在导出时,可能也会遇到乱码的问题,松子儿的解决方法如下:

下面是一段正确的导出按钮事件代码

 

private void btnMIME_Click(object sender, System.EventArgs e)
        
{
            Response.ContentType 
= "application/vnd.ms-excel";//响应类型
            Response.Charset = "";//响应编码类型
            Response.ContentEncoding = Encoding.UTF7;//注意:UTF8是不支持简体中文的
            this.EnableViewState = false;
            System.IO.StringWriter sw 
= new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw 
= new System.Web.UI.HtmlTextWriter(sw);
            
int nCur = dgShow.CurrentPageIndex;
            
int nSize = dgShow.PageSize;
            
            dgShow.AllowPaging 
= false;
            BindData();
                
            dgShow.Columns[
7].Visible =false;
            dgShow.RenderControl(hw);
            dgShow.Columns[
7].Visible =true;
            
            
//以下恢复分页
            dgShow.AllowPaging = true;
            dgShow.CurrentPageIndex 
= nCur;
            dgShow.PageSize 
= nSize;
            BindData();
            Response.Write(sw.ToString());
            Response.End();
        }

注意:设置输出流的http字符集(Response.ContentEncoding),“urf8”:不支持简体中文;“gb2312”:excel不支持,会报错!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值