changwen313
2017-08-22 08:46
采纳率: 50%
浏览 1.2k
已采纳

.net gridview导出成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 = "GB2312";
    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//注意编码
    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=GB2312/>");
    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();
}
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • 已采纳

    StringWriter sw = new StringWriter(Encoding.UTF8);

    已采纳该答案
    打赏 评论
  • 设置下编码格式,设置成UTF-8

    打赏 评论
  • changwen313 2017-08-22 09:59

    把原来的 StringWriter tw = new StringWriter();
    改为 StringWriter tw = new StringWriter(Encoding.UTF8);吗?
    按照你这样写, new StringWriter(Encoding.UTF8)这段提示语法错误。

    打赏 评论
  • changwen313 2017-08-22 10:08

    兄弟,可以,我全改了就好了。给分。

    打赏 评论

相关推荐 更多相似问题