changwen313 2017-08-22 08:46 采纳率: 100%
浏览 1250
已采纳

.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条回答 默认 最新

  • 专家-郭老师 Java领域新星创作者 2017-08-22 08:50
    关注

    StringWriter sw = new StringWriter(Encoding.UTF8);

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

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘