一般常用的方法为:
DataGrid1.DataSource = this.GetDataSource();
DataGrid1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "gb2312";
EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid1.RenderControl(hw );
Response.Write(tw.ToString());
Response.End();
但是有时导出会出现乱码,有时则不会出现乱码.真是百思不得其解.
我们可以这样解决将
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "gb2312";
换成:
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
Response.AppendHeader("content-disposition","attachment;filename=\"" + HttpUtility.UrlEncode("全部销售记录["+DateTime.Now.ToString("yyyy-MM-dd")+"]",System.Text.Encoding.UTF8) + ".xls\"");
为什么直接输出到Excel会出现乱码,而用Excel打开这段Html不会出现乱码呢?暂时能解决问题但还是不明白,希望高手能给予释疑!
DataGrid1.DataSource = this.GetDataSource();
DataGrid1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "gb2312";
EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid1.RenderControl(hw );
Response.Write(tw.ToString());
Response.End();
但是有时导出会出现乱码,有时则不会出现乱码.真是百思不得其解.
我们可以这样解决将
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "gb2312";
换成:
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
Response.AppendHeader("content-disposition","attachment;filename=\"" + HttpUtility.UrlEncode("全部销售记录["+DateTime.Now.ToString("yyyy-MM-dd")+"]",System.Text.Encoding.UTF8) + ".xls\"");
为什么直接输出到Excel会出现乱码,而用Excel打开这段Html不会出现乱码呢?暂时能解决问题但还是不明白,希望高手能给予释疑!