changwen313 2017-09-14 09:47 采纳率: 100%
浏览 1186
已采纳

.net gridview导出成excel汉字是乱码问题

.net gridview导出成excel,两个功能界面,代码是复制过来的,但是导出的excel一个汉字是乱码,一个正常,是哪里的问题呀?
代码如下,请指教
protected void btnExcel_Click(object sender, EventArgs e)
{
DateTime dt = System.DateTime.Now;
string str = dt.ToString("yyyyMMddhhmmss");
str = str + "-汇总.xls";

    selectFlag = 1;
    GridView2.AllowPaging = false;

    SelectGetData();
    GridViewToExcel(GridView2, "application/ms-excel", str);


}

/// <summary>
/// 将网格数据导出到Excel
/// </summary>
/// <param name="ctrl">网格名称(如GridView1)</param>
/// <param name="FileType">要导出的文件类型(Excel:application/ms-excel)</param>
/// <param name="FileName">要保存的文件名</param>
public static void GridViewToExcel(Control ctrl, string FileType, string FileName)
{
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.Buffer = false;
    HttpContext.Current.Response.Charset = "UTF-8";
    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");//注意编码
    HttpContext.Current.Response.AppendHeader("Content-Disposition",
       "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
    //HttpContext.Current.Response.AddHeader(
    // "content-disposition", string.Format("attachment; filename={0}", FileName));                                     
    // HttpContext.Current.Response.ContentType = FileType;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 
    HttpContext.Current.Response.ContentType = "application/ms-excel";
    HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=/text/html; charset=UTF-8/>");
    ctrl.Page.EnableViewState = false;
    StringWriter tw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(tw);
    ctrl.RenderControl(hw);
    HttpContext.Current.Response.Write(tw.ToString());
    HttpContext.Current.Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{

}


protected void btncancel_Click(object sender, EventArgs e)
{
    Response.Redirect("content.aspx");
}
  • 写回答

2条回答 默认 最新

  • 白萝卜。 2017-09-14 10:08
    关注

    这就是转码的问题,下面是答案。
    https://q.cnblogs.com/q/60881/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况